Data access/service class for Rock.Model.Attribute entities.
Ejemplo n.º 1
0
        /// <summary>
        /// Returns Global Attributes from cache.  If they are not already in cache, they
        /// will be read and added to cache
        /// </summary>
        /// <returns></returns>
        public static GlobalAttributesCache Read()
        {
            string cacheKey = GlobalAttributesCache.CacheKey();

            ObjectCache           cache            = MemoryCache.Default;
            GlobalAttributesCache globalAttributes = cache[cacheKey] as GlobalAttributesCache;

            if (globalAttributes != null)
            {
                return(globalAttributes);
            }
            else
            {
                globalAttributes                 = new GlobalAttributesCache();
                globalAttributes.Attributes      = new List <AttributeCache>();
                globalAttributes.AttributeValues = new Dictionary <string, KeyValuePair <string, string> >();

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

                foreach (Rock.Model.Attribute attribute in attributeService.GetGlobalAttributes())
                {
                    var attributeCache = AttributeCache.Read(attribute);
                    globalAttributes.Attributes.Add(attributeCache);

                    var    attributeValue = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, null).FirstOrDefault();
                    string value          = (attributeValue != null && !string.IsNullOrEmpty(attributeValue.Value)) ? attributeValue.Value : attributeCache.DefaultValue;
                    globalAttributes.AttributeValues.Add(attributeCache.Key, new KeyValuePair <string, string>(attributeCache.Name, value));
                }

                cache.Set(cacheKey, globalAttributes, new CacheItemPolicy());

                return(globalAttributes);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns Attribute object from cache.  If attribute does not already exist in cache, it
        /// will be read and added to cache
        /// </summary>
        /// <param name="id">The id of the Attribute to read</param>
        /// <returns></returns>
        public static AttributeCache Read(int id)
        {
            string cacheKey = AttributeCache.CacheKey(id);

            ObjectCache    cache     = MemoryCache.Default;
            AttributeCache attribute = cache[cacheKey] as AttributeCache;

            if (attribute != null)
            {
                return(attribute);
            }
            else
            {
                var attributeService = new Rock.Model.AttributeService();
                var attributeModel   = attributeService.Get(id);
                if (attributeModel != null)
                {
                    attribute = new AttributeCache(attributeModel);
                    cache.Set(cacheKey, attribute, new CacheItemPolicy());
                    return(attribute);
                }
                else
                {
                    return(null);
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Returns Global Attributes from cache.  If they are not already in cache, they
        /// will be read and added to cache
        /// </summary>
        /// <returns></returns>
        private static SystemSettings Read()
        {
            string cacheKey = SystemSettings.CacheKey();

            RockMemoryCache cache          = RockMemoryCache.Default;
            SystemSettings  systemSettings = cache[cacheKey] as SystemSettings;

            if (systemSettings != null)
            {
                return(systemSettings);
            }
            else
            {
                systemSettings            = new SystemSettings();
                systemSettings.Attributes = new List <AttributeCache>();

                var rockContext      = new RockContext();
                var attributeService = new Rock.Model.AttributeService(rockContext);

                foreach (Rock.Model.Attribute attribute in attributeService.GetSystemSettings())
                {
                    var attributeCache = AttributeCache.Read(attribute);
                    systemSettings.Attributes.Add(attributeCache);
                }

                cache.Set(cacheKey, systemSettings, new CacheItemPolicy());

                return(systemSettings);
            }
        }
    public IHttpActionResult Get(int seriesId)
    {
        var rockContext = new RockContext();

        var contentItemService = new ContentChannelService(rockContext);
        var d = new DotLiquid.Context();
        ContentChannel contentItem = null;

        var attrService = new AttributeService(rockContext);

        var dailyItems = new List<MessageArchiveItem>();

        var ids = rockContext.Database.SqlQuery<int>("exec GetMessageArchivesBySeriesId @seriesId", new SqlParameter("seriesId", seriesId)).ToList();

        contentItem = contentItemService.Get(11);

        var items = contentItem.Items.Where(a => ids.Contains(a.Id)).ToList();

        foreach (var item in items)
        {

            item.LoadAttributes(rockContext);

            var link = GetVimeoLink(item.GetAttributeValue("VideoId"));

            var newItem = new MessageArchiveItem();

            newItem.Id = item.Id;

            //   newItem.Content = item.Content;

            newItem.Content = DotLiquid.StandardFilters.StripHtml(item.Content).Replace("\n\n", "\r\n\r\n");

            newItem.Date = DateTime.Parse(item.GetAttributeValue("Date")).ToShortDateString();
            newItem.Speaker = item.GetAttributeValue("Speaker");
            newItem.SpeakerTitle = item.GetAttributeValue("SpeakerTitle");
            newItem.Title = item.Title;
            newItem.VimeoLink = link;

            var notesAttr = item.Attributes["MessageNotes"];

            var binaryFile = new BinaryFileService(new RockContext()).Get(notesAttr.Id);

            if (binaryFile != null)
                newItem.Notes = binaryFile.Url;

            var talkAttr = item.Attributes["TalkItOver"];
            binaryFile = new BinaryFileService(new RockContext()).Get(talkAttr.Id);
            if (binaryFile != null)
                newItem.TalkItOver = binaryFile.Url;

            dailyItems.Add(newItem);
        }

        return Ok(dailyItems.AsQueryable());
    }
Ejemplo n.º 5
0
        private static AttributeCache LoadById2(int id, RockContext rockContext)
        {
            var attributeService = new Rock.Model.AttributeService(rockContext);
            var attributeModel   = attributeService.Get(id);

            if (attributeModel != null)
            {
                return(new AttributeCache(attributeModel));
            }

            return(null);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Handles the Delete event of the rGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGrid_Delete(object sender, RowEventArgs e)
        {
            var attributeService = new Rock.Model.AttributeService();

            Rock.Model.Attribute attribute = attributeService.Get((int)rGrid.DataKeys[e.RowIndex]["id"]);
            if (attribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(attribute.Id);

                attributeService.Delete(attribute, CurrentPersonId);
                attributeService.Save(attribute, CurrentPersonId);
            }

            BindGrid();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Maps the activity ministry.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <returns></returns>
        private void MapActivityMinistry( IQueryable<Row> tableData )
        {
            int groupEntityTypeId = EntityTypeCache.Read( "Rock.Model.Group" ).Id;
            var attributeService = new AttributeService();

            // Add an Attribute for the unique F1 Ministry Id
            var ministryAttributeId = attributeService.Queryable().Where( a => a.EntityTypeId == groupEntityTypeId
                && a.Key == "F1MinistryId" ).Select( a => a.Id ).FirstOrDefault();
            if ( ministryAttributeId == 0 )
            {
                var newMinistryAttribute = new Rock.Model.Attribute();
                newMinistryAttribute.Key = "F1MinistryId";
                newMinistryAttribute.Name = "F1 Ministry Id";
                newMinistryAttribute.FieldTypeId = IntegerFieldTypeId;
                newMinistryAttribute.EntityTypeId = groupEntityTypeId;
                newMinistryAttribute.EntityTypeQualifierValue = string.Empty;
                newMinistryAttribute.EntityTypeQualifierColumn = string.Empty;
                newMinistryAttribute.Description = "The FellowshipOne identifier for the ministry that was imported";
                newMinistryAttribute.DefaultValue = string.Empty;
                newMinistryAttribute.IsMultiValue = false;
                newMinistryAttribute.IsRequired = false;
                newMinistryAttribute.Order = 0;

                attributeService.Add( newMinistryAttribute, ImportPersonAlias );
                attributeService.Save( newMinistryAttribute, ImportPersonAlias );
                ministryAttributeId = newMinistryAttribute.Id;
            }

            // Get previously imported Ministries
            var importedMinistries = new AttributeValueService().GetByAttributeId( ministryAttributeId )
                .Select( av => new { RLCId = av.Value.AsType<int?>(), LocationId = av.EntityId } )
                .ToDictionary( t => t.RLCId, t => t.LocationId );

            foreach ( var row in tableData )
            {
                int? ministryId = row["Ministry_ID"] as int?;
                if ( ministryId != null && !importedMinistries.ContainsKey( ministryId ) )
                {
                    // Activity_ID
                    // Ministry_Name
                    // Activity_Name
                    // Ministry_Active
                    // Activity_Active
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Handles the Delete event of the rGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGrid_Delete(object sender, RowEventArgs e)
        {
            var rockContext      = new RockContext();
            var attributeService = new Rock.Model.AttributeService(rockContext);

            Rock.Model.Attribute attribute = attributeService.Get((int)rGrid.DataKeys[e.RowIndex]["id"]);
            if (attribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(attribute.Id);

                attributeService.Delete(attribute);

                rockContext.SaveChanges();
            }

            BindGrid();
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Returns a <see cref="Rock.Model.Person"/> user preference value by preference setting's key.
        /// </summary>
        /// <param name="person">The <see cref="Rock.Model.Person"/> to retrieve the preference value for.</param>
        /// <param name="key">A <see cref="System.String"/> representing the key name of the preference setting.</param>
        /// <returns>A list of <see cref="System.String"/> containing the values associated with the user's preference setting.</returns>
        public static List<string> GetUserPreference( Person person, string key )
        {
            int? PersonEntityTypeId = Rock.Web.Cache.EntityTypeCache.Read( Person.USER_VALUE_ENTITY ).Id;

            var rockContext = new Rock.Data.RockContext();
            var attributeService = new Model.AttributeService( rockContext );
            var attribute = attributeService.Get( PersonEntityTypeId, string.Empty, string.Empty, key );

            if (attribute != null)
            {
                var attributeValueService = new Model.AttributeValueService( rockContext );
                var attributeValues = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, person.Id);
                if (attributeValues != null && attributeValues.Count() > 0)
                    return attributeValues.Select( v => v.Value).ToList();
            }

            return null;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Handles the Delete event of the rGrid control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void rGrid_Delete(object sender, RowEventArgs e)
        {
            var rockContext      = new RockContext();
            var attributeService = new Rock.Model.AttributeService(rockContext);

            Rock.Model.Attribute attribute = attributeService.Get(e.RowKeyId);
            if (attribute != null)
            {
                Rock.Web.Cache.AttributeCache.Flush(attribute.Id);

                attributeService.Delete(attribute);

                rockContext.SaveChanges();
            }

            AttributeCache.FlushEntityAttributes();

            BindGrid();
        }
Ejemplo n.º 11
0
    public List<int> Test()
    {
        var rockContext = new RockContext();

        var contentItemService = new ContentChannelService(rockContext);
        var d = new DotLiquid.Context();
        ContentChannel contentItem = null;

        var attrService = new AttributeService(rockContext);

        var dailyItems = new List<int>();

        contentItem = contentItemService.Get(20);
        var items = contentItem.Items.Where(a => a.StartDateTime < DateTime.Now).OrderByDescending(i=>i.Id);

        foreach (var i in contentItem.Items)
        {
            dailyItems.Add(i.Id);
        }

        return dailyItems;
    }
Ejemplo n.º 12
0
    public TheDailyItem GetDailyItem(int id)
    {
        var rockContext = new RockContext();

        var contentItemService = new ContentChannelItemService(rockContext);

        ContentChannelItem i = null;

        var attrService = new AttributeService(rockContext);

        var dailyItem = new  TheDailyItem();

        i = contentItemService.Get(id);

        if (i != null)
        {
            i.LoadAttributes();

            i.Content = DotLiquid.StandardFilters.StripHtml(i.Content).Replace("\n\n", "\r\n\r\n");

            var attributes = i.Attributes;

            var pdfAttr = i.Attributes["PDF"];

            var binaryFile = new BinaryFileService(new RockContext()).Get(pdfAttr.Id);
            var pdfUrl = binaryFile.Url;

            var scriptureAttr = i.Attributes["ScriptureCards"];

            binaryFile = new BinaryFileService(new RockContext()).Get(scriptureAttr.Id);
            var scriptureUrl = binaryFile.Url;

            dailyItem  = (new TheDailyItem { Id = i.Id, Title = i.Title, Content = i.Content, DailyPDF = pdfUrl, ScriptiureCards = scriptureUrl });

        }

        return dailyItem;
    }
        /// <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();
            }
        }
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="location">The location.</param>
        private void ShowEditDetails( Location location )
        {
            if ( location.Id == 0 )
            {
                lReadOnlyTitle.Text = ActionTitle.Add( Location.FriendlyTypeName ).FormatAsHtmlTitle();
                hlInactive.Visible = false;
            }
            else
            {
                if ( string.IsNullOrWhiteSpace( location.Name ) )
                {
                    lReadOnlyTitle.Text = location.ToString().FormatAsHtmlTitle();
                }
                else
                {
                    lReadOnlyTitle.Text = location.Name.FormatAsHtmlTitle();
                }
            }

            SetEditMode( true );

            imgImage.BinaryFileId = location.ImageId;
            imgImage.NoPictureUrl = System.Web.VirtualPathUtility.ToAbsolute( "~/Assets/Images/no-picture.svg?" );

            tbName.Text = location.Name;
            cbIsActive.Checked = location.IsActive;
            acAddress.SetValues( location );
            ddlPrinter.SetValue( location.PrinterDeviceId );
            geopPoint.SetValue( location.GeoPoint );
            geopFence.SetValue( location.GeoFence );

            cbGeoPointLocked.Checked = location.IsGeoPointLocked ?? false;

            Guid mapStyleValueGuid = GetAttributeValue( "MapStyle" ).AsGuid();
            geopPoint.MapStyleValueGuid = mapStyleValueGuid;
            geopFence.MapStyleValueGuid = mapStyleValueGuid;

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

            ddlLocationType.BindToDefinedType( DefinedTypeCache.Read( Rock.SystemGuid.DefinedType.LOCATION_TYPE.AsGuid() ), true );

            gpParentLocation.Location = location.ParentLocation ?? locationService.Get( location.ParentLocationId ?? 0 );

            // LocationType depends on Selected ParentLocation
            if ( location.Id == 0 && ddlLocationType.Items.Count > 1 )
            {
                // if this is a new location
                ddlLocationType.SelectedIndex = 0;
            }
            else
            {
                ddlLocationType.SetValue( location.LocationTypeValueId );
            }

            location.LoadAttributes( rockContext );
            BuildAttributeEdits( location, true );
        }
        /// <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();
        }
Ejemplo n.º 16
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);
        }
        /// <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 );
        }
 /// <summary>
 /// Handles the SelectedIndexChanged event of the gtpInheritedGroupType 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 gtpInheritedGroupType_SelectedIndexChanged( object sender, EventArgs e )
 {
     var rockContext = new RockContext();
     var groupTypeService = new GroupTypeService( rockContext );
     var attributeService = new AttributeService( rockContext );
     BindInheritedAttributes( gtpInheritedGroupType.SelectedValueAsInt(), groupTypeService, attributeService );
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            BinaryFileType binaryFileType;

            var rockContext = new RockContext();
            BinaryFileTypeService binaryFileTypeService = new BinaryFileTypeService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );

            int binaryFileTypeId = int.Parse( hfBinaryFileTypeId.Value );

            if ( binaryFileTypeId == 0 )
            {
                binaryFileType = new BinaryFileType();
                binaryFileTypeService.Add( binaryFileType );
            }
            else
            {
                binaryFileType = binaryFileTypeService.Get( binaryFileTypeId );
            }

            binaryFileType.Name = tbName.Text;
            binaryFileType.Description = tbDescription.Text;
            binaryFileType.IconCssClass = tbIconCssClass.Text;
            binaryFileType.AllowCaching = cbAllowCaching.Checked;
            binaryFileType.RequiresViewSecurity = cbRequiresViewSecurity.Checked;
            binaryFileType.MaxWidth = nbMaxWidth.Text.AsInteger();
            binaryFileType.MaxHeight = nbMaxHeight.Text.AsInteger();
            binaryFileType.PreferredFormat = ddlPreferredFormat.SelectedValueAsEnum<Format>();
            binaryFileType.PreferredResolution = ddlPreferredResolution.SelectedValueAsEnum<Resolution>();
            binaryFileType.PreferredColorDepth = ddlPreferredColorDepth.SelectedValueAsEnum<ColorDepth>();
            binaryFileType.PreferredRequired = cbPreferredRequired.Checked;

            if ( !string.IsNullOrWhiteSpace( cpStorageType.SelectedValue ) )
            {
                var entityTypeService = new EntityTypeService( rockContext );
                var storageEntityType = entityTypeService.Get( new Guid( cpStorageType.SelectedValue ) );

                if ( storageEntityType != null )
                {
                    binaryFileType.StorageEntityTypeId = storageEntityType.Id;
                }
            }

            binaryFileType.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributes, binaryFileType );

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

            rockContext.WrapTransaction( () =>
            {
                rockContext.SaveChanges();

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

                /* Take care of Binary File Attributes */
                var entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( typeof( BinaryFile ) ).Id;

                // delete BinaryFileAttributes that are no longer configured in the UI
                var attributes = attributeService.Get( entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString() );
                var selectedAttributeGuids = BinaryFileAttributesState.Select( a => a.Guid );
                foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                {
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                    attributeService.Delete( attr );
                }
                rockContext.SaveChanges();

                // add/update the BinaryFileAttributes that are assigned in the UI
                foreach ( var attributeState in BinaryFileAttributesState )
                {
                    Rock.Attribute.Helper.SaveAttributeEdits( attributeState, entityTypeId, "BinaryFileTypeId", binaryFileType.Id.ToString(), rockContext );
                }

                // SaveAttributeValues for the BinaryFileType
                binaryFileType.SaveAttributeValues( rockContext );

            } );

            AttributeCache.FlushEntityAttributes();

            NavigateToParentPage();
        }
        /// <summary>
        /// Bind the data based on the configured category setting.
        /// </summary>
        private void BindData()
        {
            AttributeList = new List<int>();

            string categoryGuid = GetAttributeValue( "Category" );
            Guid guid = Guid.Empty;
            if ( Guid.TryParse( categoryGuid, out guid ) )
            {
                var category = CategoryCache.Read( guid );
                if ( category != null )
                {
                    if ( !string.IsNullOrWhiteSpace( category.IconCssClass ) )
                    {
                        lCategoryName.Text = string.Format( "<i class='{0}'></i> {1}", category.IconCssClass, category.Name );
                    }
                    else
                    {
                        lCategoryName.Text = category.Name;
                    }

                    var orderOverride = new List<int>();
                    GetAttributeValue( "AttributeOrder" ).SplitDelimitedValues().ToList().ForEach( a => orderOverride.Add( a.AsInteger() ) );

                    var orderedAttributeList = new AttributeService( new RockContext() ).GetByCategoryId( category.Id )
                        .OrderBy( a => a.Order ).ThenBy( a => a.Name ).ToList();

                    foreach ( int attributeId in orderOverride )
                    {
                        var attribute = orderedAttributeList.FirstOrDefault( a => a.Id == attributeId );
                        if ( attribute != null && attribute.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                        {
                            AttributeList.Add( attribute.Id );
                        }
                    }

                    foreach ( var attribute in orderedAttributeList.Where( a => !orderOverride.Contains( a.Id ) ) )
                    {
                        if ( attribute.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                        {
                            AttributeList.Add( attribute.Id );
                        }
                    }
                }
            }

            CreateControls( true );
        }
        /// <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 )
        {
            ParseControls( true );

            var rockContext = new RockContext();
            var service = new RegistrationTemplateService( rockContext );

            RegistrationTemplate RegistrationTemplate = null;

            int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull();
            if ( RegistrationTemplateId.HasValue )
            {
                RegistrationTemplate = service.Get( RegistrationTemplateId.Value );
            }

            bool newTemplate = false;
            if ( RegistrationTemplate == null )
            {
                newTemplate = true;
                RegistrationTemplate = new RegistrationTemplate();
            }

            RegistrationNotify notify = RegistrationNotify.None;
            foreach( ListItem li in cblNotify.Items )
            {
                if ( li.Selected )
                {
                    notify = notify | (RegistrationNotify)li.Value.AsInteger();
                }
            }

            RegistrationTemplate.IsActive = cbIsActive.Checked;
            RegistrationTemplate.Name = tbName.Text;
            RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt();
            RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId;
            RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId;
            RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();
            RegistrationTemplate.RequiredSignatureDocumentTemplateId = ddlSignatureDocumentTemplate.SelectedValueAsInt();
            RegistrationTemplate.SignatureDocumentAction = cbDisplayInLine.Checked ? SignatureDocumentAction.Embed : SignatureDocumentAction.Email;

            RegistrationTemplate.RegistrationWorkflowTypeId = wtpRegistrationWorkflow.SelectedValueAsInt();
            RegistrationTemplate.Notify = notify;
            RegistrationTemplate.AddPersonNote = cbAddPersonNote.Checked;
            RegistrationTemplate.LoginRequired = cbLoginRequired.Checked;
            RegistrationTemplate.AllowExternalRegistrationUpdates = cbAllowExternalUpdates.Checked;
            RegistrationTemplate.AllowGroupPlacement = cbAllowGroupPlacement.Checked;
            RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked;
            RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger();
            RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>();
            RegistrationTemplate.ShowCurrentFamilyMembers = cbShowCurrentFamilyMembers.Checked;
            RegistrationTemplate.SetCostOnInstance = !tglSetCostOnTemplate.Checked;
            RegistrationTemplate.Cost = cbCost.Text.AsDecimal();
            RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull();
            RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt();
            RegistrationTemplate.BatchNamePrefix = txtBatchNamePrefix.Text;

            RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text;
            RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text;
            RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text;
            RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text;

            RegistrationTemplate.ReminderFromName = tbReminderFromName.Text;
            RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text;
            RegistrationTemplate.ReminderSubject = tbReminderSubject.Text;
            RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text;

            RegistrationTemplate.PaymentReminderFromName = tbPaymentReminderFromName.Text;
            RegistrationTemplate.PaymentReminderFromEmail = tbPaymentReminderFromEmail.Text;
            RegistrationTemplate.PaymentReminderSubject = tbPaymentReminderSubject.Text;
            RegistrationTemplate.PaymentReminderEmailTemplate = cePaymentReminderEmailTemplate.Text;
            RegistrationTemplate.PaymentReminderTimeSpan = nbPaymentReminderTimeSpan.Text.AsInteger();

            RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text;
            RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text;
            RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text;
            RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text;
            RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text;
            RegistrationTemplate.SuccessText = ceSuccessText.Text;

            if ( !Page.IsValid || !RegistrationTemplate.IsValid )
            {
                return;
            }

            foreach ( var form in FormState )
            {
                if ( !form.IsValid )
                {
                    return;
                }

                if ( FormFieldsState.ContainsKey( form.Guid ) )
                {
                    foreach( var formField in FormFieldsState[ form.Guid ])
                    {
                        if ( !formField.IsValid )
                        {
                            return;
                        }
                    }
                }
            }

            // Get the valid group member attributes
            var group = new Group();
            group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
            var groupMember = new GroupMember();
            groupMember.Group = group;
            groupMember.LoadAttributes();
            var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList();

            // Remove any group member attributes that are not valid based on selected group type
            foreach( var fieldList in FormFieldsState.Select( s => s.Value ) )
            {
                foreach( var formField in fieldList
                    .Where( a =>
                        a.FieldSource == RegistrationFieldSource.GroupMemberAttribute &&
                        a.AttributeId.HasValue &&
                        !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) )
                    .ToList() )
                {
                    fieldList.Remove( formField );
                }
            }

            // Perform Validation
            var validationErrors = new List<string>();
            if ( ( ( RegistrationTemplate.SetCostOnInstance ?? false ) || RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue )
            {
                validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees or is configured to allow instances to set a cost." );
            }

            if ( validationErrors.Any() )
            {
                nbValidationError.Visible = true;
                nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>";
            }
            else
            {
                // Save the entity field changes to registration template
                if ( RegistrationTemplate.Id.Equals( 0 ) )
                {
                    service.Add( RegistrationTemplate );
                }
                rockContext.SaveChanges();

                var attributeService = new AttributeService( rockContext );
                var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext );
                var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext );
                var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext );
                var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext );
                var registrationRegistrantFeeService = new RegistrationRegistrantFeeService( rockContext );

                var groupService = new GroupService( rockContext );

                // delete forms that aren't assigned in the UI anymore
                var formUiGuids = FormState.Select( f => f.Guid ).ToList();
                foreach ( var form in registrationTemplateFormService
                    .Queryable()
                    .Where( f =>
                        f.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !formUiGuids.Contains( f.Guid ) ) )
                {
                    foreach( var formField in form.Fields.ToList() )
                    {
                        form.Fields.Remove( formField );
                        registrationTemplateFormFieldService.Delete( formField );
                    }
                    registrationTemplateFormService.Delete( form );
                }

                // delete fields that aren't assigned in the UI anymore
                var fieldUiGuids = FormFieldsState.SelectMany( a => a.Value).Select( f => f.Guid ).ToList();
                foreach ( var formField in registrationTemplateFormFieldService
                    .Queryable()
                    .Where( a =>
                        formUiGuids.Contains( a.RegistrationTemplateForm.Guid ) &&
                        !fieldUiGuids.Contains( a.Guid ) ) )
                {
                    registrationTemplateFormFieldService.Delete( formField );
                }

                // delete discounts that aren't assigned in the UI anymore
                var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList();
                foreach ( var discount in registrationTemplateDiscountService
                    .Queryable()
                    .Where( d =>
                        d.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !discountUiGuids.Contains( d.Guid ) ) )
                {
                    registrationTemplateDiscountService.Delete( discount );
                }

                // delete fees that aren't assigned in the UI anymore
                var feeUiGuids = FeeState.Select( u => u.Guid ).ToList();
                var deletedfees = registrationTemplateFeeService
                    .Queryable()
                    .Where( d =>
                        d.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !feeUiGuids.Contains( d.Guid ) )
                    .ToList();

                var deletedFeeIds = deletedfees.Select( f => f.Id ).ToList();
                foreach ( var registrantFee in registrationRegistrantFeeService
                    .Queryable()
                    .Where( f => deletedFeeIds.Contains( f.RegistrationTemplateFeeId ) )
                    .ToList() )
                {
                    registrationRegistrantFeeService.Delete( registrantFee );
                }

                foreach ( var fee in deletedfees )
                {
                    registrationTemplateFeeService.Delete( fee );
                }

                int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id;
                var qualifierColumn = "RegistrationTemplateId";
                var qualifierValue = RegistrationTemplate.Id.ToString();

                // Get the registration attributes still in the UI
                var attributesUI = FormFieldsState
                    .SelectMany( s =>
                        s.Value.Where( a =>
                            a.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                            a.Attribute != null ) )
                    .Select( f => f.Attribute )
                    .ToList();
                var selectedAttributeGuids = attributesUI.Select( a => a.Guid );

                // Delete the registration attributes that were removed from the UI
                var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );
                foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ).ToList() )
                {
                    attributeService.Delete( attr );
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                }

                rockContext.SaveChanges();

                // Save all of the registration attributes still in the UI
                foreach ( var attr in attributesUI )
                {
                    Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                }

                // add/updated forms/fields
                foreach ( var formUI in FormState )
                {
                    var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) );
                    if ( form == null )
                    {
                        form = new RegistrationTemplateForm();
                        form.Guid = formUI.Guid;
                        RegistrationTemplate.Forms.Add( form );
                    }
                    form.Name = formUI.Name;
                    form.Order = formUI.Order;

                    if ( FormFieldsState.ContainsKey( form.Guid ) )
                    {
                        foreach ( var formFieldUI in FormFieldsState[form.Guid] )
                        {
                            var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) );
                            if ( formField == null )
                            {
                                formField = new RegistrationTemplateFormField();
                                formField.Guid = formFieldUI.Guid;
                                form.Fields.Add( formField );
                            }

                            formField.AttributeId = formFieldUI.AttributeId;
                            if ( !formField.AttributeId.HasValue &&
                                formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                formFieldUI.Attribute != null )
                            {
                                var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext );
                                if ( attr != null )
                                {
                                    formField.AttributeId = attr.Id;
                                }
                            }

                            formField.FieldSource = formFieldUI.FieldSource;
                            formField.PersonFieldType = formFieldUI.PersonFieldType;
                            formField.IsInternal = formFieldUI.IsInternal;
                            formField.IsSharedValue = formFieldUI.IsSharedValue;
                            formField.ShowCurrentValue = formFieldUI.ShowCurrentValue;
                            formField.PreText = formFieldUI.PreText;
                            formField.PostText = formFieldUI.PostText;
                            formField.IsGridField = formFieldUI.IsGridField;
                            formField.IsRequired = formFieldUI.IsRequired;
                            formField.Order = formFieldUI.Order;
                        }
                    }
                }

                // add/updated discounts
                foreach ( var discountUI in DiscountState )
                {
                    var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) );
                    if ( discount == null )
                    {
                        discount = new RegistrationTemplateDiscount();
                        discount.Guid = discountUI.Guid;
                        RegistrationTemplate.Discounts.Add( discount );
                    }
                    discount.Code = discountUI.Code;
                    discount.DiscountPercentage = discountUI.DiscountPercentage;
                    discount.DiscountAmount = discountUI.DiscountAmount;
                    discount.Order = discountUI.Order;
                }

                // add/updated fees
                foreach ( var feeUI in FeeState )
                {
                    var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) );
                    if ( fee == null )
                    {
                        fee = new RegistrationTemplateFee();
                        fee.Guid = feeUI.Guid;
                        RegistrationTemplate.Fees.Add( fee );
                    }
                    fee.Name = feeUI.Name;
                    fee.FeeType = feeUI.FeeType;
                    fee.CostValue = feeUI.CostValue;
                    fee.DiscountApplies = feeUI.DiscountApplies;
                    fee.AllowMultiple = feeUI.AllowMultiple;
                    fee.Order = feeUI.Order;
                }

                rockContext.SaveChanges();

                AttributeCache.FlushEntityAttributes();

                // If this is a new template, give the current user and the Registration Administrators role administrative
                // rights to this template, and staff, and staff like roles edit rights
                if ( newTemplate )
                {
                    RegistrationTemplate.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext );

                    var registrationAdmins = groupService.Get( Rock.SystemGuid.Group.GROUP_EVENT_REGISTRATION_ADMINISTRATORS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.ADMINISTRATE, registrationAdmins, rockContext );

                    var staffLikeUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_LIKE_MEMBERS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffLikeUsers, rockContext );

                    var staffUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_MEMBERS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffUsers, rockContext );
                }

                var qryParams = new Dictionary<string, string>();
                qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
Ejemplo n.º 22
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>>();
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Device Device = null;

            var rockContext = new RockContext();
            var deviceService = new DeviceService( rockContext );
            var attributeService = new AttributeService( rockContext );
            var locationService = new LocationService( rockContext );

            int DeviceId = int.Parse( hfDeviceId.Value );

            if ( DeviceId != 0 )
            {
                Device = deviceService.Get( DeviceId );
            }

            if ( Device == null )
            {
                // Check for existing
                var existingDevice = deviceService.Queryable()
                    .Where( d => d.Name == tbName.Text )
                    .FirstOrDefault();
                if ( existingDevice != null )
                {
                    nbDuplicateDevice.Text = string.Format( "A device already exists with the name '{0}'. Please use a different device name.", existingDevice.Name );
                    nbDuplicateDevice.Visible = true;
                }
                else
                {
                    Device = new Device();
                    deviceService.Add( Device );
                }
            }

            if ( Device != null )
            {
                Device.Name = tbName.Text;
                Device.Description = tbDescription.Text;
                Device.IPAddress = tbIpAddress.Text;
                Device.DeviceTypeValueId = ddlDeviceType.SelectedValueAsInt().Value;
                Device.PrintToOverride = (PrintTo)System.Enum.Parse( typeof( PrintTo ), ddlPrintTo.SelectedValue );
                Device.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();
                Device.PrintFrom = (PrintFrom)System.Enum.Parse( typeof( PrintFrom ), ddlPrintFrom.SelectedValue );

                if ( Device.Location == null )
                {
                    Device.Location = new Location();
                }
                Device.Location.GeoPoint = geopPoint.SelectedValue;
                Device.Location.GeoFence = geopFence.SelectedValue;

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

                // Remove any deleted locations
                foreach ( var location in Device.Locations
                    .Where( l =>
                        !Locations.Keys.Contains( l.Id ) )
                    .ToList() )
                {
                    Device.Locations.Remove( location );
                }

                // Add any new locations
                var existingLocationIDs = Device.Locations.Select( l => l.Id ).ToList();
                foreach ( var location in locationService.Queryable()
                    .Where( l =>
                        Locations.Keys.Contains( l.Id ) &&
                        !existingLocationIDs.Contains( l.Id ) ) )
                {
                    Device.Locations.Add( location );
                }

                rockContext.SaveChanges();

                Rock.CheckIn.KioskDevice.Flush( Device.Id );

                NavigateToParentPage();
            }
        }
        /// <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>
        /// Adds or update group member's attributes using any page parameters that are attributes of the group.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="group">The group.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddOrUpdateGroupMemberAttributes( Person person, Group group, RockContext rockContext )
        {
            var groupMember = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault();
            AttributeService attributeService = new AttributeService( rockContext );

            // Load all the group member attributes for comparison below.
            var attributes = attributeService.GetGroupMemberAttributesCombined( group.Id, group.GroupTypeId );

            // In order to add attributes to the person, you have to first load them all
            groupMember.LoadAttributes( rockContext );

            foreach ( var entry in PageParameters() )
            {
                // skip the parameter if the group's group type doesn't have that one
                var attribute = attributes.Where( a => a.Key.Equals( entry.Key, StringComparison.OrdinalIgnoreCase ) ).FirstOrDefault();
                if ( attribute == null )
                {
                    continue;
                }
                //attribute.SetAttributeValue
                groupMember.SetAttributeValue( entry.Key, (string) entry.Value );

            }
            groupMember.SaveAttributeValues( rockContext );
        }
        /// <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 )
        {
            GroupType groupType;
            var rockContext = new RockContext();
            GroupTypeService groupTypeService = new GroupTypeService( rockContext );
            GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext );
            CategoryService categoryService = new CategoryService( rockContext );
            GroupScheduleExclusionService scheduleExclusionService = new GroupScheduleExclusionService( rockContext );

            int groupTypeId = int.Parse( hfGroupTypeId.Value );

            if ( groupTypeId == 0 )
            {
                groupType = new GroupType();
                groupTypeService.Add( groupType );
            }
            else
            {
                groupType = groupTypeService.Get( groupTypeId );

                // selected roles
                var selectedRoleGuids = GroupTypeRolesState.Select( r => r.Guid );
                foreach ( var role in groupType.Roles.Where( r => !selectedRoleGuids.Contains( r.Guid ) ).ToList() )
                {
                    groupType.Roles.Remove( role );
                    groupTypeRoleService.Delete( role );
                }
            }

            foreach ( var roleState in GroupTypeRolesState )
            {
                GroupTypeRole role = groupType.Roles.Where( r => r.Guid == roleState.Guid ).FirstOrDefault();
                if ( role == null )
                {
                    role = new GroupTypeRole();
                    groupType.Roles.Add( role );
                }
                else
                {
                    roleState.Id = role.Id;
                    roleState.Guid = role.Guid;
                }

                role.CopyPropertiesFrom( roleState );
            }

            ScheduleType allowedScheduleTypes = ScheduleType.None;
            foreach( ListItem li in cblScheduleTypes.Items )
            {
                if ( li.Selected )
                {
                    allowedScheduleTypes = allowedScheduleTypes | (ScheduleType)li.Value.AsInteger();
                }
            }

            GroupLocationPickerMode locationSelectionMode = GroupLocationPickerMode.None;
            foreach ( ListItem li in cblLocationSelectionModes.Items )
            {
                if ( li.Selected )
                {
                    locationSelectionMode = locationSelectionMode | (GroupLocationPickerMode)li.Value.AsInteger();
                }
            }

            groupType.Name = tbName.Text;
            groupType.Description = tbDescription.Text;
            groupType.GroupTerm = tbGroupTerm.Text;
            groupType.GroupMemberTerm = tbGroupMemberTerm.Text;
            groupType.ShowInGroupList = cbShowInGroupList.Checked;
            groupType.ShowInNavigation = cbShowInNavigation.Checked;
            groupType.IconCssClass = tbIconCssClass.Text;
            groupType.TakesAttendance = cbTakesAttendance.Checked;
            groupType.SendAttendanceReminder = cbSendAttendanceReminder.Checked;
            groupType.AttendanceRule = ddlAttendanceRule.SelectedValueAsEnum<AttendanceRule>();
            groupType.AttendancePrintTo = ddlPrintTo.SelectedValueAsEnum<PrintTo>();
            groupType.AllowedScheduleTypes = allowedScheduleTypes;
            groupType.LocationSelectionMode = locationSelectionMode;
            groupType.GroupTypePurposeValueId = ddlGroupTypePurpose.SelectedValueAsInt();
            groupType.AllowMultipleLocations = cbAllowMultipleLocations.Checked;
            groupType.InheritedGroupTypeId = gtpInheritedGroupType.SelectedGroupTypeId;
            groupType.EnableLocationSchedules = cbEnableLocationSchedules.Checked;

            groupType.ChildGroupTypes = new List<GroupType>();
            groupType.ChildGroupTypes.Clear();
            foreach ( var item in ChildGroupTypesDictionary )
            {
                var childGroupType = groupTypeService.Get( item.Key );
                if ( childGroupType != null )
                {
                    groupType.ChildGroupTypes.Add( childGroupType );
                }
            }

            // Delete any removed exclusions
            foreach ( var exclusion in groupType.GroupScheduleExclusions.Where( s => !ScheduleExclusionDictionary.Keys.Contains( s.Guid ) ).ToList() )
            {
                groupType.GroupScheduleExclusions.Remove( exclusion );
                scheduleExclusionService.Delete( exclusion );
            }

            // Update exclusions
            foreach( var keyVal in ScheduleExclusionDictionary )
            {
                var scheduleExclusion = groupType.GroupScheduleExclusions
                    .FirstOrDefault( s => s.Guid.Equals( keyVal.Key));
                if ( scheduleExclusion == null )
                {
                    scheduleExclusion = new GroupScheduleExclusion();
                    groupType.GroupScheduleExclusions.Add( scheduleExclusion);
                }

                scheduleExclusion.StartDate = keyVal.Value.Start;
                scheduleExclusion.EndDate = keyVal.Value.End;
            }

            DefinedValueService definedValueService = new DefinedValueService( rockContext );

            groupType.LocationTypes = new List<GroupTypeLocationType>();
            groupType.LocationTypes.Clear();
            foreach ( var item in LocationTypesDictionary )
            {
                var locationType = definedValueService.Get( item.Key );
                if ( locationType != null )
                {
                    groupType.LocationTypes.Add( new GroupTypeLocationType { LocationTypeValueId = locationType.Id } );
                }
            }

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

            // need WrapTransaction due to Attribute saves
            rockContext.WrapTransaction( () =>
            {
                rockContext.SaveChanges();

                /* Save Attributes */
                string qualifierValue = groupType.Id.ToString();
                SaveAttributes( new GroupType().TypeId, "Id", qualifierValue, GroupTypeAttributesState, rockContext );
                SaveAttributes( new Group().TypeId, "GroupTypeId", qualifierValue, GroupAttributesState, rockContext );
                SaveAttributes( new GroupMember().TypeId, "GroupTypeId", qualifierValue, GroupMemberAttributesState, rockContext );

                // Reload to save default role
                groupType = groupTypeService.Get( groupType.Id );
                groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault( r => r.Guid.Equals( DefaultRoleGuid ) );
                if ( groupType.DefaultGroupRole == null )
                {
                    groupType.DefaultGroupRole = groupType.Roles.FirstOrDefault();
                }

                rockContext.SaveChanges();

                // Reload the roles and apply their attribute values
                foreach ( var role in groupTypeRoleService.GetByGroupTypeId( groupType.Id ).ToList() )
                {
                    role.LoadAttributes( rockContext );
                    var roleState = GroupTypeRolesState.Where( r => r.Guid.Equals( role.Guid ) ).FirstOrDefault();
                    if ( roleState != null && roleState.AttributeValues != null )
                    {
                        foreach ( var attributeValue in roleState.AttributeValues )
                        {
                            role.SetAttributeValue( attributeValue.Key, roleState.GetAttributeValue( attributeValue.Key ) );
                        }

                        role.SaveAttributeValues( rockContext );
                    }
                }
            } );

            GroupTypeCache.Flush( groupType.Id );

            NavigateToParentPage();
        }
Ejemplo n.º 27
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>
        public static void LoadAttributes(Rock.Attribute.IHasAttributes entity, RockContext rockContext)
        {
            if (entity != 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)
                                    .Queryable().AsNoTracking().FirstOrDefault(g => g.Id == ((GroupMember)entity).GroupId);
                        if (group != null)
                        {
                            groupType = group.GroupType ?? groupTypeService
                                        .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == group.GroupTypeId);
                        }
                    }
                    else if (entity is Group)
                    {
                        groupType = ((Group)entity).GroupType ?? groupTypeService
                                    .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == ((Group)entity).GroupTypeId);
                    }
                    else
                    {
                        groupType = ((GroupType)entity);
                    }

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

                        // Check for inherited group type id's
                        if (groupType.InheritedGroupTypeId.HasValue)
                        {
                            groupType = groupType.InheritedGroupType ?? groupTypeService
                                        .Queryable().AsNoTracking().FirstOrDefault(t => t.Id == (groupType.InheritedGroupTypeId ?? 0));
                        }
                        else
                        {
                            groupType = null;
                        }
                    }
                }

                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
                var entityTypeCache = Rock.Web.Cache.EntityTypeCache.Read(entityType);
                if (entityTypeCache != null)
                {
                    int entityTypeId = entityTypeCache.Id;
                    foreach (var attribute in attributeService.Queryable()
                             .AsNoTracking()
                             .Where(a => a.EntityTypeId == entityTypeCache.Id)
                             .Select(a => new
                    {
                        a.Id,
                        a.EntityTypeQualifierColumn,
                        a.EntityTypeQualifierValue
                    }
                                     ))
                    {
                        // 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.Id));
                            }
                        }

                        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.Id));
                        }
                    }
                }

                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, 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, null);
                    }

                    // If loading attributes for a saved item, read the item's value(s) for each attribute
                    if (!entityTypeCache.IsEntity || entity.Id != 0)
                    {
                        List <int> attributeIds = allAttributes.Select(a => a.Id).ToList();
                        foreach (var attributeValue in attributeValueService.Queryable().AsNoTracking()
                                 .Where(v => v.EntityId == entity.Id && attributeIds.Contains(v.AttributeId)))
                        {
                            var attributeKey = AttributeCache.Read(attributeValue.AttributeId).Key;
                            attributeValues[attributeKey] = 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] == null)
                        {
                            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] = attributeValue;
                        }
                        else
                        {
                            if (!String.IsNullOrWhiteSpace(attribute.DefaultValue) &&
                                String.IsNullOrWhiteSpace(attributeValues[attribute.Key].Value))
                            {
                                attributeValues[attribute.Key].Value = attribute.DefaultValue;
                            }
                        }
                    }
                }

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

                entity.AttributeValues = attributeValues;
            }
        }
Ejemplo n.º 28
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;
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Loads the cache objects.
        /// </summary>
        private void LoadCacheObjects(RockContext rockContext)
        {
            // Cache all the entity types
            foreach (var entityType in new Rock.Model.EntityTypeService(rockContext).Queryable().AsNoTracking())
            {
                EntityTypeCache.Read(entityType);
            }

            // Cache all the Field Types
            foreach (var fieldType in new Rock.Model.FieldTypeService(rockContext).Queryable().AsNoTracking())
            {
                Rock.Web.Cache.FieldTypeCache.Read(fieldType);
            }

            var all = Rock.Web.Cache.FieldTypeCache.All();

            // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached
            var qualifiers = new Dictionary <int, Dictionary <string, string> >();

            foreach (var attributeQualifier in new Rock.Model.AttributeQualifierService(rockContext).Queryable().AsNoTracking())
            {
                try
                {
                    if (!qualifiers.ContainsKey(attributeQualifier.AttributeId))
                    {
                        qualifiers.Add(attributeQualifier.AttributeId, new Dictionary <string, string>());
                    }

                    qualifiers[attributeQualifier.AttributeId].Add(attributeQualifier.Key, attributeQualifier.Value);
                }
                catch (Exception ex)
                {
                    LogError(ex, null);
                }
            }

            // Cache all the attributes, except for user preferences

            var attributeQuery = new Rock.Model.AttributeService(rockContext).Queryable("Categories");
            int?personUserValueEntityTypeId = Rock.Web.Cache.EntityTypeCache.GetId(Person.USER_VALUE_ENTITY);

            if (personUserValueEntityTypeId.HasValue)
            {
                attributeQuery = attributeQuery.Where(a => !a.EntityTypeId.HasValue || a.EntityTypeId.Value != personUserValueEntityTypeId);
            }

            foreach (var attribute in attributeQuery.AsNoTracking().ToList())
            {
                if (qualifiers.ContainsKey(attribute.Id))
                {
                    Rock.Web.Cache.AttributeCache.Read(attribute, qualifiers[attribute.Id]);
                }
                else
                {
                    Rock.Web.Cache.AttributeCache.Read(attribute, new Dictionary <string, string>());
                }
            }

            // cache all the Country Defined Values since those can be loaded in just a few millisecond here, but take around 1-2 seconds if first loaded when formatting an address
            foreach (var definedValue in new Rock.Model.DefinedValueService(rockContext).GetByDefinedTypeGuid(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid()).AsNoTracking())
            {
                DefinedValueCache.Read(definedValue, rockContext);
            }
        }
        /// <summary>
        /// Handles the SaveClick event of the dlgField 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 dlgField_SaveClick( object sender, EventArgs e )
        {
            var formGuid = hfFormGuid.Value.AsGuid();
            var attributeGuid = hfAttributeGuid.Value.AsGuid();

            if ( FormFieldsState.ContainsKey( formGuid ) )
            {
                var attributeForm = FormFieldsState[formGuid].FirstOrDefault( a => a.Guid.Equals( attributeGuid ) );
                if ( attributeForm == null )
                {
                    attributeForm = new RegistrationTemplateFormField();
                    attributeForm.Order = FormFieldsState[formGuid].Any() ? FormFieldsState[formGuid].Max( a => a.Order ) + 1 : 0;
                    attributeForm.Guid = attributeGuid;
                    FormFieldsState[formGuid].Add( attributeForm );
                }

                attributeForm.PreText = ceAttributePreText.Text;
                attributeForm.PostText = ceAttributePostText.Text;
                attributeForm.FieldSource = ddlFieldSource.SelectedValueAsEnum<RegistrationFieldSource>();
                if ( ddlPersonField.Visible )
                {
                    attributeForm.PersonFieldType = ddlPersonField.SelectedValueAsEnum<RegistrationPersonFieldType>();
                }

                attributeForm.IsInternal = cbInternalField.Checked;
                attributeForm.IsSharedValue = cbCommonValue.Checked;

                int? attributeId = null;

                switch ( attributeForm.FieldSource )
                {
                    case RegistrationFieldSource.PersonField:
                        {
                            attributeForm.ShowCurrentValue = cbUsePersonCurrentValue.Checked;
                            attributeForm.IsGridField = cbShowOnGrid.Checked;
                            attributeForm.IsRequired = cbRequireInInitialEntry.Checked;
                            break;
                        }
                    case RegistrationFieldSource.PersonAttribute:
                        {
                            attributeId = ddlPersonAttributes.SelectedValueAsInt();
                            attributeForm.ShowCurrentValue = cbUsePersonCurrentValue.Checked;
                            attributeForm.IsGridField = cbShowOnGrid.Checked;
                            attributeForm.IsRequired = cbRequireInInitialEntry.Checked;
                            break;
                        }
                    case RegistrationFieldSource.GroupMemberAttribute:
                        {
                            attributeId = ddlGroupTypeAttributes.SelectedValueAsInt();
                            attributeForm.ShowCurrentValue = false;
                            attributeForm.IsGridField = cbShowOnGrid.Checked;
                            attributeForm.IsRequired = cbRequireInInitialEntry.Checked;
                            break;
                        }
                    case RegistrationFieldSource.RegistrationAttribute:
                        {
                            Rock.Model.Attribute attribute = new Rock.Model.Attribute();
                            edtRegistrationAttribute.GetAttributeProperties( attribute );
                            attributeForm.Attribute = attribute;
                            attributeForm.Id = attribute.Id;
                            attributeForm.ShowCurrentValue = false;
                            attributeForm.IsGridField = attribute.IsGridColumn;
                            attributeForm.IsRequired = attribute.IsRequired;
                            break;
                        }
                }

                if ( attributeId.HasValue )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        var attribute = new AttributeService( rockContext ).Get( attributeId.Value );
                        if ( attribute != null )
                        {
                            attributeForm.Attribute = attribute.Clone( false );
                            attributeForm.Attribute.FieldType = attribute.FieldType.Clone( false );
                            attributeForm.AttributeId = attribute.Id;
                        }
                    }
                }
            }

            HideDialog();

            BuildControls( true );
        }
        private void BuildAttributes( RockContext rockContext, bool setValues = false )
        {
            var selectedCategories = new List<CategoryCache>();
            foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
            {
                var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                if ( category != null )
                {
                    selectedCategories.Add( category );
                }
            }

            int categoryIndex = 0;
            foreach( var category in selectedCategories.OrderBy( c => c.Name ) )
            {
                var pw = new PanelWidget();
                if ( categoryIndex % 2 == 0)
                {
                    phAttributesCol1.Controls.Add( pw );
                }
                else
                {
                    phAttributesCol2.Controls.Add( pw );
                }
                pw.ID = "pwAttributes_" + category.Id.ToString();
                categoryIndex++;

                if ( !string.IsNullOrWhiteSpace( category.IconCssClass ) )
                {
                    pw.TitleIconCssClass = category.IconCssClass;
                }
                pw.Title = category.Name;

                var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                    .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                foreach ( var attribute in orderedAttributeList )
                {
                    if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                    {
                        var attributeCache = AttributeCache.Read( attribute.Id );

                        string clientId = string.Format( "{0}_attribute_field_{1}", pw.ClientID, attribute.Id );
                        bool controlEnabled = SelectedFields.Contains( clientId, StringComparer.OrdinalIgnoreCase );
                        string iconCss = controlEnabled ? "fa-check-circle-o" : "fa-circle-o";

                        string labelText = string.Format( "<span class='js-select-item'><i class='fa {0}'></i></span> {1}", iconCss, attributeCache.Name );
                        Control control = attributeCache.AddControl( pw.Controls, string.Empty, string.Empty, setValues, true, false, labelText );

                        if ( !( control is RockCheckBox ) )
                        {
                            var webControl = control as WebControl;
                            if ( webControl != null )
                            {
                                webControl.Enabled = controlEnabled;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Gets the entity fields.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="includeOnlyReportingFields">if set to <c>true</c> [include only reporting fields].</param>
        /// <param name="limitToFilterableFields">if set to <c>true</c> [limit to filterable fields].</param>
        /// <returns></returns>
        public static List<EntityField> GetEntityFields( Type entityType, bool includeOnlyReportingFields = true, bool limitToFilterableFields = true )
        {
            List<EntityField> entityFields = null;
            _workflowTypeNameLookup = null;

            if ( HttpContext.Current != null )
            {
                entityFields = HttpContext.Current.Items[EntityHelper.GetCacheKey(entityType, includeOnlyReportingFields, limitToFilterableFields)] as List<EntityField>;
                if ( entityFields != null )
                {
                    return entityFields;
                }
            }

            if ( entityFields == null )
            {
                entityFields = new List<EntityField>();
            }

            // Find all non-virtual properties or properties that have the [IncludeForReporting] attribute
            var entityProperties = entityType.GetProperties().ToList();
            var filteredEntityProperties = entityProperties
                .Where( p =>
                    !p.GetGetMethod().IsVirtual ||
                    p.GetCustomAttributes( typeof( IncludeForReportingAttribute ), true ).Any() ||
                    p.Name == "Order" )
                .ToList();

            // Get Properties
            foreach ( var property in filteredEntityProperties )
            {
                bool isReportable = !property.GetCustomAttributes( typeof( HideFromReportingAttribute ), true ).Any();
                if ( !includeOnlyReportingFields || isReportable )
                {

                    EntityField entityField = new EntityField( property.Name, FieldKind.Property, property );
                    entityField.IsPreviewable = property.GetCustomAttributes( typeof( PreviewableAttribute ), true ).Any();
                    var fieldTypeAttribute = property.GetCustomAttribute<Rock.Data.FieldTypeAttribute>();

                    // check if we can set it from the fieldTypeAttribute
                    if ( ( fieldTypeAttribute != null ) && SetEntityFieldFromFieldTypeAttribute( entityField, fieldTypeAttribute ) )
                    {
                        // intentially blank, entity field is already setup
                    }

                    // Enum Properties
                    else if ( property.PropertyType.IsEnum )
                    {
                        entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.SINGLE_SELECT.AsGuid() );

                        var list = new List<string>();
                        foreach ( var value in Enum.GetValues( property.PropertyType ) )
                        {
                            list.Add( string.Format( "{0}^{1}", value, value.ToString().SplitCase() ) );
                        }

                        var listSource = string.Join( ",", list );
                        entityField.FieldConfig.Add( "values", new Field.ConfigurationValue( listSource ) );
                        entityField.FieldConfig.Add( "fieldtype", new Field.ConfigurationValue( "rb" ) );
                    }

                    // Boolean properties
                    else if ( property.PropertyType == typeof( bool ) || property.PropertyType == typeof( bool? ) )
                    {
                        entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.BOOLEAN.AsGuid() );
                    }

                    // Datetime properties
                    else if ( property.PropertyType == typeof( DateTime ) || property.PropertyType == typeof( DateTime? ) )
                    {
                        var colAttr = property.GetCustomAttributes( typeof( ColumnAttribute ), true ).FirstOrDefault();
                        if ( colAttr != null && ( (ColumnAttribute)colAttr ).TypeName == "Date" )
                        {
                            entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.DATE.AsGuid() );
                        }
                        else
                        {
                            entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.DATE_TIME.AsGuid() );
                        }
                    }

                    // Decimal properties
                    else if ( property.PropertyType == typeof( decimal ) || property.PropertyType == typeof( decimal? ) )
                    {
                        entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.DECIMAL.AsGuid() );
                    }

                    // Text Properties
                    else if ( property.PropertyType == typeof( string ) )
                    {
                        entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.TEXT.AsGuid() );
                    }

                    // Integer Properties (which may be a DefinedValue)
                    else if ( property.PropertyType == typeof( int ) || property.PropertyType == typeof( int? ) )
                    {
                        entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.INTEGER.AsGuid() );

                        var definedValueAttribute = property.GetCustomAttribute<Rock.Data.DefinedValueAttribute>();
                        if ( definedValueAttribute != null )
                        {
                            // Defined Value Properties
                            Guid? definedTypeGuid = ( (Rock.Data.DefinedValueAttribute)definedValueAttribute ).DefinedTypeGuid;
                            if ( definedTypeGuid.HasValue )
                            {
                                var definedType = DefinedTypeCache.Read( definedTypeGuid.Value );
                                entityField.Title = definedType != null ? definedType.Name : property.Name.Replace( "ValueId", string.Empty ).SplitCase();
                                if ( definedType != null )
                                {
                                    entityField.FieldType = FieldTypeCache.Read( SystemGuid.FieldType.DEFINED_VALUE.AsGuid() );
                                    entityField.FieldConfig.Add( "definedtype", new Field.ConfigurationValue( definedType.Id.ToString() ) );
                                }
                            }
                        }
                    }

                    if ( entityField != null && entityField.FieldType != null )
                    {
                        entityFields.Add( entityField );
                    }
                }
            }

            // Get Attributes
            var entityTypeCache = EntityTypeCache.Read( entityType, true );
            if ( entityTypeCache != null )
            {
                int entityTypeId = entityTypeCache.Id;
                using ( var rockContext = new RockContext() )
                {
                    var qryAttributes = new AttributeService( rockContext ).Queryable().Where( a => a.EntityTypeId == entityTypeId );
                    if ( entityType == typeof( Group ) )
                    {
                        // in the case of Group, show attributes that are entity global, but also ones that are qualified by GroupTypeId
                        qryAttributes = qryAttributes
                            .Where( a =>
                                a.EntityTypeQualifierColumn == null ||
                                a.EntityTypeQualifierColumn == string.Empty ||
                                a.EntityTypeQualifierColumn == "GroupTypeId" );
                    }
                    else if ( entityType == typeof( ContentChannelItem ) )
                    {
                        // in the case of ContentChannelItem, show attributes that are entity global, but also ones that are qualified by ContentChannelTypeId
                        qryAttributes = qryAttributes
                            .Where( a =>
                                a.EntityTypeQualifierColumn == null ||
                                a.EntityTypeQualifierColumn == string.Empty ||
                                a.EntityTypeQualifierColumn == "ContentChannelTypeId" );
                    }
                    else if ( entityType == typeof( Rock.Model.Workflow ) )
                    {
                        // in the case of Workflow, show attributes that are entity global, but also ones that are qualified by WorkflowTypeId (and have a valid WorkflowTypeId)
                        var validWorkflowTypeIds = new WorkflowTypeService(rockContext).Queryable().Select(a=> a.Id).ToList().Select(a => a.ToString()).ToList();
                        qryAttributes = qryAttributes
                            .Where( a =>
                                a.EntityTypeQualifierColumn == null ||
                                a.EntityTypeQualifierColumn == string.Empty ||
                                (a.EntityTypeQualifierColumn == "WorkflowTypeId" && validWorkflowTypeIds.Contains(a.EntityTypeQualifierValue) ));
                    }
                    else
                    {
                        qryAttributes = qryAttributes.Where( a => a.EntityTypeQualifierColumn == string.Empty && a.EntityTypeQualifierValue == string.Empty );
                    }

                    var attributeIdList = qryAttributes.Select( a => a.Id ).ToList();

                    foreach ( var attributeId in attributeIdList )
                    {
                        AddEntityFieldForAttribute( entityFields, AttributeCache.Read( attributeId ), limitToFilterableFields );
                    }
                }
            }

            // Order the fields by title, name
            int index = 0;
            var sortedFields = new List<EntityField>();
            foreach ( var entityField in entityFields.OrderBy( p => !string.IsNullOrEmpty(p.AttributeEntityTypeQualifierName)).ThenBy( p => p.Title ).ThenBy( p => p.Name ) )
            {
                entityField.Index = index;
                index++;
                sortedFields.Add( entityField );
            }

            if ( HttpContext.Current != null )
            {
                HttpContext.Current.Items[EntityHelper.GetCacheKey( entityType, includeOnlyReportingFields, limitToFilterableFields )] = sortedFields;
            }

            return sortedFields;
        }
        /// <summary>
        /// Handles the Click event of the btnConfirm 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 btnConfirm_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var ids = Individuals.Select( i => i.PersonId ).ToList();

                #region Individual Details Updates

                int? newTitleId = ddlTitle.SelectedValueAsInt();
                int? newSuffixId = ddlSuffix.SelectedValueAsInt();
                int? newConnectionStatusId = ddlStatus.SelectedValueAsInt();
                int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                int? newInactiveReasonId = ddlInactiveReason.SelectedValueAsInt();
                string newInactiveReasonNote = tbInactiveReasonNote.Text;
                Gender newGender = ddlGender.SelectedValue.ConvertToEnum<Gender>();
                int? newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();

                int? newGraduationYear = null;
                if ( ypGraduation.SelectedYear.HasValue )
                {
                    newGraduationYear = ypGraduation.SelectedYear.Value;
                }

                int? newCampusId = cpCampus.SelectedCampusId;

                bool? newEmailActive = null;
                if ( !string.IsNullOrWhiteSpace( ddlIsEmailActive.SelectedValue ) )
                {
                    newEmailActive = ddlIsEmailActive.SelectedValue == "Active";
                }

                EmailPreference? newEmailPreference = ddlEmailPreference.SelectedValue.ConvertToEnumOrNull<EmailPreference>();

                string newEmailNote = tbEmailNote.Text;

                int? newReviewReason = ddlReviewReason.SelectedValueAsInt();
                string newSystemNote = tbSystemNote.Text;
                string newReviewReasonNote = tbReviewReasonNote.Text;

                int inactiveStatusId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ).Id;

                var allChanges = new Dictionary<int, List<string>>();

                var people = personService.Queryable().Where( p => ids.Contains( p.Id ) ).ToList();
                foreach ( var person in people )
                {
                    var changes = new List<string>();
                    allChanges.Add( person.Id, changes );

                    if ( SelectedFields.Contains( ddlTitle.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Title", DefinedValueCache.GetName( person.TitleValueId ), DefinedValueCache.GetName( newTitleId ) );
                        person.TitleValueId = newTitleId;
                    }

                    if ( SelectedFields.Contains( ddlSuffix.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Suffix", DefinedValueCache.GetName( person.SuffixValueId ), DefinedValueCache.GetName( newSuffixId ) );
                        person.SuffixValueId = newSuffixId;
                    }

                    if ( SelectedFields.Contains( ddlStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Connection Status", DefinedValueCache.GetName( person.ConnectionStatusValueId ), DefinedValueCache.GetName( newConnectionStatusId ) );
                        person.ConnectionStatusValueId = newConnectionStatusId;
                    }

                    if ( SelectedFields.Contains( ddlRecordStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( person.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) );
                        person.RecordStatusValueId = newRecordStatusId;

                        if ( newRecordStatusId.HasValue && newRecordStatusId.Value == inactiveStatusId )
                        {
                            History.EvaluateChange( changes, "Inactive Reason", DefinedValueCache.GetName( person.RecordStatusReasonValueId ), DefinedValueCache.GetName( newInactiveReasonId ) );
                            person.RecordStatusReasonValueId = newInactiveReasonId;

                            if ( !string.IsNullOrWhiteSpace( newInactiveReasonNote ) )
                            {
                                History.EvaluateChange( changes, "Inactive Reason Note", person.InactiveReasonNote, newInactiveReasonNote );
                                person.InactiveReasonNote = newInactiveReasonNote;
                            }
                        }
                    }

                    if ( SelectedFields.Contains( ddlGender.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                        person.Gender = newGender;
                    }

                    if ( SelectedFields.Contains( ddlMaritalStatus.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                        person.MaritalStatusValueId = newMaritalStatusId;
                    }

                    if ( SelectedFields.Contains( ddlGradePicker.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Graduation Year", person.GraduationYear, newGraduationYear );
                        person.GraduationYear = newGraduationYear;
                    }

                    if ( SelectedFields.Contains( ddlIsEmailActive.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Is Active", person.IsEmailActive ?? true, newEmailActive.Value );
                        person.IsEmailActive = newEmailActive;
                    }

                    if ( SelectedFields.Contains( ddlEmailPreference.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Preference", person.EmailPreference, newEmailPreference );
                        person.EmailPreference = newEmailPreference.Value;
                    }

                    if ( SelectedFields.Contains( tbEmailNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Email Note", person.EmailNote, newEmailNote );
                        person.EmailNote = newEmailNote;
                    }

                    if ( SelectedFields.Contains( tbSystemNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "System Note", person.SystemNote, newSystemNote );
                        person.SystemNote = newSystemNote;
                    }

                    if ( SelectedFields.Contains( ddlReviewReason.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason", DefinedValueCache.GetName( person.ReviewReasonValueId ), DefinedValueCache.GetName( newReviewReason ) );
                        person.ReviewReasonValueId = newReviewReason;
                    }

                    if ( SelectedFields.Contains( tbReviewReasonNote.ClientID ) )
                    {
                        History.EvaluateChange( changes, "Review Reason Note", person.ReviewReasonNote, newReviewReasonNote );
                        person.ReviewReasonNote = newReviewReasonNote;
                    }
                }

                if ( SelectedFields.Contains( cpCampus.ClientID ) && cpCampus.SelectedCampusId.HasValue )
                {
                    int campusId = cpCampus.SelectedCampusId.Value;

                    Guid familyGuid = new Guid( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );

                    var familyMembers = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => new { m.PersonId, m.GroupId } )
                        .Distinct()
                        .ToList();

                    var families = new GroupMemberService( rockContext ).Queryable()
                        .Where( m => ids.Contains( m.PersonId ) && m.Group.GroupType.Guid == familyGuid )
                        .Select( m => m.Group )
                        .Distinct()
                        .ToList();

                    foreach ( int personId in ids )
                    {
                        var familyIds = familyMembers.Where( m => m.PersonId == personId ).Select( m => m.GroupId ).ToList();
                        if ( familyIds.Count == 1 )
                        {
                            int familyId = familyIds.FirstOrDefault();
                            var family = families.Where( g => g.Id == familyId ).FirstOrDefault();
                            {
                                if ( family != null )
                                {
                                    family.CampusId = campusId;
                                }
                                familyMembers.RemoveAll( m => m.GroupId == familyId );
                            }
                        }
                    }

                    rockContext.SaveChanges();
                }

                // Update following
                if ( SelectedFields.Contains( ddlFollow.ClientID ) )
                {
                    var personAliasEntityType = EntityTypeCache.Read( "Rock.Model.PersonAlias" );
                    if ( personAliasEntityType != null )
                    {
                        int personAliasEntityTypeId = personAliasEntityType.Id;

                        bool follow = true;
                        if ( !string.IsNullOrWhiteSpace( ddlFollow.SelectedValue ) )
                        {
                            follow = ddlFollow.SelectedValue == "Add";
                        }

                        var personAliasService = new PersonAliasService( rockContext );
                        var followingService = new FollowingService( rockContext );
                        if ( follow )
                        {
                            var paQry = personAliasService.Queryable();

                            var alreadyFollowingIds = followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id )
                                .Join( paQry, f => f.EntityId, p => p.Id, ( f, p ) => new { PersonAlias = p } )
                                .Select( p => p.PersonAlias.PersonId )
                                .Distinct()
                                .ToList();

                            foreach ( int id in ids.Where( id => !alreadyFollowingIds.Contains( id ) ) )
                            {
                                var following = new Following
                                {
                                    EntityTypeId = personAliasEntityTypeId,
                                    EntityId = ( people.FirstOrDefault( p => p.Id == id ).PrimaryAliasId ) ?? 0,
                                    PersonAliasId = CurrentPersonAlias.Id
                                };
                                followingService.Add( following );
                            }
                        }
                        else
                        {
                            var paQry = personAliasService.Queryable()
                                .Where( p => ids.Contains( p.PersonId ) )
                                .Select( p => p.Id );

                            foreach ( var following in followingService.Queryable()
                                .Where( f =>
                                    f.EntityTypeId == personAliasEntityTypeId &&
                                    paQry.Contains( f.EntityId ) &&
                                    f.PersonAlias.Id == CurrentPersonAlias.Id ) )
                            {
                                followingService.Delete( following );
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                #endregion

                #region Attributes

                var selectedCategories = new List<CategoryCache>();
                foreach ( string categoryGuid in GetAttributeValue( "AttributeCategories" ).SplitDelimitedValues() )
                {
                    var category = CategoryCache.Read( categoryGuid.AsGuid(), rockContext );
                    if ( category != null )
                    {
                        selectedCategories.Add( category );
                    }
                }

                var attributes = new List<AttributeCache>();
                var attributeValues = new Dictionary<int, string>();

                int categoryIndex = 0;
                foreach ( var category in selectedCategories.OrderBy( c => c.Name ) )
                {
                    PanelWidget pw = null;
                    string controlId = "pwAttributes_" + category.Id.ToString();
                    if ( categoryIndex % 2 == 0 )
                    {
                        pw = phAttributesCol1.FindControl( controlId ) as PanelWidget;
                    }
                    else
                    {
                        pw = phAttributesCol2.FindControl( controlId ) as PanelWidget;
                    }
                    categoryIndex++;

                    if ( pw != null )
                    {
                        var orderedAttributeList = new AttributeService( rockContext ).GetByCategoryId( category.Id )
                            .OrderBy( a => a.Order ).ThenBy( a => a.Name );
                        foreach ( var attribute in orderedAttributeList )
                        {
                            if ( attribute.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                            {
                                var attributeCache = AttributeCache.Read( attribute.Id );

                                Control attributeControl = pw.FindControl( string.Format( "attribute_field_{0}", attribute.Id ) );

                                if ( attributeControl != null && SelectedFields.Contains( attributeControl.ClientID ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    attributes.Add( attributeCache );
                                    attributeValues.Add( attributeCache.Id, newValue );
                                }
                            }
                        }
                    }
                }

                if ( attributes.Any() )
                {
                    foreach ( var person in people )
                    {
                        person.LoadAttributes();
                        foreach ( var attribute in attributes )
                        {
                            string originalValue = person.GetAttributeValue( attribute.Key );
                            string newValue = attributeValues[attribute.Id];
                            if ( ( originalValue ?? string.Empty ).Trim() != ( newValue ?? string.Empty ).Trim() )
                            {
                                Rock.Attribute.Helper.SaveAttributeValue( person, attribute, newValue, rockContext );

                                string formattedOriginalValue = string.Empty;
                                if ( !string.IsNullOrWhiteSpace( originalValue ) )
                                {
                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue( null, originalValue, attribute.QualifierValues, false );
                                }

                                string formattedNewValue = string.Empty;
                                if ( !string.IsNullOrWhiteSpace( newValue ) )
                                {
                                    formattedNewValue = attribute.FieldType.Field.FormatValue( null, newValue, attribute.QualifierValues, false );
                                }

                                History.EvaluateChange( allChanges[person.Id], attribute.Name, formattedOriginalValue, formattedNewValue );
                            }
                        }
                    }
                }

                // Create the history records
                foreach ( var changes in allChanges )
                {
                    if ( changes.Value.Any() )
                    {
                        HistoryService.AddChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            changes.Key, changes.Value );
                    }
                }
                rockContext.SaveChanges();

                #endregion

                #region Add Note

                if ( !string.IsNullOrWhiteSpace( tbNote.Text ) && CurrentPerson != null )
                {
                    string text = tbNote.Text;
                    bool isAlert = cbIsAlert.Checked;
                    bool isPrivate = cbIsPrivate.Checked;

                    var noteTypeService = new NoteTypeService( rockContext );
                    var noteType = noteTypeService.Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() );
                    if ( noteType != null )
                    {
                        var notes = new List<Note>();
                        var noteService = new NoteService( rockContext );

                        foreach ( int id in ids )
                        {
                            var note = new Note();
                            note.IsSystem = false;
                            note.EntityId = id;
                            note.Caption = isPrivate ? "You - Personal Note" : string.Empty;
                            note.Text = tbNote.Text;
                            note.IsAlert = cbIsAlert.Checked;
                            note.NoteType = noteType;
                            notes.Add( note );
                            noteService.Add( note );
                        }

                        rockContext.WrapTransaction( () =>
                        {
                            rockContext.SaveChanges();
                            foreach ( var note in notes )
                            {
                                note.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                                if ( isPrivate )
                                {
                                    note.MakePrivate( Authorization.VIEW, CurrentPerson, rockContext );
                                }
                            }
                        } );

                    }
                }

                #endregion

                #region Group

                int? groupId = gpGroup.SelectedValue.AsIntegerOrNull();
                if ( groupId.HasValue )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        var groupMemberService = new GroupMemberService( rockContext );

                        var existingMembers = groupMemberService.Queryable( "Group" )
                            .Where( m =>
                                m.GroupId == group.Id &&
                                ids.Contains( m.PersonId ) )
                            .ToList();

                        string action = ddlGroupAction.SelectedValue;
                        if ( action == "Remove" )
                        {
                            groupMemberService.DeleteRange( existingMembers );
                            rockContext.SaveChanges();
                        }
                        else
                        {
                            var roleId = ddlGroupRole.SelectedValueAsInt();
                            var status = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();

                            // Get the attribute values updated
                            var gm = new GroupMember();
                            gm.Group = group;
                            gm.GroupId = group.Id;
                            gm.LoadAttributes( rockContext );
                            var selectedGroupAttributes = new List<AttributeCache>();
                            var selectedGroupAttributeValues = new Dictionary<string, string>();
                            foreach ( var attributeCache in gm.Attributes.Select( a => a.Value ) )
                            {
                                Control attributeControl = phAttributes.FindControl( string.Format( "attribute_field_{0}", attributeCache.Id ) );
                                if ( attributeControl != null && ( action == "Add" || SelectedFields.Contains( attributeControl.ClientID ) ) )
                                {
                                    string newValue = attributeCache.FieldType.Field.GetEditValue( attributeControl, attributeCache.QualifierValues );
                                    selectedGroupAttributes.Add( attributeCache );
                                    selectedGroupAttributeValues.Add( attributeCache.Key, newValue );
                                }
                            }

                            if ( action == "Add" )
                            {
                                if ( roleId.HasValue )
                                {
                                    var newGroupMembers = new List<GroupMember>();

                                    var existingIds = existingMembers.Select( m => m.PersonId ).Distinct().ToList();
                                    foreach ( int id in ids.Where( id => !existingIds.Contains( id ) ) )
                                    {
                                        var groupMember = new GroupMember();
                                        groupMember.GroupId = group.Id;
                                        groupMember.GroupRoleId = roleId.Value;
                                        groupMember.GroupMemberStatus = status;
                                        groupMember.PersonId = id;
                                        groupMemberService.Add( groupMember );
                                        newGroupMembers.Add( groupMember );
                                    }

                                    rockContext.SaveChanges();

                                    if ( selectedGroupAttributes.Any() )
                                    {
                                        foreach ( var groupMember in newGroupMembers )
                                        {
                                            foreach ( var attribute in selectedGroupAttributes )
                                            {
                                                Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                            }
                                        }
                                    }
                                }
                            }
                            else // Update
                            {
                                if ( SelectedFields.Contains( ddlGroupRole.ClientID ) && roleId.HasValue )
                                {
                                    foreach ( var member in existingMembers.Where( m => m.GroupRoleId != roleId.Value ) )
                                    {
                                        if ( !existingMembers.Where( m => m.PersonId == member.PersonId && m.GroupRoleId == roleId.Value ).Any() )
                                        {
                                            member.GroupRoleId = roleId.Value;
                                        }
                                    }
                                }

                                if ( SelectedFields.Contains( ddlGroupMemberStatus.ClientID ) )
                                {
                                    foreach ( var member in existingMembers )
                                    {
                                        member.GroupMemberStatus = status;
                                    }
                                }

                                rockContext.SaveChanges();

                                if ( selectedGroupAttributes.Any() )
                                {
                                    foreach ( var groupMember in existingMembers )
                                    {
                                        foreach ( var attribute in selectedGroupAttributes )
                                        {
                                            Rock.Attribute.Helper.SaveAttributeValue( groupMember, attribute, selectedGroupAttributeValues[attribute.Key], rockContext );
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                #endregion

                pnlEntry.Visible = false;
                pnlConfirm.Visible = false;

                nbResult.Text = string.Format( "{0} {1} succesfully updated.",
                    ids.Count().ToString( "N0" ), ( ids.Count() > 1 ? "people were" : "person was" ) ); ;
                pnlResult.Visible = true;
            }
        }
        private void SaveAttributes( int entityTypeId, string qualifierColumn, string qualifierValue, ViewStateList<Attribute> viewStateAttributes, RockContext rockContext )
        {
            // Get the existing attributes for this entity type and qualifier value
            var attributeService = new AttributeService( rockContext );
            var attributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );

            // Delete any of those attributes that were removed in the UI
            var selectedAttributeGuids = viewStateAttributes.Select( a => a.Guid );
            foreach ( var attr in attributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
            {
                attributeService.Delete( attr );
                rockContext.SaveChanges();
                Rock.Web.Cache.AttributeCache.Flush( attr.Id );
            }

            // Update the Attributes that were assigned in the UI
            foreach ( var attributeState in viewStateAttributes )
            {
                Helper.SaveAttributeEdits( attributeState, entityTypeId, qualifierColumn, qualifierValue, rockContext );
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            BinaryFile binaryFile;
            var rockContext = new RockContext();
            BinaryFileService binaryFileService = new BinaryFileService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );

            int? prevBinaryFileTypeId = null;

            int binaryFileId = int.Parse( hfBinaryFileId.Value );

            if ( binaryFileId == 0 )
            {
                binaryFile = new BinaryFile();
                binaryFileService.Add( binaryFile );
            }
            else
            {
                binaryFile = binaryFileService.Get( binaryFileId );
                prevBinaryFileTypeId = binaryFile != null ? binaryFile.BinaryFileTypeId : (int?)null;
            }

            // if a new file was uploaded, copy the uploaded file to this binaryFile (uploaded files are always new temporary binaryFiles)
            if ( fsFile.BinaryFileId != binaryFile.Id)
            {
                var uploadedBinaryFile = binaryFileService.Get(fsFile.BinaryFileId ?? 0);
                if (uploadedBinaryFile != null)
                {
                    binaryFile.BinaryFileTypeId = uploadedBinaryFile.BinaryFileTypeId;
                    binaryFile.ContentStream = uploadedBinaryFile.ContentStream;
                }
            }

            binaryFile.IsTemporary = false;
            binaryFile.FileName = tbName.Text;
            binaryFile.Description = tbDescription.Text;
            binaryFile.MimeType = tbMimeType.Text;
            binaryFile.BinaryFileTypeId = ddlBinaryFileType.SelectedValueAsInt();

            binaryFile.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributes, binaryFile );

            if ( !Page.IsValid )
            {
                return;
            }

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

            rockContext.WrapTransaction( () =>
            {
                foreach ( var id in OrphanedBinaryFileIdList )
                {
                    var tempBinaryFile = binaryFileService.Get( id );
                    if ( tempBinaryFile != null && tempBinaryFile.IsTemporary )
                    {
                        binaryFileService.Delete( tempBinaryFile );
                    }
                }

                rockContext.SaveChanges();
                binaryFile.SaveAttributeValues( rockContext );

            } );

            Rock.CheckIn.KioskLabel.Flush( binaryFile.Guid );

            if ( !prevBinaryFileTypeId.Equals( binaryFile.BinaryFileTypeId ) )
            {
                var checkInBinaryFileType = new BinaryFileTypeService( rockContext )
                    .Get( Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL.AsGuid() );
                if ( checkInBinaryFileType != null && (
                    ( prevBinaryFileTypeId.HasValue && prevBinaryFileTypeId.Value == checkInBinaryFileType.Id )  ||
                    ( binaryFile.BinaryFileTypeId.HasValue && binaryFile.BinaryFileTypeId.Value == checkInBinaryFileType.Id ) ) )
                {
                    Rock.CheckIn.KioskDevice.FlushAll();
                }
            }

            NavigateToParentPage();
        }
        /// <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 )
        {
            Location location;

            var rockContext = new RockContext();
            LocationService locationService = new LocationService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );

            int locationId = int.Parse( hfLocationId.Value );

            if ( locationId == 0 )
            {
                location = new Location();
                location.Name = string.Empty;
            }
            else
            {
                location = locationService.Get( locationId );
                FlushCampus( locationId );
            }

            int? orphanedImageId = null;
            if ( location.ImageId != imgImage.BinaryFileId )
            {
                orphanedImageId = location.ImageId;
                location.ImageId = imgImage.BinaryFileId;
            }

            location.Name = tbName.Text;
            location.IsActive = cbIsActive.Checked;
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();
            if ( gpParentLocation != null && gpParentLocation.Location != null )
            {
                location.ParentLocationId = gpParentLocation.Location.Id;
            }
            else
            {
                location.ParentLocationId = null;
            }

            location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();

            acAddress.GetValues(location);

            location.GeoPoint = geopPoint.SelectedValue;
            if ( geopPoint.SelectedValue != null )
            {
                location.IsGeoPointLocked = true;
            }
            location.GeoFence = geopFence.SelectedValue;

            location.IsGeoPointLocked = cbGeoPointLocked.Checked;

            location.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributeEdits, location );

            if ( !Page.IsValid )
            {
                return;
            }

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

            rockContext.WrapTransaction( () =>
            {
                if ( location.Id.Equals( 0 ) )
                {
                    locationService.Add( location );
                }
                rockContext.SaveChanges();

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

                location.SaveAttributeValues( rockContext );

            } );

            var qryParams = new Dictionary<string, string>();
            qryParams["LocationId"] = location.Id.ToString();
            qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );

            NavigateToPage( RockPage.Guid, qryParams );
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            Location location = null;

            var rockContext = new RockContext();
            LocationService locationService = new LocationService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService( rockContext );

            int locationId = int.Parse( hfLocationId.Value );

            if ( locationId != 0 )
            {
                location = locationService.Get( locationId );
                FlushCampus( locationId );
            }

            if ( location == null )
            {
                location = new Location();
                location.Name = string.Empty;
            }

            string previousName = location.Name;

            int? orphanedImageId = null;
            if ( location.ImageId != imgImage.BinaryFileId )
            {
                orphanedImageId = location.ImageId;
                location.ImageId = imgImage.BinaryFileId;
            }

            location.Name = tbName.Text;
            location.IsActive = cbIsActive.Checked;
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();
            if ( gpParentLocation != null && gpParentLocation.Location != null )
            {
                location.ParentLocationId = gpParentLocation.Location.Id;
            }
            else
            {
                location.ParentLocationId = null;
            }

            location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();

            acAddress.GetValues(location);

            location.GeoPoint = geopPoint.SelectedValue;
            if ( geopPoint.SelectedValue != null )
            {
                location.IsGeoPointLocked = true;
            }
            location.GeoFence = geopFence.SelectedValue;

            location.IsGeoPointLocked = cbGeoPointLocked.Checked;

            location.SoftRoomThreshold = nbSoftThreshold.Text.AsIntegerOrNull();
            location.FirmRoomThreshold = nbFirmThreshold.Text.AsIntegerOrNull();

            location.LoadAttributes( rockContext );
            Rock.Attribute.Helper.GetEditValues( phAttributeEdits, location );

            if ( !Page.IsValid )
            {
                return;
            }

            // if the location IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of location didn't pass.
            // So, make sure a message is displayed in the validation summary
            cvLocation.IsValid = location.IsValid;

            if ( !cvLocation.IsValid )
            {
                cvLocation.ErrorMessage = location.ValidationResults.Select( a => a.ErrorMessage ).ToList().AsDelimited( "<br />" );
                return;
            }

            rockContext.WrapTransaction( () =>
            {
                if ( location.Id.Equals( 0 ) )
                {
                    locationService.Add( location );
                }
                rockContext.SaveChanges();

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

                location.SaveAttributeValues( rockContext );

            } );

            // If this is a names location (or was previouisly)
            if ( !string.IsNullOrWhiteSpace( location.Name ) || ( previousName ?? string.Empty ) != (location.Name ?? string.Empty ) )
            {
                // flush the checkin config
                Rock.CheckIn.KioskDevice.FlushAll();
            }

            if ( _personId.HasValue )
            {
                NavigateToParentPage( new Dictionary<string, string> { { "PersonId", _personId.Value.ToString() } } );
            }
            else
            {
                Rock.CheckIn.KioskDevice.FlushAll();

                var qryParams = new Dictionary<string, string>();
                qryParams["LocationId"] = location.Id.ToString();
                qryParams["ExpandedIds"] = PageParameter( "ExpandedIds" );

                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            WorkflowTrigger WorkflowTrigger;
            var rockContext = new RockContext();
            WorkflowTriggerService WorkflowTriggerService = new WorkflowTriggerService( rockContext );
            AttributeService attributeService = new AttributeService( rockContext );

            int WorkflowTriggerId = int.Parse( hfWorkflowTriggerId.Value );

            if ( WorkflowTriggerId == 0 )
            {
                WorkflowTrigger = new WorkflowTrigger();
                WorkflowTriggerService.Add( WorkflowTrigger );
            }
            else
            {
                WorkflowTrigger = WorkflowTriggerService.Get( WorkflowTriggerId );
            }

            WorkflowTrigger.EntityTypeId = ddlEntityType.SelectedValueAsInt().Value;
            WorkflowTrigger.EntityTypeQualifierColumn = ddlQualifierColumn.SelectedValue;
            WorkflowTrigger.EntityTypeQualifierValue = tbQualifierValue.Text;
            WorkflowTrigger.WorkflowTypeId = ddlWorkflowType.SelectedValueAsInt().Value;
            WorkflowTrigger.WorkflowTriggerType = (WorkflowTriggerType)System.Enum.Parse( typeof( WorkflowTriggerType ), rblTriggerType.SelectedValue );
            WorkflowTrigger.IsActive = cbIsActive.Checked;
            if ( string.IsNullOrWhiteSpace( tbWorkflowName.Text ) )
            {
                WorkflowTrigger.WorkflowName = null;
            }
            else
            {
                WorkflowTrigger.WorkflowName = tbWorkflowName.Text;
            }

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

            rockContext.SaveChanges();

            Rock.Workflow.TriggerCache.Refresh();

            NavigateToParentPage();
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="ministryFileType">Type of the ministry file.</param>
        /// <param name="storageProvider">The storage provider.</param>
        public void Map( ZipArchive folder, BinaryFileType ministryFileType, ProviderComponent storageProvider )
        {
            var lookupContext = new RockContext();
            var personEntityTypeId = EntityTypeCache.GetId<Person>();
            var fileFieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.FILE.AsGuid(), lookupContext ).Id;

            var existingAttributes = new AttributeService( lookupContext ).GetByFieldTypeId( fileFieldTypeId )
                .Where( a => a.EntityTypeId == personEntityTypeId )
                .ToDictionary( a => a.Key, a => a.Id );

            var emptyJsonObject = "{}";
            var newFileList = new List<DocumentKeys>();

            int completed = 0;
            int totalRows = folder.Entries.Count;
            int percentage = ( totalRows - 1 ) / 100 + 1;
            ReportProgress( 0, string.Format( "Verifying files import ({0:N0} found.", totalRows ) );

            foreach ( var file in folder.Entries )
            {
                var fileExtension = Path.GetExtension( file.Name );
                var fileMimeType = Extensions.GetMIMEType( file.Name );
                if ( BinaryFileComponent.FileTypeBlackList.Contains( fileExtension ) )
                {
                    LogException( "Binary File Import", string.Format( "{0} filetype not allowed ({1})", fileExtension, file.Name ) );
                    continue;
                }
                else if ( fileMimeType == null )
                {
                    LogException( "Binary File Import", string.Format( "{0} filetype not recognized ({1})", fileExtension, file.Name ) );
                    continue;
                }

                string[] parsedFileName = file.Name.Split( '_' );
                // Ministry docs should follow this pattern:
                // 0. Firstname
                // 1. Lastname
                // 2. ForeignId
                // 3. Filename

                var personForeignId = parsedFileName[2].AsType<int?>();
                var personKeys = BinaryFileComponent.ImportedPeople.FirstOrDefault( p => p.IndividualId == personForeignId );
                if ( personKeys != null )
                {
                    var rockFile = new Rock.Model.BinaryFile();
                    rockFile.IsSystem = false;
                    rockFile.IsTemporary = false;
                    rockFile.FileName = file.Name;
                    rockFile.MimeType = fileMimeType;
                    rockFile.BinaryFileTypeId = ministryFileType.Id;
                    rockFile.CreatedDateTime = file.LastWriteTime.DateTime;
                    rockFile.ModifiedDateTime = ImportDateTime;
                    rockFile.Description = string.Format( "Imported as {0}", file.Name );
                    rockFile.SetStorageEntityTypeId( ministryFileType.StorageEntityTypeId );
                    rockFile.StorageEntitySettings = emptyJsonObject;

                    if ( ministryFileType.AttributeValues.Any() )
                    {
                        rockFile.StorageEntitySettings = ministryFileType.AttributeValues
                            .ToDictionary( a => a.Key, v => v.Value.Value ).ToJson();
                    }

                    // use base stream instead of file stream to keep the byte[]
                    // NOTE: if byte[] converts to a string it will corrupt the stream
                    using ( var fileContent = new StreamReader( file.Open() ) )
                    {
                        rockFile.ContentStream = new MemoryStream( fileContent.BaseStream.ReadBytesToEnd() );
                    }

                    var attributePattern = "[A-Za-z0-9-]+";
                    var attributeName = Regex.Match( parsedFileName[3].RemoveWhitespace(), attributePattern );
                    var attributeKey = attributeName.Value.RemoveWhitespace();

                    // change key to default key for Background Check Documents
                    if ( attributeKey == "BackgroundCheck" )
                    {
                        attributeKey = "BackgroundCheckDocument";
                    }

                    if ( !existingAttributes.ContainsKey( attributeKey ) )
                    {
                        var newAttribute = new Attribute();
                        newAttribute.FieldTypeId = fileFieldTypeId;
                        newAttribute.EntityTypeId = personEntityTypeId;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.EntityTypeQualifierValue = string.Empty;
                        newAttribute.Key = attributeKey;
                        newAttribute.Name = attributeName.Value;
                        newAttribute.Description = attributeName.Value + " created by binary file import";
                        newAttribute.CreatedDateTime = ImportDateTime;
                        newAttribute.ModifiedDateTime = ImportDateTime;
                        newAttribute.IsGridColumn = false;
                        newAttribute.IsMultiValue = false;
                        newAttribute.IsRequired = false;
                        newAttribute.AllowSearch = false;
                        newAttribute.IsSystem = false;
                        newAttribute.Order = 0;

                        newAttribute.AttributeQualifiers.Add( new AttributeQualifier()
                        {
                            Key = "binaryFileType",
                            Value = ministryFileType.Guid.ToString()
                        } );

                        lookupContext.Attributes.Add( newAttribute );
                        lookupContext.SaveChanges();

                        existingAttributes.Add( newAttribute.Key, newAttribute.Id );
                    }

                    newFileList.Add( new DocumentKeys()
                    {
                        PersonId = personKeys.PersonId,
                        AttributeId = existingAttributes[attributeKey],
                        File = rockFile
                    } );

                    completed++;
                    if ( completed % percentage < 1 )
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress( percentComplete, string.Format( "{0:N0} files imported ({1}% complete).", completed, percentComplete ) );
                    }
                    else if ( completed % ReportingNumber < 1 )
                    {
                        SaveFiles( newFileList, storageProvider );

                        // Reset list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if ( newFileList.Any() )
            {
                SaveFiles( newFileList, storageProvider );
            }

            ReportProgress( 100, string.Format( "Finished files import: {0:N0} addresses imported.", completed ) );
        }
        /// <summary>
        /// Saves the attributes.
        /// </summary>
        /// <param name="channelId">The channel identifier.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="rockContext">The rock context.</param>
        private void SaveAttributes( int channelId, int entityTypeId, List<Attribute> attributes, RockContext rockContext )
        {
            string qualifierColumn = "ContentChannelId";
            string qualifierValue = channelId.ToString();

            AttributeService attributeService = new AttributeService( rockContext );

            // Get the existing attributes for this entity type and qualifier value
            var existingAttributes = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );

            // Delete any of those attributes that were removed in the UI
            var selectedAttributeGuids = attributes.Select( a => a.Guid );
            foreach ( var attr in existingAttributes.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
            {
                Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                attributeService.Delete( attr );
            }

            rockContext.SaveChanges();

            int newOrder = 1000;

            // Update the Attributes that were assigned in the UI
            foreach ( var attr in attributes.OrderBy( a => a.Order ) )
            {
                // Artificially exaggerate the order so that all channel specific attributes are displayed after the content-type specific attributes (unless categorized)
                attr.Order = newOrder++;
                Rock.Attribute.Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext );
            }

            AttributeCache.FlushEntityAttributes();
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Loads the cache objects.
        /// </summary>
        private static void LoadCacheObjects(RockContext rockContext)
        {
            // Cache all the entity types
            foreach (var entityType in new Rock.Model.EntityTypeService(rockContext).Queryable().AsNoTracking())
            {
                EntityTypeCache.Get(entityType);
            }

            // Cache all the Field Types
            foreach (var fieldType in new Rock.Model.FieldTypeService(rockContext).Queryable().AsNoTracking())
            {
                // improve performance of loading FieldTypeCache by doing LoadAttributes using an existing rockContext before doing FieldTypeCache.Get to avoid calling LoadAttributes with new context per FieldTypeCache
                fieldType.LoadAttributes(rockContext);
                FieldTypeCache.Get(fieldType);
            }

            var all = FieldTypeCache.All();

            // Read all the qualifiers first so that EF doesn't perform a query for each attribute when it's cached
            var qualifiers = new Dictionary <int, Dictionary <string, string> >();

            foreach (var attributeQualifier in new Rock.Model.AttributeQualifierService(rockContext).Queryable().AsNoTracking())
            {
                try
                {
                    if (!qualifiers.ContainsKey(attributeQualifier.AttributeId))
                    {
                        qualifiers.Add(attributeQualifier.AttributeId, new Dictionary <string, string>());
                    }

                    qualifiers[attributeQualifier.AttributeId].Add(attributeQualifier.Key, attributeQualifier.Value);
                }
                catch (Exception ex)
                {
                    var startupException = new RockStartupException("Error loading cache objects", ex);
                    LogError(startupException, null);
                }
            }

            // Cache all the attributes, except for user preferences
            var attributeQuery = new Rock.Model.AttributeService(rockContext).Queryable("Categories");
            int?personUserValueEntityTypeId = EntityTypeCache.GetId(Person.USER_VALUE_ENTITY);

            if (personUserValueEntityTypeId.HasValue)
            {
                attributeQuery = attributeQuery.Where(a => !a.EntityTypeId.HasValue || a.EntityTypeId.Value != personUserValueEntityTypeId);
            }

            foreach (var attribute in attributeQuery.AsNoTracking().ToList())
            {
                // improve performance of loading AttributeCache by doing LoadAttributes using an existing rockContext before doing AttributeCache.Get to avoid calling LoadAttributes with new context per AttributeCache
                attribute.LoadAttributes(rockContext);

                if (qualifiers.ContainsKey(attribute.Id))
                {
                    Rock.Web.Cache.AttributeCache.Get(attribute, qualifiers[attribute.Id]);
                }
                else
                {
                    Rock.Web.Cache.AttributeCache.Get(attribute, new Dictionary <string, string>());
                }
            }

            // Force authorizations to be cached
            Rock.Security.Authorization.Get();
        }