Exemplo n.º 1
0
        /// <summary>
        /// Loads the UserLogin data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadUserLogin(CSVInstance csvData)
        {
            var lookupContext    = new RockContext();
            var userLoginService = new UserLoginService(lookupContext);

            var newUserLoginList      = new List <UserLogin>();
            var existingUserLoginList = new List <UserLogin>();

            existingUserLoginList.AddRange(userLoginService.Queryable().AsNoTracking().Where(a => a.ForeignId == null));

            int completed            = 0;
            int importedCount        = 0;
            int alreadyImportedCount = userLoginService.Queryable().AsNoTracking().Count(a => a.ForeignKey != null);

            ReportProgress(0, string.Format("Starting user login import ({0:N0} already exist).", alreadyImportedCount));

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                string rowUserLoginId                 = row[UserLoginId];
                string rowUserLoginPersonId           = row[UserLoginPersonId];
                string rowUserLoginUserName           = row[UserLoginUserName];
                string rowUserLoginPassword           = row[UserLoginPassword];
                string rowUserLoginDateCreated        = row[UserLoginDateCreated];
                string rowUserLoginAuthenticationType = row[UserLoginAuthenticationType];
                string rowUserLoginIsConfirmed        = row[UserLoginIsConfirmed];

                int?rowLoginId           = rowUserLoginId.AsType <int?>();
                int authenticationTypeId = EntityTypeCache.Get(rowUserLoginAuthenticationType).Id;

                //
                // Find this person in the database.
                //
                var personKeys = GetPersonKeys(rowUserLoginPersonId);
                if (personKeys == null || personKeys.PersonId == 0)
                {
                    ReportProgress(0, string.Format("Person key {0} not found", rowUserLoginPersonId));
                }

                //
                // Verify the authentication type exists.
                //
                if (authenticationTypeId < 1)
                {
                    ReportProgress(0, string.Format("Authentication type {0} not found", rowUserLoginAuthenticationType));
                }

                //
                // Check that this user login record doesn't already exist.
                //
                bool exists = false;

                if (existingUserLoginList.Count > 0)
                {
                    exists = userLoginService.Queryable().AsNoTracking().Any(a => a.UserName.ToLower() == rowUserLoginUserName.ToLower());
                }

                if (exists == false && alreadyImportedCount > 0)
                {
                    exists = userLoginService.Queryable().AsNoTracking().Any(a => a.ForeignKey == rowUserLoginId);
                }

                if (!exists && personKeys != null && personKeys.PersonId != 0 && authenticationTypeId > 0)
                {
                    //
                    // Create and populate the new user login record.
                    //
                    UserLogin login = new UserLogin();
                    login.CreatedDateTime        = ParseDateOrDefault(rowUserLoginDateCreated, DateTime.Now);
                    login.CreatedByPersonAliasId = ImportPersonAliasId;
                    login.EntityTypeId           = authenticationTypeId;
                    login.IsConfirmed            = ParseBoolOrDefault(rowUserLoginIsConfirmed, true);
                    login.UserName   = rowUserLoginUserName;
                    login.Password   = rowUserLoginPassword;
                    login.PersonId   = personKeys.PersonId;
                    login.ForeignKey = rowUserLoginId;
                    login.ForeignId  = rowLoginId;

                    //
                    // Force not confirmed if no password provided for database logins.
                    //
                    if (rowUserLoginAuthenticationType == "Rock.Security.Authentication.Database" && string.IsNullOrWhiteSpace(rowUserLoginPassword))
                    {
                        login.IsConfirmed = false;
                    }

                    //
                    // Add the record for delayed saving.
                    //
                    newUserLoginList.Add(login);
                    importedCount++;
                }

                //
                // Notify user of our status.
                //
                completed++;
                if (completed % (ReportingNumber * 10) < 1)
                {
                    ReportProgress(0, string.Format("{0:N0} user login records processed, {1:N0} imported.", completed, importedCount));
                }

                if (completed % ReportingNumber < 1)
                {
                    SaveUserLogin(newUserLoginList);
                    lookupContext.SaveChanges();
                    ReportPartialProgress();

                    // Clear out variables
                    newUserLoginList.Clear();
                    userLoginService = new UserLoginService(lookupContext);
                }
            }

            //
            // Save any final changes to new records
            //
            if (newUserLoginList.Any())
            {
                SaveUserLogin(newUserLoginList);
            }

            //
            // Save any other changes to existing items.
            //
            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress(0, string.Format("Finished user login import: {0:N0} records added.", importedCount));

            return(completed);
        }
Exemplo n.º 2
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)
        {
            Site site;

            if (Page.IsValid)
            {
                var               rockContext       = new RockContext();
                PageService       pageService       = new PageService(rockContext);
                SiteService       siteService       = new SiteService(rockContext);
                SiteDomainService siteDomainService = new SiteDomainService(rockContext);
                bool              newSite           = false;

                int siteId = hfSiteId.Value.AsInteger();

                if (siteId == 0)
                {
                    newSite = true;
                    site    = new Rock.Model.Site();
                    siteService.Add(site);
                }
                else
                {
                    site = siteService.Get(siteId);
                }

                site.Name                      = tbSiteName.Text;
                site.Description               = tbDescription.Text;
                site.Theme                     = ddlTheme.Text;
                site.DefaultPageId             = ppDefaultPage.PageId;
                site.DefaultPageRouteId        = ppDefaultPage.PageRouteId;
                site.LoginPageId               = ppLoginPage.PageId;
                site.LoginPageRouteId          = ppLoginPage.PageRouteId;
                site.ChangePasswordPageId      = ppChangePasswordPage.PageId;
                site.ChangePasswordPageRouteId = ppChangePasswordPage.PageRouteId;
                site.CommunicationPageId       = ppCommunicationPage.PageId;
                site.CommunicationPageRouteId  = ppCommunicationPage.PageRouteId;
                site.RegistrationPageId        = ppRegistrationPage.PageId;
                site.RegistrationPageRouteId   = ppRegistrationPage.PageRouteId;
                site.PageNotFoundPageId        = ppPageNotFoundPage.PageId;
                site.PageNotFoundPageRouteId   = ppPageNotFoundPage.PageRouteId;
                site.ErrorPage                 = tbErrorPage.Text;
                site.GoogleAnalyticsCode       = tbGoogleAnalytics.Text;
                site.RequiresEncryption        = cbRequireEncryption.Checked;
                site.EnabledForShortening      = cbEnableForShortening.Checked;
                site.EnableMobileRedirect      = cbEnableMobileRedirect.Checked;
                site.MobilePageId              = ppMobilePage.PageId;
                site.ExternalUrl               = tbExternalURL.Text;
                site.AllowedFrameDomains       = tbAllowedFrameDomains.Text;
                site.RedirectTablets           = cbRedirectTablets.Checked;
                site.EnablePageViews           = cbEnablePageViews.Checked;
                site.IsActive                  = cbIsActive.Checked;
                site.AllowIndexing             = cbAllowIndexing.Checked;
                site.IsIndexEnabled            = cbEnableIndexing.Checked;
                site.IndexStartingLocation     = tbIndexStartingLocation.Text;
                site.EnableExclusiveRoutes     = cbEnableExclusiveRoutes.Checked;

                site.PageHeaderContent = cePageHeaderContent.Text;

                avcAttributes.GetEditValues(site);
                // only save if everything saves:
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    site.SaveAttributeValues();
                });

                int?existingIconId = null;
                if (site.FavIconBinaryFileId != imgSiteIcon.BinaryFileId)
                {
                    existingIconId           = site.FavIconBinaryFileId;
                    site.FavIconBinaryFileId = imgSiteIcon.BinaryFileId;
                }

                int?existingLogoId = null;
                if (site.SiteLogoBinaryFileId != imgSiteLogo.BinaryFileId)
                {
                    existingLogoId            = site.SiteLogoBinaryFileId;
                    site.SiteLogoBinaryFileId = imgSiteLogo.BinaryFileId;
                }

                var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>();
                site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>();

                // Remove any deleted domains
                foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList())
                {
                    site.SiteDomains.Remove(domain);
                    siteDomainService.Delete(domain);
                }

                int order = 0;
                foreach (string domain in currentDomains)
                {
                    SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault();
                    if (sd == null)
                    {
                        sd        = new SiteDomain();
                        sd.Domain = domain;
                        sd.Guid   = Guid.NewGuid();
                        site.SiteDomains.Add(sd);
                    }
                    sd.Order = order++;
                }

                if (!site.DefaultPageId.HasValue && !newSite)
                {
                    ppDefaultPage.ShowErrorMessage("Default Page is required.");
                    return;
                }

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

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

                    SaveAttributes(new Page().TypeId, "SiteId", site.Id.ToString(), PageAttributesState, rockContext);

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

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

                    if (newSite)
                    {
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE);
                    }
                });

                // add/update for the InteractionChannel for this site and set the RetentionPeriod
                var interactionChannelService   = new InteractionChannelService(rockContext);
                int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                var interactionChannelForSite   = interactionChannelService.Queryable()
                                                  .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

                if (interactionChannelForSite == null)
                {
                    interactionChannelForSite = new InteractionChannel();
                    interactionChannelForSite.ChannelTypeMediumValueId = channelMediumWebsiteValueId;
                    interactionChannelForSite.ChannelEntityId          = site.Id;
                    interactionChannelService.Add(interactionChannelForSite);
                }

                interactionChannelForSite.Name = site.Name;
                interactionChannelForSite.RetentionDuration     = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull();
                interactionChannelForSite.ComponentEntityTypeId = EntityTypeCache.Get <Rock.Model.Page>().Id;

                rockContext.SaveChanges();


                // Create the default page is this is a new site
                if (!site.DefaultPageId.HasValue && newSite)
                {
                    var siteCache = SiteCache.Get(site.Id);

                    // Create the layouts for the site, and find the first one
                    LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache);

                    var    layoutService = new LayoutService(rockContext);
                    var    layouts       = layoutService.GetBySiteId(siteCache.Id);
                    Layout layout        = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase));
                    if (layout == null)
                    {
                        layout = layouts.FirstOrDefault();
                    }

                    if (layout != null)
                    {
                        var page = new Page();
                        page.LayoutId              = layout.Id;
                        page.PageTitle             = siteCache.Name + " Home Page";
                        page.InternalName          = page.PageTitle;
                        page.BrowserTitle          = page.PageTitle;
                        page.EnableViewState       = true;
                        page.IncludeAdminFooter    = true;
                        page.MenuDisplayChildPages = true;

                        var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault();

                        page.Order = lastPage != null ? lastPage.Order + 1 : 0;
                        pageService.Add(page);

                        rockContext.SaveChanges();

                        site = siteService.Get(siteCache.Id);
                        site.DefaultPageId = page.Id;

                        rockContext.SaveChanges();
                    }
                }

                var qryParams = new Dictionary <string, string>();
                qryParams["SiteId"] = site.Id.ToString();

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
Exemplo n.º 3
0
        public string GetSeriesPartitionName(int metricId, [FromBody] List <string> metricValuePartitionEntityIdList)
        {
            var entityTypeEntityIdList = metricValuePartitionEntityIdList.Select(a => a.Split('|')).Select(a =>
                                                                                                           new
            {
                EntityTypeId = a[0].AsIntegerOrNull(),
                EntityId     = a[1].AsIntegerOrNull()
            });

            var rockContext = new RockContext();

            List <string> seriesPartitionValues = new List <string>();

            foreach (var entityTypeEntity in entityTypeEntityIdList)
            {
                if (entityTypeEntity.EntityTypeId.HasValue && entityTypeEntity.EntityId.HasValue)
                {
                    var entityTypeCache = EntityTypeCache.Get(entityTypeEntity.EntityTypeId.Value);
                    if (entityTypeCache != null)
                    {
                        if (entityTypeCache.Id == EntityTypeCache.GetId <Campus>())
                        {
                            var campus = CampusCache.Get(entityTypeEntity.EntityId.Value);
                            if (campus != null)
                            {
                                seriesPartitionValues.Add(campus.Name);
                            }
                        }
                        else if (entityTypeCache.Id == EntityTypeCache.GetId <DefinedValue>())
                        {
                            var definedValue = DefinedValueCache.Get(entityTypeEntity.EntityId.Value);
                            if (definedValue != null)
                            {
                                seriesPartitionValues.Add(definedValue.ToString());
                            }
                        }
                        else
                        {
                            Type[]     modelType          = { entityTypeCache.GetEntityType() };
                            Type       genericServiceType = typeof(Rock.Data.Service <>);
                            Type       modelServiceType   = genericServiceType.MakeGenericType(modelType);
                            var        serviceInstance    = Activator.CreateInstance(modelServiceType, new object[] { rockContext }) as IService;
                            MethodInfo getMethod          = serviceInstance.GetType().GetMethod("Get", new Type[] { typeof(int) });
                            var        result             = getMethod.Invoke(serviceInstance, new object[] { entityTypeEntity.EntityId });
                            if (result != null)
                            {
                                seriesPartitionValues.Add(result.ToString());
                            }
                        }
                    }
                }
            }

            if (seriesPartitionValues.Any())
            {
                return(seriesPartitionValues.AsDelimited(","));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 4
0
        public IHttpActionResult PostInteractions([FromBody] List <MobileInteractionSession> sessions, Guid?personalDeviceGuid = null)
        {
            var person    = GetPerson();
            var ipAddress = System.Web.HttpContext.Current?.Request?.UserHostAddress;

            using (var rockContext = new Data.RockContext())
            {
                var interactionChannelService   = new InteractionChannelService(rockContext);
                var interactionComponentService = new InteractionComponentService(rockContext);
                var interactionSessionService   = new InteractionSessionService(rockContext);
                var interactionService          = new InteractionService(rockContext);
                var userLoginService            = new UserLoginService(rockContext);
                var channelMediumTypeValue      = DefinedValueCache.Get(SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE);
                var pageEntityTypeId            = EntityTypeCache.Get(typeof(Model.Page)).Id;

                //
                // Check to see if we have a site and the API key is valid.
                //
                if (MobileHelper.GetCurrentApplicationSite() == null)
                {
                    return(StatusCode(System.Net.HttpStatusCode.Forbidden));
                }

                //
                // Get the personal device identifier if they provided it's unique identifier.
                //
                int?personalDeviceId = null;
                if (personalDeviceGuid.HasValue)
                {
                    personalDeviceId = new PersonalDeviceService(rockContext).GetId(personalDeviceGuid.Value);
                }

                rockContext.WrapTransaction(() =>
                {
                    foreach (var mobileSession in sessions)
                    {
                        var interactionGuids         = mobileSession.Interactions.Select(i => i.Guid).ToList();
                        var existingInteractionGuids = interactionService.Queryable()
                                                       .Where(i => interactionGuids.Contains(i.Guid))
                                                       .Select(i => i.Guid)
                                                       .ToList();

                        //
                        // Loop through all interactions that don't already exist and add each one.
                        //
                        foreach (var mobileInteraction in mobileSession.Interactions.Where(i => !existingInteractionGuids.Contains(i.Guid)))
                        {
                            int?interactionComponentId = null;

                            //
                            // Lookup the interaction channel, and create it if it doesn't exist
                            //
                            if (mobileInteraction.AppId.HasValue && mobileInteraction.PageGuid.HasValue)
                            {
                                var site = SiteCache.Get(mobileInteraction.AppId.Value);
                                var page = PageCache.Get(mobileInteraction.PageGuid.Value);

                                if (site == null || page == null)
                                {
                                    continue;
                                }

                                //
                                // Try to find an existing interaction channel.
                                //
                                var interactionChannelId = interactionChannelService.Queryable()
                                                           .Where(a =>
                                                                  a.ChannelTypeMediumValueId == channelMediumTypeValue.Id &&
                                                                  a.ChannelEntityId == site.Id)
                                                           .Select(a => ( int? )a.Id)
                                                           .FirstOrDefault();

                                //
                                // If not found, create one.
                                //
                                if (!interactionChannelId.HasValue)
                                {
                                    var interactionChannel = new InteractionChannel
                                    {
                                        Name = site.Name,
                                        ChannelTypeMediumValueId = channelMediumTypeValue.Id,
                                        ChannelEntityId          = site.Id,
                                        ComponentEntityTypeId    = pageEntityTypeId
                                    };

                                    interactionChannelService.Add(interactionChannel);
                                    rockContext.SaveChanges();

                                    interactionChannelId = interactionChannel.Id;
                                }

                                //
                                // Get an existing or create a new component.
                                //
                                var interactionComponent = interactionComponentService.GetComponentByChannelIdAndEntityId(interactionChannelId.Value, page.Id, page.InternalName);
                                rockContext.SaveChanges();

                                interactionComponentId = interactionComponent.Id;
                            }
                            else if (mobileInteraction.ChannelId.HasValue)
                            {
                                var interactionChannelId = mobileInteraction.ChannelId;

                                if (mobileInteraction.ComponentId.HasValue)
                                {
                                    interactionComponentId = mobileInteraction.ComponentId.Value;
                                }
                                else if (mobileInteraction.ComponentName.IsNotNullOrWhiteSpace())
                                {
                                    //
                                    // Get an existing or create a new component.
                                    //
                                    var interactionComponent = interactionComponentService.GetComponentByComponentName(interactionChannelId.Value, mobileInteraction.ComponentName);
                                    rockContext.SaveChanges();

                                    interactionComponentId = interactionComponent.Id;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                continue;
                            }

                            //
                            // Add the interaction
                            //
                            if (interactionComponentId.HasValue)
                            {
                                var interaction = interactionService.CreateInteraction(interactionComponentId.Value,
                                                                                       mobileInteraction.EntityId,
                                                                                       mobileInteraction.Operation,
                                                                                       mobileInteraction.Summary,
                                                                                       mobileInteraction.Data,
                                                                                       person?.PrimaryAliasId,
                                                                                       mobileInteraction.DateTime,
                                                                                       mobileSession.Application,
                                                                                       mobileSession.OperatingSystem,
                                                                                       mobileSession.ClientType,
                                                                                       null,
                                                                                       ipAddress,
                                                                                       mobileSession.Guid);

                                interaction.Guid             = mobileInteraction.Guid;
                                interaction.PersonalDeviceId = personalDeviceId;
                                interactionService.Add(interaction);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                });
            }

            return(Ok());
        }
Exemplo n.º 5
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            // Exclude the categories for block and service job attributes, since they are controlled through code attribute decorations
            var exclusions = new List <Guid>();

            exclusions.Add(Rock.SystemGuid.EntityType.BLOCK.AsGuid());
            exclusions.Add(Rock.SystemGuid.EntityType.SERVICE_JOB.AsGuid());

            var rockContext = new RockContext();
            var entityTypes = new EntityTypeService(rockContext).GetEntities()
                              .Where(t => !exclusions.Contains(t.Guid))
                              .OrderBy(t => t.FriendlyName)
                              .ToList();

            entityTypePicker.IncludeGlobalOption = false;
            entityTypeFilter.IncludeGlobalOption = false;

            entityTypePicker.EntityTypes = entityTypes;
            entityTypeFilter.EntityTypes = entityTypes;

            entityTypeFilter.SetValue(rFilter.GetUserPreference(AttributeKey.EntityType));

            if (_hasEntityTypeBlockSetting)
            {
                pnlEntityInfo.Visible = false;

                var entityTypeField = gCategories.ColumnsOfType <RockBoundField>().FirstOrDefault(a => a.DataField == AttributeKey.EntityType);
                if (entityTypeField != null)
                {
                    entityTypeField.Visible = false;
                }

                var entityQualifierField = gCategories.ColumnsOfType <RockBoundField>().FirstOrDefault(a => a.DataField == "EntityQualifierField");
                if (entityQualifierField != null)
                {
                    entityQualifierField.Visible = false;
                }

                var entityQualifierValue = gCategories.ColumnsOfType <RockBoundField>().FirstOrDefault(a => a.DataField == AttributeKey.EntityQualifierValue);
                if (entityQualifierValue != null)
                {
                    entityQualifierValue.Visible = false;
                }

                catpParentCategory.Visible = false;

                rFilter.Visible = false;
            }

            gCategories.DataSource = GetCategories()
                                     .Select(c => new
            {
                Id                   = c.Id,
                Name                 = c.Name,
                Description          = c.Description,
                IconCssClass         = c.IconCssClass,
                ChildCount           = c.ChildCategories.Count(),
                EntityType           = c.EntityType.Name,
                EntityQualifierField = c.EntityTypeQualifierColumn,
                EntityQualifierValue = c.EntityTypeQualifierValue,
                IsSystem             = c.IsSystem
            }).ToList();

            gCategories.EntityTypeId = EntityTypeCache.Get <Rock.Model.Category>().Id;
            gCategories.DataBind();
        }
Exemplo n.º 6
0
        private void DisplayDetails()
        {
            var registrationSlug = PageParameter("Slug");

            var eventItemOccurrenceId = PageParameter("EventOccurrenceId").AsInteger();

            if (eventItemOccurrenceId == 0 && registrationSlug.IsNullOrWhiteSpace())
            {
                lOutput.Text = "<div class='alert alert-warning'>No event was available from the querystring.</div>";
                return;
            }

            EventItemOccurrence   eventItemOccurrence = null;
            Dictionary <int, int> registrationCounts  = null;

            using (var rockContext = new RockContext())
            {
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
                var qry = eventItemOccurrenceService
                          .Queryable("EventItem, EventItem.Photo, Campus, Linkages")
                          .Include(e => e.Linkages.Select(l => l.RegistrationInstance));

                if (eventItemOccurrenceId > 0)
                {
                    qry = qry.Where(i => i.Id == eventItemOccurrenceId);
                }
                else
                {
                    qry = qry.Where(i => i.Linkages.Any(l => l.UrlSlug == registrationSlug));
                }

                eventItemOccurrence = qry.FirstOrDefault();

                registrationCounts = qry
                                     .SelectMany(o => o.Linkages)
                                     .SelectMany(l => l.RegistrationInstance.Registrations)
                                     .Select(r => new { r.RegistrationInstanceId, RegistrantCount = r.Registrants.Where(reg => !reg.OnWaitList).Count() })
                                     .GroupBy(r => r.RegistrationInstanceId)
                                     .Select(r => new { RegistrationInstanceId = r.Key, TotalRegistrantCount = r.Sum(rr => rr.RegistrantCount) })
                                     .ToDictionary(r => r.RegistrationInstanceId, r => r.TotalRegistrantCount);


                if (eventItemOccurrence == null)
                {
                    lOutput.Text = "<div class='alert alert-warning'>We could not find that event.</div>";
                    return;
                }

                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));

                var campusEntityType = EntityTypeCache.Get("Rock.Model.Campus");
                var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                if (contextCampus != null)
                {
                    mergeFields.Add("CampusContext", contextCampus);
                }

                // determine registration status (Register, Full, or Join Wait List) for each unique registration instance
                Dictionary <int, string> registrationStatusLabels = new Dictionary <int, string>();
                var registrationInstances = eventItemOccurrence
                                            .Linkages
                                            .Where(l => l.RegistrationInstanceId != null)
                                            .Select(a => a.RegistrationInstance)
                                            .Distinct();

                foreach (var registrationInstance in registrationInstances)
                {
                    int?maxRegistrantCount       = null;
                    var currentRegistrationCount = 0;

                    if (registrationInstance != null)
                    {
                        maxRegistrantCount = registrationInstance.MaxAttendees;
                    }


                    int?registrationSpotsAvailable = null;
                    int registrationCount          = 0;
                    if (maxRegistrantCount.HasValue && registrationCounts.TryGetValue(registrationInstance.Id, out registrationCount))
                    {
                        currentRegistrationCount   = registrationCount;
                        registrationSpotsAvailable = maxRegistrantCount - currentRegistrationCount;
                    }

                    string registrationStatusLabel = "Register";

                    if (registrationSpotsAvailable.HasValue && registrationSpotsAvailable.Value < 1)
                    {
                        if (registrationInstance.RegistrationTemplate.WaitListEnabled)
                        {
                            registrationStatusLabel = "Join Wait List";
                        }
                        else
                        {
                            registrationStatusLabel = "Full";
                        }
                    }

                    registrationStatusLabels.Add(registrationInstance.Id, registrationStatusLabel);
                }

                // Status of first registration instance
                mergeFields.Add("RegistrationStatusLabel", registrationStatusLabels.Values.FirstOrDefault());


                // Status of each registration instance
                mergeFields.Add("RegistrationStatusLabels", registrationStatusLabels);

                mergeFields.Add("EventItemOccurrence", eventItemOccurrence);
                mergeFields.Add("Event", eventItemOccurrence != null ? eventItemOccurrence.EventItem : null);
                mergeFields.Add("CurrentPerson", CurrentPerson);

                lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                if (GetAttributeValue("SetPageTitle").AsBoolean())
                {
                    string pageTitle = eventItemOccurrence != null ? eventItemOccurrence.EventItem.Name : "Event";
                    RockPage.PageTitle    = pageTitle;
                    RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private bool SetFilterControls()
        {
            // Get and verify the calendar id
            if (_calendarId <= 0)
            {
                ShowError("Configuration Error", "The 'Event Calendar' setting has not been set correctly.");
                return(false);
            }

            // Get and verify the view mode
            ViewMode = GetAttributeValue("DefaultViewOption");
            if (!GetAttributeValue(string.Format("Show{0}View", ViewMode)).AsBoolean())
            {
                ShowError("Configuration Error", string.Format("The Default View Option setting has been set to '{0}', but the Show {0} View setting has not been enabled.", ViewMode));
                return(false);
            }

            // Show/Hide calendar control
            pnlCalendar.Visible = GetAttributeValue("ShowSmallCalendar").AsBoolean();

            // Get the first/last dates based on today's date and the viewmode setting
            var today = RockDateTime.Today;

            FilterStartDate = today;
            FilterEndDate   = today;
            if (ViewMode == "Week")
            {
                FilterStartDate = today.StartOfWeek(_firstDayOfWeek);
                FilterEndDate   = today.EndOfWeek(_firstDayOfWeek);
            }
            else if (ViewMode == "Month")
            {
                FilterStartDate = new DateTime(today.Year, today.Month, 1);
                FilterEndDate   = FilterStartDate.Value.AddMonths(1).AddDays(-1);
            }

            // Setup small calendar Filter
            calEventCalendar.FirstDayOfWeek = _firstDayOfWeek.ConvertToInt().ToString().ConvertToEnum <FirstDayOfWeek>();
            calEventCalendar.SelectedDates.Clear();
            calEventCalendar.SelectedDates.SelectRange(FilterStartDate.Value, FilterEndDate.Value);

            // Setup different dates if QueryString is set on load
            var selectedDate = PageParameter(GetAttributeValue("DateParameterName")).AsDateTime();

            if (selectedDate.HasValue)
            {
                if (selectedDate != null)
                {
                    SelectedDate = selectedDate;
                    ResetCalendarSelection();
                }
            }

            // Setup Campus Filter
            var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList();

            rcwCampus.Visible = GetAttributeValue("CampusFilterDisplayMode").AsInteger() > 1;

            if (campusGuidList.Any())
            {
                cblCampus.DataSource = CampusCache.All(false).Where(c => campusGuidList.Contains(c.Guid));
            }
            else
            {
                cblCampus.DataSource = CampusCache.All(false);
            }

            cblCampus.DataBind();

            if (cblCampus.Items.Count == 1)
            {
                CampusPanelClosed = false;
                CampusPanelOpen   = false;
                rcwCampus.Visible = false;
            }

            // Check for Campus Parameter
            var campusId = PageParameter(GetAttributeValue("CampusParameterName")).AsIntegerOrNull();

            if (campusId.HasValue)
            {
                // Check if there's a campus with this id.
                var campus = CampusCache.Get(campusId.Value);
                if (campus != null)
                {
                    cblCampus.SetValue(campusId.Value);
                }
            }
            else
            {
                if (GetAttributeValue("EnableCampusContext").AsBoolean())
                {
                    var contextCampus = RockPage.GetCurrentContext(EntityTypeCache.Get("Rock.Model.Campus")) as Campus;
                    if (contextCampus != null)
                    {
                        cblCampus.SetValue(contextCampus.Id);
                    }
                }
            }

            // Setup Category Filter
            var selectedCategoryGuids = GetAttributeValue("FilterCategories").SplitDelimitedValues(true).AsGuidList();

            rcwCategory.Visible = selectedCategoryGuids.Any() && GetAttributeValue("CategoryFilterDisplayMode").AsInteger() > 1;
            var definedType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.MARKETING_CAMPAIGN_AUDIENCE_TYPE.AsGuid());

            if (definedType != null)
            {
                cblCategory.DataSource = definedType.DefinedValues.Where(v => selectedCategoryGuids.Contains(v.Guid));
                cblCategory.DataBind();
            }

            var categoryId = PageParameter(GetAttributeValue("CategoryParameterName")).AsIntegerOrNull();

            if (categoryId.HasValue)
            {
                if (definedType.DefinedValues.Where(v => selectedCategoryGuids.Contains(v.Guid) && v.Id == categoryId.Value).FirstOrDefault() != null)
                {
                    cblCategory.SetValue(categoryId.Value);
                }
            }

            // Date Range Filter
            drpDateRange.Visible       = GetAttributeValue("ShowDateRangeFilter").AsBoolean();
            lbDateRangeRefresh.Visible = drpDateRange.Visible;
            drpDateRange.LowerValue    = FilterStartDate;
            drpDateRange.UpperValue    = FilterEndDate;

            // Get the View Modes, and only show them if more than one is visible
            var viewsVisible = new List <bool> {
                GetAttributeValue("ShowDayView").AsBoolean(),
                GetAttributeValue("ShowWeekView").AsBoolean(),
                GetAttributeValue("ShowMonthView").AsBoolean()
            };
            var howManyVisible = viewsVisible.Where(v => v).Count();

            btnDay.Visible   = howManyVisible > 1 && viewsVisible[0];
            btnWeek.Visible  = howManyVisible > 1 && viewsVisible[1];
            btnMonth.Visible = howManyVisible > 1 && viewsVisible[2];

            // Set filter visibility
            bool showFilter = pnlCalendar.Visible || rcwCampus.Visible || rcwCategory.Visible || drpDateRange.Visible;

            pnlFilters.Visible = showFilter;
            pnlList.CssClass   = showFilter ? "col-md-9" : "col-md-12";

            return(true);
        }
        /// <summary>
        /// Get the Rock Entity Type information for the entity type displayed by this block.
        /// </summary>
        /// <returns></returns>
        private bool InitializeEntityType()
        {
            _entityType = EntityTypeCache.Get(this._entitySystemType);

            return(_entityType != null);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Updates any Cache Objects that are associated with this entity
        /// </summary>
        /// <param name="entityState">State of the entity.</param>
        /// <param name="dbContext">The database context.</param>
        public void UpdateCache(EntityState entityState, Rock.Data.DbContext dbContext)
        {
            AttributeCache.UpdateCachedEntity(this.Id, entityState);
            AttributeCache.UpdateCacheEntityAttributes(this, entityState);

            int?   entityTypeId;
            string entityTypeQualifierColumn;
            string entityTypeQualifierValue;

            if (entityState == EntityState.Deleted)
            {
                entityTypeId = originalEntityTypeId;
                entityTypeQualifierColumn = originalEntityTypeQualifierColumn;
                entityTypeQualifierValue  = originalEntityTypeQualifierValue;
            }
            else
            {
                entityTypeId = this.EntityTypeId;
                entityTypeQualifierColumn = this.EntityTypeQualifierColumn;
                entityTypeQualifierValue  = this.EntityTypeQualifierValue;
            }

            if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && string.IsNullOrEmpty(entityTypeQualifierColumn) && string.IsNullOrEmpty(entityTypeQualifierValue))
            {
                GlobalAttributesCache.Remove();
            }

            if ((!entityTypeId.HasValue || entityTypeId.Value == 0) && entityTypeQualifierColumn == Attribute.SYSTEM_SETTING_QUALIFIER && string.IsNullOrEmpty(entityTypeQualifierValue))
            {
                Rock.Web.SystemSettings.Remove();
            }

            if (entityTypeId.HasValue)
            {
                if (entityTypeId == EntityTypeCache.GetId <Block>())
                {
                    // Update BlockTypes/Blocks that reference this attribute
                    if (entityTypeQualifierColumn.Equals("BlockTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?blockTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (blockTypeId.HasValue)
                        {
                            BlockTypeCache.FlushItem(blockTypeId.Value);

                            foreach (var blockId in new BlockService(dbContext as RockContext).GetByBlockTypeId(blockTypeId.Value).Select(a => a.Id).ToList())
                            {
                                BlockCache.FlushItem(blockId);
                            }
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <DefinedValue>())
                {
                    // Update DefinedTypes/DefinedValues that reference this attribute
                    if (entityTypeQualifierColumn.Equals("DefinedTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?definedTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (definedTypeId.HasValue)
                        {
                            DefinedTypeCache.FlushItem(definedTypeId.Value);

                            foreach (var definedValueId in new DefinedValueService(dbContext as RockContext).GetByDefinedTypeId(definedTypeId.Value).Select(a => a.Id).ToList())
                            {
                                DefinedValueCache.FlushItem(definedValueId);
                            }
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <WorkflowActivityType>())
                {
                    if (entityTypeQualifierColumn.Equals("ActivityTypeId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?activityTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (activityTypeId.HasValue)
                        {
                            WorkflowActivityTypeCache.FlushItem(activityTypeId.Value);
                        }
                    }
                }
                else if (entityTypeId == EntityTypeCache.GetId <GroupType>())
                {
                    if (entityTypeQualifierColumn.Equals("Id", StringComparison.OrdinalIgnoreCase))
                    {
                        int?groupTypeId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (groupTypeId.HasValue)
                        {
                            GroupTypeCache.FlushItem(groupTypeId.Value);
                        }
                    }
                    else if (entityTypeQualifierColumn.Equals("GroupTypePurposeValueId", StringComparison.OrdinalIgnoreCase))
                    {
                        int?groupTypePurposeValueId = entityTypeQualifierValue.AsIntegerOrNull();
                        if (groupTypePurposeValueId.HasValue)
                        {
                            foreach (var groupTypeId in GroupTypeCache.All().Where(a => a.GroupTypePurposeValueId == groupTypePurposeValueId.Value).Select(a => a.Id).ToList())
                            {
                                GroupTypeCache.FlushItem(groupTypeId);
                            }
                        }
                    }
                }
                else if (entityTypeId.HasValue)
                {
                    // some other EntityType. If it the EntityType has a CacheItem associated with it, clear out all the CachedItems of that type to ensure they have a clean read of the Attributes that were Added, Changed or Removed
                    EntityTypeCache entityType = EntityTypeCache.Get(entityTypeId.Value, dbContext as RockContext);

                    if (entityType?.HasEntityCache() == true)
                    {
                        entityType.ClearCachedItems();
                    }
                }
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            if (_workflowType != null)
            {
                pnlWorkflowList.Visible = true;

                var idCol = gWorkflows.ColumnsOfType <BoundField>().Where(c => c.DataField == "WorkflowId").FirstOrDefault();
                if (idCol != null)
                {
                    idCol.Visible = !string.IsNullOrWhiteSpace(_workflowType.WorkflowIdPrefix);
                }

                var rockContext     = new RockContext();
                var workflowService = new WorkflowService(rockContext);

                var qry = workflowService
                          .Queryable("Activities.ActivityType,InitiatorPersonAlias.Person").AsNoTracking()
                          .Where(w => w.WorkflowTypeId.Equals(_workflowType.Id));

                // Activated Date Range Filter
                if (drpActivated.LowerValue.HasValue)
                {
                    qry = qry.Where(w => w.ActivatedDateTime >= drpActivated.LowerValue.Value);
                }
                if (drpActivated.UpperValue.HasValue)
                {
                    DateTime upperDate = drpActivated.UpperValue.Value.Date.AddDays(1);
                    qry = qry.Where(w => w.ActivatedDateTime.Value < upperDate);
                }

                // State Filter
                List <string> states = cblState.SelectedValues;
                if (states.Count == 1)      // Don't filter if none or both options are selected
                {
                    if (states[0] == "Active")
                    {
                        qry = qry.Where(w => !w.CompletedDateTime.HasValue);
                    }
                    else
                    {
                        qry = qry.Where(w => w.CompletedDateTime.HasValue);
                    }
                }

                // Completed Date Range Filter
                if (drpCompleted.LowerValue.HasValue)
                {
                    qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value >= drpCompleted.LowerValue.Value);
                }
                if (drpCompleted.UpperValue.HasValue)
                {
                    DateTime upperDate = drpCompleted.UpperValue.Value.Date.AddDays(1);
                    qry = qry.Where(w => w.CompletedDateTime.HasValue && w.CompletedDateTime.Value < upperDate);
                }

                string name = tbName.Text;
                if (!string.IsNullOrWhiteSpace(name))
                {
                    qry = qry.Where(w => w.Name.StartsWith(name));
                }

                int?personId = ppInitiator.SelectedValue;
                if (personId.HasValue)
                {
                    qry = qry.Where(w => w.InitiatorPersonAlias.PersonId == personId.Value);
                }

                string status = tbStatus.Text;
                if (!string.IsNullOrWhiteSpace(status))
                {
                    qry = qry.Where(w => w.Status.StartsWith(status));
                }

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

                    foreach (var attribute in AvailableAttributes)
                    {
                        var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());
                        qry = attribute.FieldType.Field.ApplyAttributeQueryFilter(qry, filterControl, attribute, workflowService, Rock.Reporting.FilterMode.SimpleFilter);
                    }
                }

                IQueryable <Workflow> workflows = null;

                var sortProperty = gWorkflows.SortProperty;
                if (sortProperty != null)
                {
                    if (sortProperty.Property == "Initiator")
                    {
                        if (sortProperty.Direction == SortDirection.Ascending)
                        {
                            workflows = qry
                                        .OrderBy(w => w.InitiatorPersonAlias.Person.LastName)
                                        .ThenBy(w => w.InitiatorPersonAlias.Person.NickName);
                        }
                        else
                        {
                            workflows = qry
                                        .OrderByDescending(w => w.InitiatorPersonAlias.Person.LastName)
                                        .ThenByDescending(w => w.InitiatorPersonAlias.Person.NickName);
                        }
                    }
                    else
                    {
                        workflows = qry.Sort(sortProperty);
                    }
                }
                else
                {
                    workflows = qry.OrderByDescending(s => s.CreatedDateTime);
                }

                // Since we're not binding to actual workflow list, but are using AttributeField columns,
                // we need to save the workflows into the grid's object list
                var workflowObjectQry = workflows;
                if (gWorkflows.AllowPaging)
                {
                    workflowObjectQry = workflowObjectQry.Skip(gWorkflows.PageIndex * gWorkflows.PageSize).Take(gWorkflows.PageSize);
                }

                gWorkflows.ObjectList = workflowObjectQry.ToList().ToDictionary(k => k.Id.ToString(), v => v as object);

                gWorkflows.EntityTypeId = EntityTypeCache.Get <Workflow>().Id;
                var qryGrid = workflows.Select(w => new
                {
                    w.Id,
                    w.WorkflowId,
                    w.Name,
                    Initiator  = w.InitiatorPersonAlias != null ? w.InitiatorPersonAlias.Person : null,
                    Activities = w.Activities.Where(a => a.ActivatedDateTime.HasValue && !a.CompletedDateTime.HasValue).OrderBy(a => a.ActivityType.Order).Select(a => a.ActivityType.Name),
                    w.CreatedDateTime,
                    Status      = w.Status,
                    IsCompleted = w.CompletedDateTime.HasValue
                });

                gWorkflows.SetLinqDataSource(qryGrid);
                gWorkflows.DataBind();
            }
            else
            {
                pnlWorkflowList.Visible = false;
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            int?   entityTypeId   = PageParameter("EntityTypeId").AsIntegerOrNull();
            string entityTypeName = string.Empty;
            Type   type           = null;

            // Get Entity Type
            if (entityTypeId.HasValue)
            {
                var entityType = EntityTypeCache.Get(entityTypeId.Value);
                if (entityType != null)
                {
                    entityTypeName = entityType.FriendlyName;
                    type           = entityType.GetEntityType();
                }
            }

            // Get Entity Id
            int entityId = PageParameter("EntityId").AsIntegerOrNull() ?? 0;

            // Get object type
            if (type != null)
            {
                if (entityId == 0)
                {
                    iSecured = (ISecured)Activator.CreateInstance(type);
                }
                else
                {
                    // Get the context type since this may be for a non-rock core object
                    Type contextType = null;
                    var  contexts    = Rock.Reflection.SearchAssembly(type.Assembly, typeof(Rock.Data.DbContext));
                    if (contexts.Any())
                    {
                        contextType = contexts.First().Value;
                    }
                    else
                    {
                        contextType = typeof(RockContext);
                    }

                    Type   serviceType = typeof(Rock.Data.Service <>);
                    Type[] modelType   = { type };
                    Type   service     = serviceType.MakeGenericType(modelType);
                    var    getMethod   = service.GetMethod("Get", new Type[] { typeof(int) });

                    var context         = Activator.CreateInstance(contextType);
                    var serviceInstance = Activator.CreateInstance(service, new object[] { context });
                    iSecured = getMethod.Invoke(serviceInstance, new object[] { entityId }) as ISecured;
                }

                var block = iSecured as Rock.Model.Block;
                if (block != null)
                {
                    // If the entity is a block, get any actions that were updated or added by the block type using
                    // one or more SecurityActionAttributes.
                    var blockCache = BlockCache.Get(block.Id);
                    if (blockCache != null && blockCache.BlockType != null)
                    {
                        // just in case the block hasn't had its security actions set (they get loaded on page load), set them
                        if (blockCache.BlockType.SecurityActions == null)
                        {
                            if (block.BlockType.Path.IsNotNullOrWhiteSpace())
                            {
                                blockCache.BlockType.SetSecurityActions(TemplateControl.LoadControl(block.BlockType.Path) as RockBlock);
                            }
                            if (block.BlockType.EntityTypeId.HasValue)
                            {
                                blockCache.BlockType.SetSecurityActions(blockCache.BlockType.GetCompiledType());
                            }
                        }

                        foreach (var action in blockCache.BlockType.SecurityActions)
                        {
                            if (block.SupportedActions.ContainsKey(action.Key))
                            {
                                block.SupportedActions[action.Key] = action.Value;
                            }
                            else
                            {
                                block.SupportedActions.Add(action.Key, action.Value);
                            }
                        }
                    }

                    iSecured = block;
                }

                if (iSecured != null)
                {
                    if (iSecured.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                    {
                        if (iSecured.SupportedActions.Any())
                        {
                            lActionDescription.Text = iSecured.SupportedActions.FirstOrDefault().Value;
                        }

                        rptActions.DataSource = iSecured.SupportedActions;
                        rptActions.DataBind();

                        rGrid.DataKeyNames        = new string[] { "Id" };
                        rGrid.GridReorder        += new GridReorderEventHandler(rGrid_GridReorder);
                        rGrid.GridRebind         += new GridRebindEventHandler(rGrid_GridRebind);
                        rGrid.RowDataBound       += new GridViewRowEventHandler(rGrid_RowDataBound);
                        rGrid.ShowHeaderWhenEmpty = false;
                        rGrid.EmptyDataText       = string.Empty;
                        rGrid.ShowActionRow       = false;

                        rGridParentRules.DataKeyNames        = new string[] { "Id" };
                        rGridParentRules.ShowHeaderWhenEmpty = false;
                        rGridParentRules.EmptyDataText       = string.Empty;
                        rGridParentRules.ShowActionRow       = false;

                        BindRoles();

                        string scriptFormat = @"
                    Sys.Application.add_load(function () {{
                        $('#modal-popup div.modal-header h3 small', window.parent.document).html('{0}');
                    }});
                ";
                        string script       = string.Format(scriptFormat, HttpUtility.JavaScriptStringEncode(iSecured.ToString()));

                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("set-html-{0}", this.ClientID), script, true);
                    }
                    else
                    {
                        nbMessage.Text = "Unfortunately, you are not able to edit security because you do not belong to a role that has been configured to allow administration of this item.";
                    }
                }
                else
                {
                    nbMessage.Text = "The item you are trying to secure does not exist or does not implement ISecured.";
                }
            }
            else
            {
                nbMessage.Text = string.Format("The requested entity type ('{0}') could not be loaded to determine security attributes.", entityTypeName);
            }

            base.OnInit(e);
        }
        /// <summary>
        /// Sets the filters.
        /// </summary>
        private void SetFilters(bool setValues)
        {
            using (var rockContext = new RockContext())
            {
                string sessionKey       = string.Format("ConnectionSearch_{0}", this.BlockId);
                var    searchSelections = Session[sessionKey] as Dictionary <string, string>;
                setValues = setValues && searchSelections != null;

                var connectionType = new ConnectionTypeService(rockContext).Get(GetAttributeValue("ConnectionTypeId").AsInteger());

                if (!GetAttributeValue("DisplayNameFilter").AsBoolean())
                {
                    tbSearchName.Visible = false;
                }

                if (GetAttributeValue("DisplayCampusFilter").AsBoolean())
                {
                    cblCampus.Visible    = true;
                    cblCampus.DataSource = CampusCache.All(GetAttributeValue("DisplayInactiveCampuses").AsBoolean());
                    cblCampus.DataBind();
                }
                else
                {
                    cblCampus.Visible = false;
                }

                if (setValues)
                {
                    if (searchSelections.ContainsKey("tbSearchName"))
                    {
                        tbSearchName.Text = searchSelections["tbSearchName"];
                    }
                    if (searchSelections.ContainsKey("cblCampus"))
                    {
                        var selectedItems = searchSelections["cblCampus"].SplitDelimitedValues().AsIntegerList();
                        cblCampus.SetValues(selectedItems);
                    }
                }
                else if (GetAttributeValue("EnableCampusContext").AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Get("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        cblCampus.SetValue(contextCampus.Id.ToString());
                    }
                }

                if (GetAttributeValue("DisplayAttributeFilters").AsBoolean())
                {
                    // Parse the attribute filters
                    AvailableAttributes = new List <AttributeCache>();
                    if (connectionType != null)
                    {
                        int entityTypeId = new ConnectionOpportunity().TypeId;
                        foreach (var attributeModel in new AttributeService(new RockContext()).Queryable()
                                 .Where(a =>
                                        a.EntityTypeId == entityTypeId &&
                                        a.EntityTypeQualifierColumn.Equals("ConnectionTypeId", StringComparison.OrdinalIgnoreCase) &&
                                        a.EntityTypeQualifierValue.Equals(connectionType.Id.ToString()) &&
                                        a.AllowSearch == true)
                                 .OrderBy(a => a.Order)
                                 .ThenBy(a => a.Name))
                        {
                            AvailableAttributes.Add(AttributeCache.Get(attributeModel));
                        }
                    }

                    // Clear the filter controls
                    phAttributeFilters.Controls.Clear();

                    if (AvailableAttributes != null)
                    {
                        foreach (var attribute in AvailableAttributes)
                        {
                            string controlId = "filter_" + attribute.Id.ToString();
                            var    control   = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, controlId, false, Rock.Reporting.FilterMode.SimpleFilter);
                            if (control != null)
                            {
                                if (control is IRockControl)
                                {
                                    var rockControl = (IRockControl)control;
                                    rockControl.Label = attribute.Name;
                                    rockControl.Help  = attribute.Description;
                                    phAttributeFilters.Controls.Add(control);
                                }
                                else
                                {
                                    var wrapper = new RockControlWrapper();
                                    wrapper.ID    = control.ID + "_wrapper";
                                    wrapper.Label = attribute.Name;
                                    wrapper.Controls.Add(control);
                                    phAttributeFilters.Controls.Add(wrapper);
                                }

                                if (setValues && searchSelections.ContainsKey(controlId))
                                {
                                    var values = searchSelections[controlId].FromJsonOrNull <List <string> >();
                                    attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                                }
                            }
                        }
                    }
                }
                else
                {
                    phAttributeFilters.Visible = false;
                }
            }
        }
        /// <summary>
        /// Updates the list.
        /// </summary>
        private void UpdateList()
        {
            using (var rockContext = new RockContext())
            {
                var searchSelections = new Dictionary <string, string>();

                var connectionTypeId             = GetAttributeValue("ConnectionTypeId").AsInteger();
                var connectionType               = new ConnectionTypeService(rockContext).Get(connectionTypeId);
                var connectionOpportunityService = new ConnectionOpportunityService(rockContext);

                var qrySearch = connectionOpportunityService.Queryable().Where(a => a.ConnectionTypeId == connectionTypeId && a.IsActive == true);

                if (GetAttributeValue("DisplayNameFilter").AsBoolean())
                {
                    if (!string.IsNullOrWhiteSpace(tbSearchName.Text))
                    {
                        searchSelections.Add("tbSearchName", tbSearchName.Text);
                        var searchTerms = tbSearchName.Text.ToLower().SplitDelimitedValues(true);
                        qrySearch = qrySearch.Where(o => searchTerms.Any(t => t.Contains(o.Name.ToLower()) || o.Name.ToLower().Contains(t)));
                    }
                }

                if (GetAttributeValue("DisplayCampusFilter").AsBoolean())
                {
                    cblCampus.Label = GetAttributeValue("CampusLabel");
                    var searchCampuses = cblCampus.SelectedValuesAsInt;
                    if (searchCampuses.Count > 0)
                    {
                        searchSelections.Add("cblCampus", searchCampuses.AsDelimited("|"));
                        qrySearch = qrySearch.Where(o => o.ConnectionOpportunityCampuses.Any(c => searchCampuses.Contains(c.CampusId)));
                    }
                }

                if (GetAttributeValue("DisplayAttributeFilters").AsBoolean())
                {
                    // Filter query by any configured attribute filters
                    if (AvailableAttributes != null && AvailableAttributes.Any())
                    {
                        foreach (var attribute in AvailableAttributes)
                        {
                            string filterControlId = "filter_" + attribute.Id.ToString();
                            var    filterControl   = phAttributeFilters.FindControl(filterControlId);
                            qrySearch = attribute.FieldType.Field.ApplyAttributeQueryFilter(qrySearch, filterControl, attribute, connectionOpportunityService, Rock.Reporting.FilterMode.SimpleFilter);
                        }
                    }
                }

                string sessionKey = string.Format("ConnectionSearch_{0}", this.BlockId);
                Session[sessionKey] = searchSelections;

                var opportunities = qrySearch.OrderBy(s => s.PublicName).ToList();

                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("CurrentPerson", CurrentPerson);
                mergeFields.Add("CampusContext", RockPage.GetCurrentContext(EntityTypeCache.Get("Rock.Model.Campus")) as Campus);
                var pageReference = new PageReference(GetAttributeValue("DetailPage"), null);
                mergeFields.Add("DetailPage", BuildDetailPageUrl(pageReference.BuildUrl()));

                // iterate through the opportunities and lava merge the summaries and descriptions
                foreach (var opportunity in opportunities)
                {
                    opportunity.Summary     = opportunity.Summary.ResolveMergeFields(mergeFields);
                    opportunity.Description = opportunity.Description.ResolveMergeFields(mergeFields);
                }

                mergeFields.Add("Opportunities", opportunities);

                lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);

                if (GetAttributeValue("SetPageTitle").AsBoolean())
                {
                    string pageTitle = "Connection";
                    RockPage.PageTitle    = pageTitle;
                    RockPage.BrowserTitle = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                    RockPage.Header.Title = String.Format("{0} | {1}", pageTitle, RockPage.Site.Name);
                }
            }
        }
Exemplo n.º 14
0
        private List <JournalEntryLine> GetGlEntries(RockContext rockContext, FinancialBatch financialBatch, string journalCode, int period, ref string debugLava, string DescriptionLava = "")
        {
            if (string.IsNullOrWhiteSpace(DescriptionLava))
            {
                DescriptionLava = "{{ Batch.Id }}: {{ Batch.Name }}";
            }
            //
            // Group/Sum Transactions by Account and Project since Project can come from Account or Transaction Details
            //
            var batchTransactions = new List <GLTransaction>();
            var registrationLinks = new List <RegistrationInstance>();
            var groupMemberLinks  = new List <GroupMember>();

            foreach (var transaction in financialBatch.Transactions)
            {
                transaction.LoadAttributes();
                foreach (var transactionDetail in transaction.TransactionDetails)
                {
                    transactionDetail.LoadAttributes();
                    transactionDetail.Account.LoadAttributes();

                    var detailProject      = transactionDetail.GetAttributeValue("rocks.kfs.ShelbyFinancials.Project").AsGuidOrNull();
                    var transactionProject = transaction.GetAttributeValue("rocks.kfs.ShelbyFinancials.Project").AsGuidOrNull();
                    var accountProject     = transactionDetail.Account.GetAttributeValue("rocks.kfs.ShelbyFinancials.Project").AsGuidOrNull();

                    var projectCode = string.Empty;
                    if (detailProject != null)
                    {
                        projectCode = DefinedValueCache.Get(( Guid )detailProject).Value;
                    }
                    else if (transactionProject != null)
                    {
                        projectCode = DefinedValueCache.Get(( Guid )transactionProject).Value;
                    }
                    else if (accountProject != null)
                    {
                        projectCode = DefinedValueCache.Get(( Guid )accountProject).Value;
                    }

                    if (transactionDetail.EntityTypeId.HasValue)
                    {
                        var registrationEntityType = EntityTypeCache.Get(typeof(Rock.Model.Registration));
                        var groupMemberEntityType  = EntityTypeCache.Get(typeof(Rock.Model.GroupMember));

                        if (transactionDetail.EntityId.HasValue && transactionDetail.EntityTypeId == registrationEntityType.Id)
                        {
                            foreach (var registration in new RegistrationService(rockContext)
                                     .Queryable().AsNoTracking()
                                     .Where(r =>
                                            r.RegistrationInstance != null &&
                                            r.RegistrationInstance.RegistrationTemplate != null &&
                                            r.Id == transactionDetail.EntityId))
                            {
                                registrationLinks.Add(registration.RegistrationInstance);
                            }
                        }
                        if (transactionDetail.EntityId.HasValue && transactionDetail.EntityTypeId == groupMemberEntityType.Id)
                        {
                            foreach (var groupMember in new GroupMemberService(rockContext)
                                     .Queryable().AsNoTracking()
                                     .Where(gm =>
                                            gm.Group != null &&
                                            gm.Id == transactionDetail.EntityId))
                            {
                                groupMemberLinks.Add(groupMember);
                            }
                        }
                    }

                    var transactionItem = new GLTransaction()
                    {
                        Amount             = transactionDetail.Amount,
                        FinancialAccountId = transactionDetail.AccountId,
                        Project            = projectCode
                    };

                    batchTransactions.Add(transactionItem);
                }
            }

            var batchTransactionsSummary = batchTransactions
                                           .GroupBy(d => new { d.FinancialAccountId, d.Project })
                                           .Select(s => new GLTransaction
            {
                FinancialAccountId = s.Key.FinancialAccountId,
                Project            = s.Key.Project,
                Amount             = s.Sum(f => ( decimal? )f.Amount) ?? 0.0M
            })
                                           .ToList();

            var batchSummary = new List <GLBatchTotals>();

            foreach (var summary in batchTransactionsSummary)
            {
                var account = new FinancialAccountService(rockContext).Get(summary.FinancialAccountId);
                account.LoadAttributes();

                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("Account", account);
                mergeFields.Add("Summary", summary);
                mergeFields.Add("Batch", financialBatch);
                mergeFields.Add("Registrations", registrationLinks);
                mergeFields.Add("GroupMembers", groupMemberLinks);
                mergeFields.Add("JournalCode", journalCode);
                mergeFields.Add("Period", period);

                var batchSummaryItem = new GLBatchTotals()
                {
                    CompanyNumber       = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.Company"),
                    RegionNumber        = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.Region"),
                    SuperFundNumber     = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.SuperFund"),
                    FundNumber          = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.Fund"),
                    LocationNumber      = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.Location"),
                    CostCenterNumber    = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.CostCenter"),
                    DepartmentNumber    = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.Department"),
                    CreditAccountNumber = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.CreditAccount"),
                    DebitAccountNumber  = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.DebitAccount"),
                    AccountSub          = account.GetAttributeValue("rocks.kfs.ShelbyFinancials.AccountSub"),
                    Amount             = summary.Amount,
                    Project            = summary.Project,
                    JournalNumber      = financialBatch.Id,
                    JournalDescription = DescriptionLava.ResolveMergeFields(mergeFields),
                    Date = financialBatch.BatchStartDateTime ?? RockDateTime.Now,
                    Note = financialBatch.Note
                };

                if (debugLava.Length < 6 && debugLava.AsBoolean())
                {
                    debugLava = mergeFields.lavaDebugInfo();
                }

                batchSummary.Add(batchSummaryItem);
            }

            return(GenerateLineItems(batchSummary));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Checks the database for existing import data.
        /// returns false if an error occurred
        /// </summary>
        /// <param name="importUser">The import user.</param>
        /// <returns></returns>
        private bool LoadExistingData(string importUser)
        {
            var lookupContext = new RockContext();
            var personService = new PersonService(lookupContext);
            var importPerson  = personService.GetByFullName(importUser, includeDeceased: false, allowFirstNameOnly: true).FirstOrDefault();

            if (importPerson == null)
            {
                importPerson = personService.Queryable().FirstOrDefault();
                if (importPerson == null)
                {
                    LogException("CheckExistingImport", "The named import user was not found, and none could be created.");
                    return(false);
                }
            }

            ImportPersonAliasId = importPerson.PrimaryAliasId;

            var anonymousGiver = personService.GetByFullName("Anonymous, Giver", includeDeceased: false, allowFirstNameOnly: true).FirstOrDefault();

            if (anonymousGiver == null)
            {
                anonymousGiver = personService.Queryable().FirstOrDefault(p => p.Guid.ToString().ToUpper() == "802235DC-3CA5-94B0-4326-AACE71180F48");
                if (anonymousGiver == null && requireAnonymousGiver)
                {
                    LogException("CheckExistingImport", "The record for anonymous giving could not be found, please add a person with first name 'Giver' and last name 'Anonymous'.  Optionally, consider disabling RequireAnonymousGiver in the App.Config file.");
                    return(false);
                }
            }

            if (anonymousGiver != null)
            {
                AnonymousGiverAliasId = anonymousGiver.PrimaryAliasId;
            }

            PersonAttributeCategoryEntityTypeId = EntityTypeCache.Get("Rock.Model.Attribute").Id;

            ReportProgress(0, "Checking for existing data...");

            // Don't track groups in this context, just use it as a static reference
            ImportedFamilies = lookupContext.Groups.AsNoTracking()
                               .Where(g => g.GroupTypeId == FamilyGroupTypeId && g.ForeignKey != null)
                               .OrderBy(g => g.ForeignKey).ToList();

            LoadCampuses();

            LoadPersonKeys(lookupContext);

            ImportedAccounts = new FinancialAccountService(lookupContext).Queryable().AsNoTracking()
                               .Where(a => a.ForeignId != null)
                               .ToDictionary(a => ( int )a.ForeignId, a => ( int? )a.Id);

            if (csvBatchUseForeignKey)
            {
                ImportedBatches = new FinancialBatchService(lookupContext).Queryable().AsNoTracking()
                                  .Where(b => b.ForeignKey != null)
                                  .ToDictionary(b => b.ForeignKey, b => ( int? )b.Id);
            }
            else
            {
                ImportedBatches = new FinancialBatchService(lookupContext).Queryable().AsNoTracking()
                                  .Where(b => b.ForeignId != null)
                                  .ToDictionary(b => b.ForeignId.ToString(), b => ( int? )b.Id);
            }

            LoadImportedGroups(lookupContext);

            LoadImportedGroupTypes(lookupContext);

            LoadImportedLocations(lookupContext);

            return(true);
        }
        /// <summary>
        /// Loads the campuses
        /// </summary>
        protected void LoadCampusDropdowns()
        {
            var campusEntityType = EntityTypeCache.Get(typeof(Campus));
            var currentCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

            var campusIdString = Request.QueryString["CampusId"];

            if (campusIdString != null)
            {
                var campusId = campusIdString.AsInteger();

                // if there is a query parameter, ensure that the Campus Context cookie is set (and has an updated expiration)
                // note, the Campus Context might already match due to the query parameter, but has a different cookie context, so we still need to ensure the cookie context is updated
                currentCampus = SetCampusContext(campusId, false);
            }

            if (currentCampus == null && GetAttributeValue(AttributeKey.DefaultToCurrentUser).AsBoolean() && CurrentPerson != null)
            {
                currentCampus = CurrentPerson.GetFamily().Campus;
            }

            if (currentCampus != null)
            {
                var mergeObjects = new Dictionary <string, object>();
                mergeObjects.Add("CampusName", currentCampus.Name);
                lCurrentCampusSelection.Text = GetAttributeValue(AttributeKey.CampusCurrentItemTemplate).ResolveMergeFields(mergeObjects);
                _currentCampusText           = GetAttributeValue(AttributeKey.CampusCurrentItemTemplate).ResolveMergeFields(mergeObjects);
            }
            else
            {
                lCurrentCampusSelection.Text = GetAttributeValue(AttributeKey.NoCampusText);
                _currentCampusText           = GetAttributeValue(AttributeKey.NoCampusText);
            }

            var campusList = CampusCache.All()
                             .Select(a => new CampusItem {
                Name = a.Name, Id = a.Id
            })
                             .ToList();

            // run lava on each campus
            string dropdownItemTemplate = GetAttributeValue(AttributeKey.CampusDropdownItemTemplate);

            if (!string.IsNullOrWhiteSpace(dropdownItemTemplate))
            {
                foreach (var campus in campusList)
                {
                    var mergeObjects = new Dictionary <string, object>();
                    mergeObjects.Add("CampusName", campus.Name);
                    campus.Name = dropdownItemTemplate.ResolveMergeFields(mergeObjects);
                }
            }

            // check if the campus can be unselected
            if (!string.IsNullOrEmpty(GetAttributeValue(AttributeKey.CampusClearSelectionText)))
            {
                var blankCampus = new CampusItem
                {
                    Name = GetAttributeValue(AttributeKey.CampusClearSelectionText),
                    Id   = Rock.Constants.All.Id
                };

                campusList.Insert(0, blankCampus);
            }

            rptCampuses.DataSource = campusList;
            rptCampuses.DataBind();
        }
Exemplo n.º 17
0
        /// <summary>
        /// Shows the wall.
        /// </summary>
        private void ShowWall()
        {
            var pageRef = CurrentPageReference;

            pageRef.Parameters.AddOrReplace("Page", "PageNum");

            var prayerRequests = new List <PrayerRequest>();

            var qry = new PrayerRequestService(new RockContext())
                      .Queryable()
                      .AsNoTracking()
                      .Where(r => r.ExpirationDate >= RockDateTime.Now &&
                             r.IsApproved == true &&
                             r.IsPublic == true);

            var categoryGuids = (GetAttributeValue("CategoryFilter") ?? string.Empty).SplitDelimitedValues().AsGuidList();

            if (categoryGuids.Any())
            {
                qry = qry.Where(a => a.CategoryId.HasValue && (categoryGuids.Contains(a.Category.Guid) || (a.Category.ParentCategoryId.HasValue && categoryGuids.Contains(a.Category.ParentCategory.Guid))));
            }

            var campusEntity = RockPage.GetCurrentContext(EntityTypeCache.Get(typeof(Campus)));

            if (campusEntity != null)
            {
                var campusId = campusEntity.Id;
                qry = qry.Where(r => r.CampusId.HasValue && r.CampusId == campusId);
            }

            var sortOrder = GetAttributeValue("SortOrder").AsInteger();

            switch (sortOrder)
            {
            case 0:
                qry = qry.OrderByDescending(a => a.EnteredDateTime);
                break;

            case 1:
                qry = qry.OrderBy(a => a.EnteredDateTime);
                break;
            }

            prayerRequests = qry.ToList();

            var pagination = new Pagination();

            pagination.ItemCount   = prayerRequests.Count();
            pagination.PageSize    = GetAttributeValue("PageSize").AsInteger();
            pagination.CurrentPage = PageParameter("Page").AsIntegerOrNull() ?? 1;
            pagination.UrlTemplate = pageRef.BuildUrl();

            var currentPrayerRequests = pagination.GetCurrentPageItems(prayerRequests);

            var commonMergeFields = LavaHelper.GetCommonMergeFields(RockPage);

            var mergeFields = new Dictionary <string, object>(commonMergeFields);

            mergeFields.Add("Pagination", pagination);
            mergeFields.Add("PrayerRequests", currentPrayerRequests);

            Template      template     = null;
            ILavaTemplate lavaTemplate = null;
            var           error        = string.Empty;

            try
            {
                if (LavaService.RockLiquidIsEnabled)
                {
                    template = Template.Parse(GetAttributeValue("LavaTemplate"));

                    LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue("LavaTemplate"));
                }
                else
                {
                    var parseResult = LavaService.ParseTemplate(GetAttributeValue("LavaTemplate"));

                    lavaTemplate = parseResult.Template;
                }
            }
            catch (Exception ex)
            {
                error = string.Format("Lava error: {0}", ex.Message);
            }
            finally
            {
                if (error.IsNotNullOrWhiteSpace())
                {
                    nbError.Text    = error;
                    nbError.Visible = true;
                }

                if (template != null || lavaTemplate != null)
                {
                    if (LavaService.RockLiquidIsEnabled)
                    {
                        template.Registers["EnabledCommands"] = GetAttributeValue("EnabledLavaCommands");
                        lContent.Text = template.Render(Hash.FromDictionary(mergeFields));
                    }
                    else
                    {
                        var lavaContext = LavaService.NewRenderContext(mergeFields, GetAttributeValue("EnabledLavaCommands").SplitDelimitedValues());
                        var result      = LavaService.RenderTemplate(lavaTemplate, lavaContext);

                        lContent.Text = result.Text;
                    }
                }
            }
        }
        /// <summary>
        /// Loads the schedules
        /// </summary>
        private void LoadScheduleDropdowns()
        {
            var scheduleEntityType = EntityTypeCache.Get(typeof(Schedule));
            var currentSchedule    = RockPage.GetCurrentContext(scheduleEntityType) as Schedule;

            var scheduleIdString = Request.QueryString["ScheduleId"];

            if (scheduleIdString != null)
            {
                var scheduleId = scheduleIdString.AsInteger();

                // if there is a query parameter, ensure that the Schedule Context cookie is set (and has an updated expiration)
                // note, the Schedule Context might already match due to the query parameter, but has a different cookie context, so we still need to ensure the cookie context is updated
                currentSchedule = SetScheduleContext(scheduleId, false);
            }

            if (currentSchedule != null)
            {
                var mergeObjects = new Dictionary <string, object>();
                mergeObjects.Add("ScheduleName", currentSchedule.Name);
                lCurrentScheduleSelection.Text = GetAttributeValue(AttributeKey.ScheduleCurrentItemTemplate).ResolveMergeFields(mergeObjects);
                _currentScheduleText           = GetAttributeValue(AttributeKey.ScheduleCurrentItemTemplate).ResolveMergeFields(mergeObjects);
            }
            else
            {
                lCurrentScheduleSelection.Text = GetAttributeValue(AttributeKey.NoScheduleText);
                _currentScheduleText           = GetAttributeValue(AttributeKey.NoScheduleText);
            }

            var schedules = new List <ScheduleItem>();

            if (GetAttributeValue(AttributeKey.ScheduleGroup) != null)
            {
                var selectedSchedule     = GetAttributeValue(AttributeKey.ScheduleGroup);
                var selectedScheduleList = selectedSchedule.Split(',').AsGuidList();

                schedules.AddRange(new ScheduleService(new RockContext()).Queryable()
                                   .Where(a => selectedScheduleList.Contains(a.Guid))
                                   .Select(a => new ScheduleItem {
                    Name = a.Name, Id = a.Id
                })
                                   .OrderBy(s => s.Name)
                                   .ToList()
                                   );
            }

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

            // run lava on each campus
            foreach (var schedule in schedules)
            {
                var mergeObjects = new Dictionary <string, object>();
                mergeObjects.Clear();
                mergeObjects.Add("ScheduleName", schedule.Name);
                schedule.Name = GetAttributeValue(AttributeKey.ScheduleDropdownItemTemplate).ResolveMergeFields(mergeObjects);
            }

            // check if the schedule can be unselected
            if (!string.IsNullOrEmpty(GetAttributeValue(AttributeKey.ScheduleClearSelectionText)))
            {
                var blankCampus = new ScheduleItem
                {
                    Name = GetAttributeValue(AttributeKey.ScheduleClearSelectionText),
                    Id   = Rock.Constants.All.Id
                };

                schedules.Insert(0, blankCampus);
            }

            rptSchedules.DataSource = schedules;
            rptSchedules.DataBind();
        }
        /// <summary>
        /// Gets the merge object list for the current EntitySet
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="fetchCount">The fetch count.</param>
        /// <returns></returns>
        private List <object> GetMergeObjectList(RockContext rockContext, int?fetchCount = null)
        {
            int entitySetId      = hfEntitySetId.Value.AsInteger();
            var entitySetService = new EntitySetService(rockContext);
            var entitySet        = entitySetService.Get(entitySetId);
            Dictionary <int, object> mergeObjectsDictionary = new Dictionary <int, object>();

            // If this EntitySet contains IEntity Items, add those first
            if (entitySet.EntityTypeId.HasValue)
            {
                var qryEntity = entitySetService.GetEntityQuery(entitySetId);

                if (fetchCount.HasValue)
                {
                    qryEntity = qryEntity.Take(fetchCount.Value);
                }

                var  entityTypeCache         = EntityTypeCache.Get(entitySet.EntityTypeId.Value);
                bool isPersonEntityType      = entityTypeCache != null && entityTypeCache.Guid == Rock.SystemGuid.EntityType.PERSON.AsGuid();
                bool isGroupMemberEntityType = entityTypeCache != null && entityTypeCache.Guid == Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid();
                bool combineFamilyMembers    = cbCombineFamilyMembers.Visible && cbCombineFamilyMembers.Checked;

                if ((isGroupMemberEntityType || isPersonEntityType) && combineFamilyMembers)
                {
                    IQueryable <IEntity> qryPersons;
                    if (isGroupMemberEntityType)
                    {
                        qryPersons = qryEntity.OfType <GroupMember>().Select(a => a.Person).Distinct();
                    }
                    else
                    {
                        qryPersons = qryEntity;
                    }

                    Guid familyGroupType       = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                    var  qryFamilyGroupMembers = new GroupMemberService(rockContext).Queryable("GroupRole,Person").AsNoTracking()
                                                 .Where(a => a.Group.GroupType.Guid == familyGroupType)
                                                 .Where(a => qryPersons.Any(aa => aa.Id == a.PersonId));

                    var qryCombined = qryFamilyGroupMembers.Join(
                        qryPersons,
                        m => m.PersonId,
                        p => p.Id,
                        (m, p) => new { GroupMember = m, Person = p })
                                      .GroupBy(a => a.GroupMember.GroupId)
                                      .Select(x => new
                    {
                        GroupId = x.Key,
                        // Order People to match ordering in the GroupMembers.ascx block.
                        Persons =
                            // Adult Male
                            x.Where(xx => xx.GroupMember.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)) &&
                                    xx.GroupMember.Person.Gender == Gender.Male).OrderByDescending(xx => xx.GroupMember.Person.BirthDate).Select(xx => xx.Person)
                            // Adult Female
                            .Concat(x.Where(xx => xx.GroupMember.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)) &&
                                            xx.GroupMember.Person.Gender != Gender.Male).OrderByDescending(xx => xx.GroupMember.Person.BirthDate).Select(xx => xx.Person))
                            // non-adults
                            .Concat(x.Where(xx => !xx.GroupMember.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)))
                                    .OrderByDescending(xx => xx.GroupMember.Person.BirthDate).Select(xx => xx.Person))
                    });

                    foreach (var combinedFamilyItem in qryCombined)
                    {
                        object mergeObject;

                        string commaPersonIds = combinedFamilyItem.Persons.Select(a => a.Id).Distinct().ToList().AsDelimited(",");

                        var primaryGroupPerson = combinedFamilyItem.Persons.FirstOrDefault() as Person;

                        if (mergeObjectsDictionary.ContainsKey(primaryGroupPerson.Id))
                        {
                            foreach (var person in combinedFamilyItem.Persons)
                            {
                                if (!mergeObjectsDictionary.ContainsKey(person.Id))
                                {
                                    primaryGroupPerson = person as Person;
                                    break;
                                }
                            }
                        }

                        // if we are combining from a GroupMemberEntityType list add the GroupMember attributes of the primary person in the combined list
                        if (isGroupMemberEntityType)
                        {
                            var groupMember = qryEntity.OfType <GroupMember>().Where(a => a.PersonId == primaryGroupPerson.Id).FirstOrDefault();
                            primaryGroupPerson.AdditionalLavaFields = primaryGroupPerson.AdditionalLavaFields ?? new Dictionary <string, object>();
                            if (groupMember != null)
                            {
                                primaryGroupPerson.AdditionalLavaFields.AddOrIgnore("GroupMember", groupMember);
                            }
                        }

                        if (combinedFamilyItem.Persons.Count() > 1)
                        {
                            var combinedPerson = primaryGroupPerson.ToJson().FromJsonOrNull <MergeTemplateCombinedPerson>();

                            var familyTitle = RockUdfHelper.ufnCrm_GetFamilyTitle(rockContext, null, combinedFamilyItem.GroupId, commaPersonIds, true);
                            combinedPerson.FullName = familyTitle;

                            var firstNameList = combinedFamilyItem.Persons.Select(a => (a as Person).FirstName).ToList();
                            var nickNameList  = combinedFamilyItem.Persons.Select(a => (a as Person).NickName).ToList();

                            combinedPerson.FirstName     = firstNameList.AsDelimited(", ", " & ");
                            combinedPerson.NickName      = nickNameList.AsDelimited(", ", " & ");
                            combinedPerson.LastName      = primaryGroupPerson.LastName;
                            combinedPerson.SuffixValueId = null;
                            combinedPerson.SuffixValue   = null;
                            mergeObject = combinedPerson;
                        }
                        else
                        {
                            mergeObject = primaryGroupPerson;
                        }

                        mergeObjectsDictionary.AddOrIgnore(primaryGroupPerson.Id, mergeObject);
                    }
                }
                else if (isGroupMemberEntityType)
                {
                    List <int> personIds = new List <int>();

                    foreach (var groupMember in qryEntity.AsNoTracking().OfType <GroupMember>())
                    {
                        var person = groupMember.Person;
                        if (!personIds.Contains(person.Id))
                        {
                            // Attach the person record to rockContext so that navigation properties can be still lazy-loaded if needed (if the lava template needs it)
                            rockContext.People.Attach(person);
                        }

                        person.AdditionalLavaFields = new Dictionary <string, object>();
                        person.AdditionalLavaFields.Add("GroupMember", groupMember);
                        mergeObjectsDictionary.AddOrIgnore(groupMember.PersonId, person);
                        personIds.Add(person.Id);
                    }
                }
                else
                {
                    foreach (var item in qryEntity.AsNoTracking())
                    {
                        mergeObjectsDictionary.AddOrIgnore(item.Id, item);
                    }
                }
            }

            var entitySetItemService = new EntitySetItemService(rockContext);

            string[] emptyJson = new string[] { string.Empty, "{}" };
            var      entitySetItemMergeValuesQry = entitySetItemService.GetByEntitySetId(entitySetId, true).Where(a => !emptyJson.Contains(a.AdditionalMergeValuesJson));

            if (fetchCount.HasValue)
            {
                entitySetItemMergeValuesQry = entitySetItemMergeValuesQry.Take(fetchCount.Value);
            }

            // the entityId to use for NonEntity objects
            int nonEntityId = 1;

            // now, add the additional MergeValues regardless of if the EntitySet contains IEntity items or just Non-IEntity items
            foreach (var additionalMergeValuesItem in entitySetItemMergeValuesQry.AsNoTracking())
            {
                object mergeObject;
                int    entityId;
                if (additionalMergeValuesItem.EntityId > 0)
                {
                    entityId = additionalMergeValuesItem.EntityId;
                }
                else
                {
                    // not pointing to an actual EntityId, so use the nonEntityId for ti
                    entityId = nonEntityId++;
                }

                if (mergeObjectsDictionary.ContainsKey(entityId))
                {
                    mergeObject = mergeObjectsDictionary[entityId];
                }
                else
                {
                    if (entitySet.EntityTypeId.HasValue)
                    {
                        // if already have real entities in our list, don't add additional items to the mergeObjectsDictionary
                        continue;
                    }

                    // non-Entity merge object, so just use Dictionary
                    mergeObject = new Dictionary <string, object>();
                    mergeObjectsDictionary.AddOrIgnore(entityId, mergeObject);
                }

                foreach (var additionalMergeValue in additionalMergeValuesItem.AdditionalMergeValues)
                {
                    if (mergeObject is IEntity)
                    {
                        // add the additional fields to AdditionalLavaFields
                        IEntity mergeEntity = (mergeObject as IEntity);
                        mergeEntity.AdditionalLavaFields = mergeEntity.AdditionalLavaFields ?? new Dictionary <string, object>();
                        object mergeValueObject = additionalMergeValue.Value;

                        // if the mergeValueObject is a JArray (JSON Object), convert it into an ExpandoObject or List<ExpandoObject> so that Lava will work on it
                        if (mergeValueObject is JArray)
                        {
                            var jsonOfObject = mergeValueObject.ToJson();
                            try
                            {
                                mergeValueObject = Rock.Lava.RockFilters.FromJSON(jsonOfObject);
                            }
                            catch (Exception ex)
                            {
                                LogException(new Exception("MergeTemplateEntry couldn't do a FromJSON", ex));
                            }
                        }

                        mergeEntity.AdditionalLavaFields.AddOrIgnore(additionalMergeValue.Key, mergeValueObject);
                    }
                    else if (mergeObject is IDictionary <string, object> )
                    {
                        // anonymous object with no fields yet
                        IDictionary <string, object> nonEntityObject = mergeObject as IDictionary <string, object>;
                        nonEntityObject.AddOrIgnore(additionalMergeValue.Key, additionalMergeValue.Value);
                    }
                    else
                    {
                        throw new Exception(string.Format("Unexpected MergeObject Type: {0}", mergeObject));
                    }
                }
            }

            var result = mergeObjectsDictionary.Select(a => a.Value);

            if (fetchCount.HasValue)
            {
                // make sure the result is limited to fetchCount (even though the above queries are also limited to fetch count)
                result = result.Take(fetchCount.Value);
            }

            return(result.ToList());
        }
Exemplo n.º 20
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Get the entity type
            EntityTypeCache entityType     = null;
            var             entityTypeGuid = GetAttributeValue(action, "EntityType").AsGuidOrNull();

            if (entityTypeGuid.HasValue)
            {
                entityType = EntityTypeCache.Get(entityTypeGuid.Value);
            }
            if (entityType == null)
            {
                errorMessages.Add(string.Format("Entity Type could not be found for selected value ('{0}')!", entityTypeGuid.ToString()));
                return(false);
            }

            var         mergeFields  = GetMergeFields(action);
            RockContext _rockContext = new RockContext();

            // Get the entity
            EntityTypeService entityTypeService  = new EntityTypeService(_rockContext);
            IEntity           entityObject       = null;
            string            entityIdGuidString = GetAttributeValue(action, "EntityIdGuid", true).ResolveMergeFields(mergeFields).Trim();
            var entityGuid = entityIdGuidString.AsGuidOrNull();

            if (entityGuid.HasValue)
            {
                entityObject = entityTypeService.GetEntity(entityType.Id, entityGuid.Value);
            }
            else
            {
                var entityId = entityIdGuidString.AsIntegerOrNull();
                if (entityId.HasValue)
                {
                    entityObject = entityTypeService.GetEntity(entityType.Id, entityId.Value);
                }
            }

            if (entityObject == null)
            {
                errorMessages.Add(string.Format("Entity could not be found for selected value ('{0}')!", entityIdGuidString));
                return(false);
            }

            // Get the property settings
            string propertyName       = GetAttributeValue(action, "PropertyName", true).ResolveMergeFields(mergeFields);
            string propertyValue      = GetAttributeValue(action, "PropertyValue", true).ResolveMergeFields(mergeFields);
            string emptyValueHandling = GetAttributeValue(action, "EmptyValueHandling");

            if (emptyValueHandling == "IGNORE" && String.IsNullOrWhiteSpace(propertyValue))
            {
                action.AddLogEntry("Skipping empty value.");
                return(true);
            }

            PropertyInfo propInf = entityObject.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);

            if (propInf == null)
            {
                errorMessages.Add(string.Format("Property does not exist ('{0}')!", propertyName));
                return(false);
            }

            if (!propInf.CanWrite)
            {
                errorMessages.Add(string.Format("Property is not writable ('{0}')!", entityIdGuidString));
                return(false);
            }

            try
            {
                propInf.SetValue(entityObject, ConvertObject(propertyValue, propInf.PropertyType, emptyValueHandling == "NULL"), null);
            }
            catch (Exception ex) when(ex is InvalidCastException || ex is FormatException || ex is OverflowException)
            {
                errorMessages.Add(string.Format("Could not convert property value ('{0}')! {1}", propertyValue, ex.Message));
                return(false);
            }

            if (!entityObject.IsValid)
            {
                errorMessages.Add(string.Format("Invalid property value ('{0}')! {1}", propertyValue, entityObject.ValidationResults.Select(r => r.ErrorMessage).ToList().AsDelimited(" ")));
                return(false);
            }

            try
            {
                _rockContext.SaveChanges();
            }
            catch (Exception ex)
            {
                errorMessages.Add(string.Format("Could not save value ('{0}')! {1}", propertyValue, ex.Message));
                return(false);
            }

            action.AddLogEntry(string.Format("Set '{0}' property to '{1}'.", propertyName, propertyValue));

            return(true);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        protected void BindGrid()
        {
            AddScheduleColumns();

            var rockContext = new RockContext();

            var groupLocationService = new GroupLocationService(rockContext);
            var groupTypeService     = new GroupTypeService(rockContext);
            var groupService         = new GroupService(rockContext);

            var groupPaths       = new List <GroupTypePath>();
            var groupLocationQry = groupLocationService.Queryable().Where(gl => gl.Group.IsActive && !gl.Group.IsArchived);
            int groupTypeId;

            // if this page has a PageParam for groupTypeId use that to limit which groupTypeId to see. Otherwise, use the groupTypeId specified in the filter
            if (_groupTypeId.HasValue)
            {
                groupTypeId = _groupTypeId.Value;
            }
            else
            {
                groupTypeId = ddlGroupType.SelectedValueAsInt() ?? Rock.Constants.All.Id;
            }

            if (groupTypeId != Rock.Constants.All.Id)
            {
                var descendantGroupTypeIds = groupTypeService.GetAllAssociatedDescendents(groupTypeId).Select(a => a.Id);

                // filter to groups that either are of the GroupType or are of a GroupType that has the selected GroupType as a parent (ancestor)
                groupLocationQry = groupLocationQry.Where(a => a.Group.GroupType.Id == groupTypeId || descendantGroupTypeIds.Contains(a.Group.GroupTypeId));

                groupPaths = groupTypeService.GetAllAssociatedDescendentsPath(groupTypeId).ToList();
            }
            else
            {
                List <int> descendantGroupTypeIds = new List <int>();
                foreach (GroupType groupType in GetTopGroupTypes(rockContext))
                {
                    descendantGroupTypeIds.Add(groupType.Id);

                    groupPaths.AddRange(groupTypeService.GetAllAssociatedDescendentsPath(groupType.Id).ToList());
                    foreach (var childGroupType in groupTypeService.GetChildGroupTypes(groupType.Id))
                    {
                        descendantGroupTypeIds.Add(childGroupType.Id);
                        descendantGroupTypeIds.AddRange(groupTypeService.GetAllAssociatedDescendents(childGroupType.Id).Select(a => a.Id).ToList());
                    }
                }

                groupLocationQry = groupLocationQry.Where(a => descendantGroupTypeIds.Contains(a.Group.GroupTypeId));
            }

            if (gGroupLocationSchedule.SortProperty != null)
            {
                groupLocationQry = groupLocationQry.Sort(gGroupLocationSchedule.SortProperty);
            }
            else
            {
                groupLocationQry = groupLocationQry.OrderBy(a => a.Group.Name).ThenBy(a => a.Location.Name);
            }

            var qryList = groupLocationQry
                          .Where(a => a.Location != null)
                          .Select(a =>
                                  new
            {
                GroupLocationId = a.Id,
                a.Location,
                GroupId        = a.GroupId,
                GroupName      = a.Group.Name,
                ScheduleIdList = a.Schedules.Select(s => s.Id),
                GroupTypeId    = a.Group.GroupTypeId
            }).ToList();

            var locationService  = new LocationService(rockContext);
            int parentLocationId = pkrParentLocation.SelectedValueAsInt() ?? Rock.Constants.All.Id;

            if (parentLocationId != Rock.Constants.All.Id)
            {
                var currentAndDescendantLocationIds = new List <int>();
                currentAndDescendantLocationIds.Add(parentLocationId);
                currentAndDescendantLocationIds.AddRange(locationService.GetAllDescendents(parentLocationId).Select(a => a.Id));

                qryList = qryList.Where(a => currentAndDescendantLocationIds.Contains(a.Location.Id)).ToList();
            }

            // put stuff in a DataTable so we can dynamically have columns for each Schedule
            DataTable dataTable = new DataTable();

            dataTable.Columns.Add("GroupLocationId");
            dataTable.Columns.Add("GroupId");
            dataTable.Columns.Add("GroupName");
            dataTable.Columns.Add("GroupPath");
            dataTable.Columns.Add("LocationName");
            dataTable.Columns.Add("LocationPath");
            foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>())
            {
                dataTable.Columns.Add(field.DataField, typeof(bool));
            }

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

            foreach (var row in qryList)
            {
                DataRow dataRow = dataTable.NewRow();
                dataRow["GroupLocationId"] = row.GroupLocationId;
                dataRow["GroupName"]       = groupService.GroupAncestorPathName(row.GroupId);
                dataRow["GroupPath"]       = groupPaths.Where(gt => gt.GroupTypeId == row.GroupTypeId).Select(gt => gt.Path).FirstOrDefault();
                dataRow["LocationName"]    = row.Location.Name;

                if (row.Location.ParentLocationId.HasValue)
                {
                    int locationId = row.Location.ParentLocationId.Value;

                    if (!locationPaths.ContainsKey(locationId))
                    {
                        var locationNames  = new List <string>();
                        var parentLocation = locationService.Get(locationId);
                        while (parentLocation != null)
                        {
                            locationNames.Add(parentLocation.Name);
                            parentLocation = parentLocation.ParentLocation;
                        }
                        if (locationNames.Any())
                        {
                            locationNames.Reverse();
                            locationPaths.Add(locationId, locationNames.AsDelimited(" > "));
                        }
                        else
                        {
                            locationPaths.Add(locationId, string.Empty);
                        }
                    }

                    dataRow["LocationPath"] = locationPaths[locationId];
                }

                foreach (var field in gGroupLocationSchedule.Columns.OfType <CheckBoxEditableField>())
                {
                    int scheduleId = int.Parse(field.DataField.Replace("scheduleField_", string.Empty));
                    dataRow[field.DataField] = row.ScheduleIdList.Any(a => a == scheduleId);
                }

                dataTable.Rows.Add(dataRow);
            }

            gGroupLocationSchedule.EntityTypeId = EntityTypeCache.Get <GroupLocation>().Id;
            gGroupLocationSchedule.DataSource   = dataTable;
            gGroupLocationSchedule.DataBind();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Determines whether [has event happened] [the specified entity].
        /// </summary>
        /// <param name="followingEvent">The following event.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="lastNotified">The last notified.</param>
        /// <returns></returns>
        public override bool HasEventHappened(FollowingEventType followingEvent, IEntity entity, DateTime?lastNotified)
        {
            if (followingEvent != null && entity != null)
            {
                var personAlias = entity as PersonAlias;

                if (personAlias != null && personAlias.Person != null)
                {
                    //
                    // Get all the attributes/settings we need.
                    //
                    int    daysBack         = GetAttributeValue(followingEvent, "MaxDaysBack").AsInteger();
                    string targetOldValue   = GetAttributeValue(followingEvent, "OldValue") ?? string.Empty;
                    string targetNewValue   = GetAttributeValue(followingEvent, "NewValue") ?? string.Empty;
                    string targetPersonGuid = GetAttributeValue(followingEvent, "Person");
                    bool   negateChangedBy  = GetAttributeValue(followingEvent, "NegatePerson").AsBoolean();
                    bool   matchBothValues  = GetAttributeValue(followingEvent, "MatchBoth").AsBoolean();
                    var    attributes       = GetAttributeValue(followingEvent, "Fields").Split(',').Select(a => a.Trim());

                    //
                    // Populate all the other random variables we need for processing.
                    //
                    PersonAlias targetPersonAlias  = new PersonAliasService(new RockContext()).Get(targetPersonGuid.AsGuid());
                    DateTime    daysBackDate       = RockDateTime.Now.AddDays(-daysBack);
                    var         person             = personAlias.Person;
                    int         personEntityTypeId = EntityTypeCache.Get(typeof(Person)).Id;
                    int         categoryId         = CategoryCache.Get(Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid()).Id;

                    //
                    // Start building the basic query. We want all History items that are for
                    // people objects and use the Demographic Changes category.
                    //
                    var qry = new HistoryService(new RockContext()).Queryable()
                              .Where(h => h.EntityTypeId == personEntityTypeId && h.EntityId == person.Id && h.CategoryId == categoryId);

                    //
                    // Put in our limiting dates. We always limit by our days back date,
                    // and conditionally limit based on the last time we notified the
                    // stalker - I mean the follower.
                    //
                    if (lastNotified.HasValue)
                    {
                        qry = qry.Where(h => h.CreatedDateTime >= lastNotified.Value);
                    }
                    qry = qry.Where(h => h.CreatedDateTime >= daysBackDate);

                    //
                    // Walk each history item found that matches our filter.
                    //
                    Dictionary <string, List <PersonHistoryChange> > changes = new Dictionary <string, List <PersonHistoryChange> >();
                    foreach (var history in qry.ToList())
                    {
                        //
                        // Check what kind of change this was.
                        //
                        History.HistoryVerb?historyVerb = history.Verb.ConvertToEnumOrNull <History.HistoryVerb>();
                        string title = history.ValueName;

                        //
                        // Walk each attribute entered by the user to match against.
                        //
                        foreach (var attribute in attributes)
                        {
                            PersonHistoryChange change = new PersonHistoryChange();

                            change.Old = history.OldValue;
                            change.New = history.NewValue;

                            //
                            // Check if this is one of the attributes we are following.
                            //
                            if (title != null && title.Trim() == attribute)
                            {
                                //
                                // Get the ValuePair object to work with.
                                //
                                if (!changes.ContainsKey(attribute))
                                {
                                    changes.Add(attribute, new List <PersonHistoryChange>());
                                }

                                change.PersonId = history.CreatedByPersonId;
                                changes[attribute].Add(change);

                                //
                                // If the value has been changed back to what it was then ignore the change.
                                //
                                if (changes[attribute].Count >= 2)
                                {
                                    var changesList = changes[attribute].ToList();

                                    if (changesList[changesList.Count - 2].Old == changesList[changesList.Count - 1].New)
                                    {
                                        changes.Remove(title);
                                    }
                                }
                            }
                        }
                    }

                    //
                    // Walk the list of final changes and see if we need to notify.
                    //
                    foreach (var items in changes.Values)
                    {
                        foreach (PersonHistoryChange change in items)
                        {
                            //
                            // Check for a match on the person who made the change.
                            //
                            if (targetPersonAlias == null ||
                                targetPersonAlias.Id == 0 ||
                                (!negateChangedBy && targetPersonAlias.PersonId == change.PersonId) ||
                                (negateChangedBy && targetPersonAlias.PersonId != change.PersonId))
                            {
                                bool oldMatch = (string.IsNullOrEmpty(targetOldValue) || targetOldValue == change.Old);
                                bool newMatch = (string.IsNullOrEmpty(targetNewValue) || targetNewValue == change.New);

                                //
                                // If the old value and the new value match then trigger the event.
                                //
                                if ((matchBothValues && oldMatch && newMatch) ||
                                    (!matchBothValues && (oldMatch || newMatch)))
                                {
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }

            return(false);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            btnExportToShelbyFinancials.Text = GetAttributeValue("ButtonText");
            var monthsBack     = GetAttributeValue("MonthsBack").AsInteger() * -1;
            var firstBatchDate = RockDateTime.Now.AddMonths(monthsBack);

            var batchIdList         = new List <int>();
            var filteredBatchIdList = new List <int>();
            var batchesToExport     = new List <BatchData>();

            using (var rockContextBatches = new RockContext())
            {
                var batchService = new FinancialBatchService(rockContextBatches);
                var qry          = batchService
                                   .Queryable().AsNoTracking()
                                   .Where(b => b.BatchStartDateTime.HasValue)
                                   .Where(b => b.BatchStartDateTime >= firstBatchDate)
                                   .Where(b => b.ControlAmount == b.Transactions.Sum(t => t.TransactionDetails.Sum(d => d.Amount)));

                string dateRangeValue = gfBatchesToExportFilter.GetUserPreference("Date Range");
                if (!string.IsNullOrWhiteSpace(dateRangeValue))
                {
                    var drp = new DateRangePicker();
                    drp.DelimitedValues = dateRangeValue;
                    if (drp.LowerValue.HasValue)
                    {
                        qry = qry.Where(b => b.BatchStartDateTime >= drp.LowerValue.Value);
                    }

                    if (drp.UpperValue.HasValue)
                    {
                        var endOfDay = drp.UpperValue.Value.AddDays(1);
                        qry = qry.Where(b => b.BatchStartDateTime < endOfDay);
                    }
                }

                var status = gfBatchesToExportFilter.GetUserPreference("Status").ConvertToEnumOrNull <BatchStatus>();
                if (status.HasValue)
                {
                    qry = qry.Where(b => b.Status == status);
                }

                SortProperty sortProperty = gBatchesToExport.SortProperty;
                if (sortProperty != null)
                {
                    qry = qry.Sort(sortProperty);
                }
                else
                {
                    qry = qry
                          .OrderByDescending(b => b.BatchStartDateTime)
                          .ThenBy(b => b.Name);
                }

                batchIdList = qry.Select(b => b.Id).ToList();
            }

            using (var rockContextAttributeValues = new RockContext())
            {
                var dateExportedAttributeId = AttributeCache.Get("4B6576DD-82F6-419F-8DF0-467D2636822D".AsGuid()).Id;    //rocks.kfs.ShelbyFinancials.DateExported

                foreach (var batchId in batchIdList)
                {
                    var attributeValue = new AttributeValueService(rockContextAttributeValues).GetByAttributeIdAndEntityId(dateExportedAttributeId, batchId);
                    if (attributeValue == null || attributeValue.ValueAsDateTime == null)
                    {
                        filteredBatchIdList.Add(batchId);
                    }
                }
            }

            using (var rockContextBatchData = new RockContext())
            {
                foreach (var batchId in filteredBatchIdList)
                {
                    var batch = new FinancialBatchService(rockContextBatchData).Get(batchId);

                    batchesToExport.Add(new BatchData
                    {
                        Id = batch.Id,
                        BatchStartDateTime = batch.BatchStartDateTime,
                        Name         = batch.Name,
                        Status       = batch.Status.ToString(),
                        Note         = batch.Note,
                        Transactions = batch.Transactions.Count,
                        Total        = batch.GetTotalTransactionAmount(rockContextBatchData)
                    });
                }
            }

            gBatchesToExport.DataSource   = batchesToExport;
            gBatchesToExport.ObjectList   = ((List <BatchData>)gBatchesToExport.DataSource).ToDictionary(b => b.Id.ToString(), v => v as object);
            gBatchesToExport.EntityTypeId = EntityTypeCache.Get <FinancialBatch>().Id;

            gBatchesToExport.DataBind();
        }
Exemplo n.º 24
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>
        /// <exception cref="System.NotImplementedException"></exception>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            var rockContext             = new RockContext();
            var financialPledgeService  = new FinancialPledgeService(rockContext);
            var financialAccountService = new FinancialAccountService(rockContext);
            var definedValueService     = new DefinedValueService(rockContext);
            var person = FindPerson(rockContext);

            FinancialPledge financialPledge = new FinancialPledge();

            financialPledge.PersonAliasId = person.PrimaryAliasId;
            financialPledge.GroupId       = ddlGroup.SelectedValueAsInt();

            var financialAccount = financialAccountService.Get(GetAttributeValue("Account").AsGuid());

            if (financialAccount != null)
            {
                if (GetAttributeValue("UseCampusContext").AsBoolean())
                {
                    var campusEntity           = RockPage.GetCurrentContext(EntityTypeCache.Get(typeof(Campus)));
                    int?CurrentCampusContextId = null;

                    if (campusEntity != null)
                    {
                        CurrentCampusContextId = campusEntity.Id;
                    }

                    if (CurrentCampusContextId != null && CurrentCampusContextId > -1)
                    {
                        var CampusAccount = financialAccount.ChildAccounts.OrderBy(c => c.Order).FirstOrDefault(c => c.CampusId == CurrentCampusContextId);
                        if (CampusAccount != null)
                        {
                            financialAccount = CampusAccount;
                        }
                    }
                }

                financialPledge.AccountId = financialAccount.Id;
            }

            financialPledge.TotalAmount = tbTotalAmount.Text.AsDecimal();

            var pledgeFrequencySelection = DefinedValueCache.Get(ddlFrequency.SelectedValue.AsInteger());

            if (pledgeFrequencySelection != null)
            {
                financialPledge.PledgeFrequencyValueId = pledgeFrequencySelection.Id;
            }

            financialPledge.StartDate = drpDateRange.LowerValue ?? DateTime.MinValue;
            financialPledge.EndDate   = drpDateRange.UpperValue ?? DateTime.MaxValue;

            if (sender != btnConfirm)
            {
                var duplicatePledges = financialPledgeService.Queryable()
                                       .Where(a => a.PersonAlias.PersonId == person.Id)
                                       .Where(a => a.AccountId == financialPledge.AccountId)
                                       .Where(a => a.StartDate == financialPledge.StartDate)
                                       .Where(a => a.EndDate == financialPledge.EndDate).ToList();

                if (duplicatePledges.Any())
                {
                    pnlAddPledge.Visible           = false;
                    pnlConfirm.Visible             = true;
                    nbDuplicatePledgeWarning.Text  = "The following pledges have already been entered for you:";
                    nbDuplicatePledgeWarning.Text += "<ul>";
                    foreach (var pledge in duplicatePledges.OrderBy(a => a.StartDate).ThenBy(a => a.Account.Name))
                    {
                        nbDuplicatePledgeWarning.Text += string.Format("<li>{0} {1} {2}</li>", pledge.Account, pledge.PledgeFrequencyValue, pledge.TotalAmount);
                    }

                    nbDuplicatePledgeWarning.Text += "</ul>";

                    return;
                }
            }

            if (financialPledge.IsValid)
            {
                financialPledgeService.Add(financialPledge);

                rockContext.SaveChanges();

                // populate account so that Liquid can access it
                financialPledge.Account = financialAccount;

                // populate PledgeFrequencyValue so that Liquid can access it
                financialPledge.PledgeFrequencyValue = definedValueService.Get(financialPledge.PledgeFrequencyValueId ?? 0);

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                mergeFields.Add("Person", person);
                mergeFields.Add("FinancialPledge", financialPledge);
                mergeFields.Add("PledgeFrequency", pledgeFrequencySelection);
                mergeFields.Add("Account", financialAccount);
                lReceipt.Text = GetAttributeValue("ReceiptText").ResolveMergeFields(mergeFields);

                // Resolve any dynamic url references
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                lReceipt.Text = lReceipt.Text.Replace("~~/", themeRoot).Replace("~/", appRoot);

                lReceipt.Visible     = true;
                pnlAddPledge.Visible = false;
                pnlConfirm.Visible   = false;

                // if a ConfirmationEmailTemplate is configured, send an email
                var confirmationEmailTemplateGuid = GetAttributeValue("ConfirmationEmailTemplate").AsGuidOrNull();
                if (confirmationEmailTemplateGuid.HasValue)
                {
                    var emailMessage = new RockEmailMessage(confirmationEmailTemplateGuid.Value);
                    emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields));
                    emailMessage.AppRoot   = ResolveRockUrl("~/");
                    emailMessage.ThemeRoot = ResolveRockUrl("~~/");
                    emailMessage.Send();
                }
            }
            else
            {
                ShowInvalidResults(financialPledge.ValidationResults);
            }
        }
Exemplo n.º 25
0
        public IQueryable <TreeViewItem> GetChildren(string id, string additionalFields)
        {
            var person = GetPerson();

            List <TreeViewItem> items = new List <TreeViewItem>();

            switch (id)
            {
            case "0":
            {
                if (!string.IsNullOrWhiteSpace(additionalFields))
                {
                    foreach (string fieldInfo in additionalFields.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        string[] parts = fieldInfo.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        string fieldId = parts.Length > 0 ? parts[0] : string.Empty;

                        if (fieldId == "AdditionalMergeFields")
                        {
                            if (parts.Length > 1)
                            {
                                var fieldsTv = new TreeViewItem
                                {
                                    Id          = $"AdditionalMergeFields_{parts[1]}",
                                    Name        = "Additional Fields",
                                    HasChildren = true,
                                    Children    = new List <TreeViewItem>()
                                };

                                foreach (string fieldName in parts[1].Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    fieldsTv.Children.Add(new TreeViewItem
                                        {
                                            Id          = $"AdditionalMergeField_{fieldName}",
                                            Name        = fieldName.SplitCase(),
                                            HasChildren = false
                                        });
                                }
                                items.Add(fieldsTv);
                            }
                        }
                        else
                        {
                            string[] idParts = fieldId.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries);

                            string fieldType = idParts.Length > 1 ? idParts[1] : fieldId;

                            var entityType = EntityTypeCache.Get(fieldType, false);
                            if (entityType != null)
                            {
                                items.Add(new TreeViewItem
                                    {
                                        Id          = fieldId,
                                        Name        = parts.Length > 1 ? parts[1] : entityType.FriendlyName,
                                        HasChildren = true
                                    });
                            }
                            else
                            {
                                items.Add(new TreeViewItem
                                    {
                                        Id          = fieldId,
                                        Name        = parts.Length > 1 ? parts[1] : fieldType.SplitCase(),
                                        HasChildren = fieldType == "GlobalAttribute"
                                    });
                            }
                        }
                    }
                }

                break;
            }

            case "GlobalAttribute":
            {
                var globalAttributes = GlobalAttributesCache.Get();

                foreach (var attributeCache in globalAttributes.Attributes.OrderBy(a => a.Key))
                {
                    if (attributeCache.IsAuthorized(Authorization.VIEW, person))
                    {
                        items.Add(new TreeViewItem
                            {
                                Id          = "GlobalAttribute|" + attributeCache.Key,
                                Name        = attributeCache.Name,
                                HasChildren = false
                            });
                    }
                }

                break;
            }

            default:
            {
                // In this scenario, the id should be a concatenation of a root qualified entity name and then the property path
                var idParts = id.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                if (idParts.Count > 0)
                {
                    // Get the root type
                    int             pathPointer = 0;
                    EntityTypeCache entityType  = null;
                    while (entityType == null && pathPointer < idParts.Count())
                    {
                        string   item      = idParts[pathPointer];
                        string[] itemParts = item.Split(new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries);
                        string   itemType  = itemParts.Length > 1 ? itemParts[1] : item;

                        entityType = EntityTypeCache.Get(itemType, false);
                        pathPointer++;
                    }

                    if (entityType != null)
                    {
                        Type type = entityType.GetEntityType();

                        // Traverse the Property path
                        while (idParts.Count > pathPointer)
                        {
                            var childProperty = type.GetProperty(idParts[pathPointer]);
                            if (childProperty != null)
                            {
                                type = childProperty.PropertyType;

                                if (type.IsGenericType &&
                                    type.GetGenericTypeDefinition() == typeof(ICollection <>) &&
                                    type.GetGenericArguments().Length == 1)
                                {
                                    type = type.GetGenericArguments()[0];
                                }
                            }

                            pathPointer++;
                        }

                        entityType = EntityTypeCache.Get(type);

                        // Add the tree view items
                        foreach (var propInfo in type.GetProperties())
                        {
                            if (propInfo.GetCustomAttributes(typeof(System.Runtime.Serialization.DataMemberAttribute)).Count() > 0)
                            {
                                var treeViewItem = new TreeViewItem
                                {
                                    Id   = id + "|" + propInfo.Name,
                                    Name = propInfo.Name.SplitCase()
                                };

                                Type propertyType = propInfo.PropertyType;

                                if (propertyType.IsGenericType &&
                                    propertyType.GetGenericTypeDefinition() == typeof(ICollection <>) &&
                                    propertyType.GetGenericArguments().Length == 1)
                                {
                                    treeViewItem.Name += " (Collection)";
                                    propertyType       = propertyType.GetGenericArguments()[0];
                                }

                                bool hasChildren = false;
                                if (EntityTypeCache.Get(propertyType.FullName, false) != null)
                                {
                                    foreach (var childPropInfo in propertyType.GetProperties())
                                    {
                                        if (childPropInfo.GetCustomAttributes(typeof(System.Runtime.Serialization.DataMemberAttribute)).Count() > 0)
                                        {
                                            hasChildren = true;
                                            break;
                                        }
                                    }
                                }

                                treeViewItem.HasChildren = hasChildren;

                                items.Add(treeViewItem);
                            }
                        }

                        if (type == typeof(Rock.Model.Person))
                        {
                            items.Add(new TreeViewItem
                                {
                                    Id   = id + "|" + "Campus",
                                    Name = "Campus"
                                });
                        }

                        if (entityType.IsEntity)
                        {
                            foreach (Rock.Model.Attribute attribute in new AttributeService(new Rock.Data.RockContext()).GetByEntityTypeId(entityType.Id, false))
                            {
                                // Only include attributes without a qualifier (since we don't have a specific instance of this entity type)
                                if (string.IsNullOrEmpty(attribute.EntityTypeQualifierColumn) &&
                                    string.IsNullOrEmpty(attribute.EntityTypeQualifierValue) &&
                                    attribute.IsAuthorized(Authorization.VIEW, person))
                                {
                                    items.Add(new TreeViewItem
                                        {
                                            Id   = id + "|" + attribute.Key,
                                            Name = attribute.Name
                                        });
                                }
                            }
                        }
                    }
                }

                break;
            }
            }

            return(items.OrderBy(i => i.Name).AsQueryable());
        }
Exemplo n.º 26
0
        /// <summary>
        /// Gets the entity fields for a specific Entity
        /// </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>();
            }

            List <PropertyInfo> entityProperties = entityType.GetProperties().ToList();

            // filter the properties to narrow down the ones that we want to include in EntityFields
            var filteredEntityProperties = entityProperties
                                           .Where((p) =>
            {
                var includeForReportingAttribute = p.GetCustomAttribute <IncludeForReportingAttribute>() != null;

                // if the property has an IncludeForReportingAttribute, include it regardless
                if (includeForReportingAttribute)
                {
                    return(true);
                }

                bool hideFromReporting = false;
                if (includeOnlyReportingFields)
                {
                    hideFromReporting = p.GetCustomAttribute <HideFromReportingAttribute>() != null;
                }

                // if the property should be hidden from reporting, don't show it
                if (hideFromReporting)
                {
                    return(false);
                }

                bool isMappedDatabaseField = Reflection.IsMappedDatabaseProperty(p);
                if (!isMappedDatabaseField)
                {
                    return(false);
                }

                return(true);
            }).ToList();

            // Go thru filteredEntityProperties and create the list of EntityFields that we can include
            foreach (var property in filteredEntityProperties)
            {
                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))
                {
                    // intentionally blank, entity field is already setup
                }

                // Enum Properties
                else if (property.PropertyType.IsEnum)
                {
                    entityField.FieldType = FieldTypeCache.Get(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.Get(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.Get(SystemGuid.FieldType.DATE.AsGuid());
                    }
                    else
                    {
                        entityField.FieldType = FieldTypeCache.Get(SystemGuid.FieldType.DATE_TIME.AsGuid());
                    }
                }

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

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

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

                    var definedValueAttribute = property.GetCustomAttribute <Rock.Data.DefinedValueAttribute>();
                    if (definedValueAttribute != null)
                    {
                        // Defined Value Properties
                        Guid?definedTypeGuid = definedValueAttribute.DefinedTypeGuid;
                        if (definedTypeGuid.HasValue)
                        {
                            var definedType = DefinedTypeCache.Get(definedTypeGuid.Value);
                            entityField.Title = definedType != null ? definedType.Name : property.Name.Replace("ValueId", string.Empty).SplitCase();
                            if (definedType != null)
                            {
                                entityField.FieldType = FieldTypeCache.Get(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.Get(entityType, true);

            if (entityTypeCache != null)
            {
                int entityTypeId = entityTypeCache.Id;

                IEnumerable <AttributeCache> cacheAttributeList = AttributeCache.GetByEntityType(entityTypeCache.Id);

                if (entityType == typeof(Group) || entityType == typeof(GroupMember))
                {
                    // in the case of Group or GroupMember, show attributes that are entity global, but also ones that are qualified by GroupTypeId
                    cacheAttributeList = cacheAttributeList
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn == null ||
                                                a.EntityTypeQualifierColumn == string.Empty ||
                                                a.EntityTypeQualifierColumn == "GroupTypeId");
                }
                else if (entityType == typeof(ConnectionRequest))
                {
                    // in the case of Connection Requests, show attributes that are entity global, but also ones that are qualified by ConnectionOpportunityId
                    cacheAttributeList = cacheAttributeList
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn == null ||
                                                a.EntityTypeQualifierColumn == string.Empty ||
                                                a.EntityTypeQualifierColumn == "ConnectionOpportunityId"
                                                );
                }
                else if (entityType == typeof(Registration))
                {
                    // in the case of Registrations, show attributes that are entity global, but also ones that are qualified by RegistrationTemplateId
                    cacheAttributeList = cacheAttributeList
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn == null ||
                                                a.EntityTypeQualifierColumn == string.Empty ||
                                                a.EntityTypeQualifierColumn == "RegistrationTemplateId"
                                                );
                }
                else if (entityType == typeof(ContentChannelItem))
                {
                    // in the case of ContentChannelItem, show attributes that are entity global, but also ones that are qualified by ContentChannelTypeId or ContentChannelId
                    cacheAttributeList = cacheAttributeList
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn == null ||
                                                a.EntityTypeQualifierColumn == string.Empty ||
                                                a.EntityTypeQualifierColumn == "ContentChannelTypeId" ||
                                                a.EntityTypeQualifierColumn == "ContentChannelId"
                                                );
                }
                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 = WorkflowTypeCache.All().Select(a => a.Id.ToString()).ToArray();
                    cacheAttributeList = cacheAttributeList
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn == null ||
                                                a.EntityTypeQualifierColumn == string.Empty ||
                                                (a.EntityTypeQualifierColumn == "WorkflowTypeId" && validWorkflowTypeIds.Contains(a.EntityTypeQualifierValue))).ToList();
                }
                else if (entityType == typeof(Note))
                {
                    // in the case of notes, show attributes that are entity global, but also ones that are qualified by ConnectionOpportunityId
                    cacheAttributeList = cacheAttributeList
                                         .Where(a =>
                                                a.EntityTypeQualifierColumn == null ||
                                                a.EntityTypeQualifierColumn == string.Empty ||
                                                a.EntityTypeQualifierColumn == "NoteTypeId"
                                                );
                }
                else
                {
                    cacheAttributeList = cacheAttributeList.Where(a => string.IsNullOrEmpty(a.EntityTypeQualifierColumn) && string.IsNullOrEmpty(a.EntityTypeQualifierValue)).ToList();
                }

                EntityHelper.AddEntityFieldsForAttributeList(entityFields, cacheAttributeList.ToList());
            }

            // 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);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Shows the edit details.
        /// </summary>
        /// <param name="site">The site.</param>
        private void ShowEditDetails(Rock.Model.Site site)
        {
            if (site.Id == 0)
            {
                nbDefaultPageNotice.Visible = true;
                lReadOnlyTitle.Text         = ActionTitle.Add(Rock.Model.Site.FriendlyTypeName).FormatAsHtmlTitle();
            }
            else
            {
                nbDefaultPageNotice.Visible = false;
                lReadOnlyTitle.Text         = site.Name.FormatAsHtmlTitle();
            }

            SetEditMode(true);

            LoadDropDowns();

            tbSiteName.ReadOnly = site.IsSystem;
            tbSiteName.Text     = site.Name;

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

            ddlTheme.Enabled = !site.IsSystem;
            ddlTheme.SetValue(site.Theme);

            imgSiteIcon.BinaryFileId = site.FavIconBinaryFileId;
            imgSiteLogo.BinaryFileId = site.SiteLogoBinaryFileId;

            cbIsActive.Checked = site.IsActive;

            if (site.DefaultPageRoute != null)
            {
                ppDefaultPage.SetValue(site.DefaultPageRoute);
            }
            else
            {
                ppDefaultPage.SetValue(site.DefaultPage);
            }

            if (site.LoginPageRoute != null)
            {
                ppLoginPage.SetValue(site.LoginPageRoute);
            }
            else
            {
                ppLoginPage.SetValue(site.LoginPage);
            }

            if (site.ChangePasswordPageRoute != null)
            {
                ppChangePasswordPage.SetValue(site.ChangePasswordPageRoute);
            }
            else
            {
                ppChangePasswordPage.SetValue(site.ChangePasswordPage);
            }

            if (site.CommunicationPageRoute != null)
            {
                ppCommunicationPage.SetValue(site.CommunicationPageRoute);
            }
            else
            {
                ppCommunicationPage.SetValue(site.CommunicationPage);
            }

            if (site.RegistrationPageRoute != null)
            {
                ppRegistrationPage.SetValue(site.RegistrationPageRoute);
            }
            else
            {
                ppRegistrationPage.SetValue(site.RegistrationPage);
            }

            if (site.PageNotFoundPageRoute != null)
            {
                ppPageNotFoundPage.SetValue(site.PageNotFoundPageRoute);
            }
            else
            {
                ppPageNotFoundPage.SetValue(site.PageNotFoundPage);
            }

            tbErrorPage.Text = site.ErrorPage;

            tbSiteDomains.Text            = string.Join("\n", site.SiteDomains.OrderBy(d => d.Order).Select(d => d.Domain).ToArray());
            tbGoogleAnalytics.Text        = site.GoogleAnalyticsCode;
            cbRequireEncryption.Checked   = site.RequiresEncryption;
            cbEnableForShortening.Checked = site.EnabledForShortening;

            cbEnableMobileRedirect.Checked = site.EnableMobileRedirect;
            ppMobilePage.SetValue(site.MobilePage);
            tbExternalURL.Text         = site.ExternalUrl;
            tbAllowedFrameDomains.Text = site.AllowedFrameDomains;
            cbRedirectTablets.Checked  = site.RedirectTablets;
            cbEnablePageViews.Checked  = site.EnablePageViews;

            int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
            var interactionChannelForSite   = new InteractionChannelService(new RockContext()).Queryable()
                                              .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

            if (interactionChannelForSite != null)
            {
                nbPageViewRetentionPeriodDays.Text = interactionChannelForSite.RetentionDuration.ToString();
            }

            cbEnableIndexing.Checked        = site.IsIndexEnabled;
            tbIndexStartingLocation.Text    = site.IndexStartingLocation;
            cbEnableExclusiveRoutes.Checked = site.EnableExclusiveRoutes;

            // disable the indexing features if indexing on site is disabled
            var siteEntityType = EntityTypeCache.Get("Rock.Model.Site");

            if (siteEntityType != null && !siteEntityType.IsIndexingEnabled)
            {
                cbEnableIndexing.Visible = false;
            }

            var attributeService     = new AttributeService(new RockContext());
            var siteIdQualifierValue = site.Id.ToString();

            PageAttributesState = attributeService.GetByEntityTypeId(new Page().TypeId, true).AsQueryable()
                                  .Where(a =>
                                         a.EntityTypeQualifierColumn.Equals("SiteId", StringComparison.OrdinalIgnoreCase) &&
                                         a.EntityTypeQualifierValue.Equals(siteIdQualifierValue))
                                  .OrderBy(a => a.Order)
                                  .ThenBy(a => a.Name)
                                  .ToList();
            BindPageAttributesGrid();

            SetControlsVisiblity();

            site.LoadAttributes();
            avcAttributes.AddEditControls(site, Rock.Security.Authorization.EDIT, CurrentPerson);
        }
Exemplo n.º 28
0
        private void ShowWidgityTypes()
        {
            var widgityTypes = WidgityTypeCache.All()
                               .Where(wt => wt.EntityTypes.Select(e => e.Id).Contains(EntityTypeId)).ToList();

            if (!widgityTypes.Any())
            {
                NotificationBox notification = new NotificationBox
                {
                    NotificationBoxType = NotificationBoxType.Warning,
                    Text = "There are no widgity types for this entity type: " + EntityTypeCache.Get(EntityTypeId)?.FriendlyName
                };
                pnlMenu.Controls.Add(notification);
                return;
            }

            var categories = widgityTypes
                             .Where(wt => wt.Category != null)
                             .Select(wt => wt.Category)
                             .DistinctBy(c => c.Id)
                             .ToList();

            foreach (var category in categories)
            {
                PanelWidget panelWidget = new PanelWidget
                {
                    ID    = this.ID + "_pwCategory_" + category.Id.ToString(),
                    Title = category.Name
                };
                pnlMenu.Controls.Add(panelWidget);

                var dragContainer = new Panel
                {
                    ID       = this.ID + "_pnlWidgityContainer_" + category.Id.ToString(),
                    CssClass = "widgitySource"
                };
                panelWidget.Controls.Add(dragContainer);

                var categoryTypes = widgityTypes.Where(wt => wt.CategoryId == category.Id).ToList();

                foreach (var widgityType in categoryTypes)
                {
                    HtmlGenericContainer item = new HtmlGenericContainer("div");
                    item.InnerHtml = string.Format("<i class='{0}'></i><br />{1}",
                                                   widgityType.Icon,
                                                   widgityType.Name);
                    item.Attributes.Add("data-component-id", widgityType.Id.ToString());
                    item.CssClass = "btn btn-default btn-block";
                    dragContainer.Controls.Add(item);
                }
            }

            var noCategoryTypes = widgityTypes.Where(wt => wt.Category == null).ToList();

            if (noCategoryTypes.Any())
            {
                var dragContainerOther = new Panel
                {
                    ID       = this.ID + "_pnlWidgityContainer_other",
                    CssClass = "widgitySource"
                };

                if (categories.Any())
                {
                    PanelWidget panelWidgetOther = new PanelWidget
                    {
                        ID    = this.ID + "_pwCategory_Other",
                        Title = "Other"
                    };
                    pnlMenu.Controls.Add(panelWidgetOther);
                    panelWidgetOther.Controls.Add(dragContainerOther);
                }
                else
                {
                    pnlMenu.Controls.Add(dragContainerOther);
                }

                foreach (var widgityType in noCategoryTypes)
                {
                    HtmlGenericContainer item = new HtmlGenericContainer("div")
                    {
                        InnerHtml = string.Format("<i class='{0}'></i><br />{1}",
                                                  widgityType.Icon,
                                                  widgityType.Name)
                    };
                    item.Attributes.Add("data-component-id", widgityType.Id.ToString());
                    dragContainerOther.Controls.Add(item);
                }
            }

            if (ShowPublishButtons)
            {
                HtmlGenericContainer hr = new HtmlGenericContainer("hr");
                pnlMenu.Controls.Add(hr);

                BootstrapButton btnSave = new BootstrapButton
                {
                    CssClass        = "btn btn-primary",
                    Text            = "Publish",
                    ID              = this.ID + "_btnSave",
                    ValidationGroup = this.ID + "ValidationGroup"
                };
                pnlMenu.Controls.Add(btnSave);
                btnSave.Click += BtnSave_Click;

                LinkButton btnCancel = new LinkButton
                {
                    ID       = this.ID + "_btnCancel",
                    Text     = "Cancel",
                    CssClass = "btn btn-link"
                };
                pnlMenu.Controls.Add(btnCancel);
                btnCancel.Click += BtnCancel_Click;
            }
        }
Exemplo n.º 29
0
        /// <summary>Process all leagues (programs) from LeagueApps.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext           dbContext             = new RockContext();
            GroupService          groupService          = new GroupService(dbContext);
            AttributeService      attributeService      = new AttributeService(dbContext);
            AttributeValueService attributeValueService = new AttributeValueService(dbContext);
            GroupTypeRoleService  groupTypeRoleService  = new GroupTypeRoleService(dbContext);
            DefinedValueService   definedValueService   = new DefinedValueService(dbContext);
            DefinedTypeService    definedTypeService    = new DefinedTypeService(dbContext);
            BinaryFileService     binaryFileService     = new BinaryFileService(dbContext);

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            var warnings  = string.Empty;
            var processed = 0;

            try
            {
                var apiClient = new APIClient();

                var settings = SettingsComponent.GetComponent <LeagueAppsSettings>();

                //Group Attributes
                var parentGroup          = groupService.Get(settings.GetAttributeValue(Constants.ParentGroup).AsGuid());
                var yearGroupType        = GroupTypeCache.Get(settings.GetAttributeValue(Constants.YearGroupType).AsGuid());
                var categoryGroupType    = GroupTypeCache.Get(settings.GetAttributeValue(Constants.CategoryGroupType).AsGuid());
                var leagueGroupType      = GroupTypeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupType).AsGuid());
                var sportsType           = DefinedTypeCache.Get(Constants.SPORTS_TYPE.AsGuid());
                var seasonsType          = DefinedTypeCache.Get(Constants.SEASONS_TYPE.AsGuid());
                var gendersType          = DefinedTypeCache.Get(Constants.GENDERS_TYPE.AsGuid());
                var groupMemberAttribute = AttributeCache.Get(settings.GetAttributeValue(Constants.LeagueGroupTeam).AsGuid());

                //Person Attribute
                var personattribute  = AttributeCache.Get(Constants.ATTRIBUTE_PERSON_USER_ID.AsGuid());
                var connectionStatus = DefinedValueCache.Get(settings.GetAttributeValue(Constants.DefaultConnectionStatus).AsGuid());

                var groupEntityType = EntityTypeCache.Get(typeof(Group)).Id;

                var programs = apiClient.GetPublic <List <Programs> >("/v1/sites/{siteid}/programs/current");


                var groups = groupService.Queryable().Where(g => g.GroupTypeId == leagueGroupType.Id).ToList();

                foreach (Contracts.Programs program in programs)
                {
                    // Process the program
                    Group league    = null;
                    Group league2   = null;
                    Group league3   = null;
                    var   startdate = program.startTime;
                    var   mode      = program.mode.ToLower();
                    mode = mode.First().ToString().ToUpper() + mode.Substring(1);
                    var grandparentgroup = string.Format("{0}", startdate.Year);
                    if (program.programId > 0)
                    {
                        league = groupService.Queryable().Where(l => l.Name == grandparentgroup && l.ParentGroupId == parentGroup.Id).FirstOrDefault();
                        if (league != null)
                        {
                            league2 = groupService.Queryable().Where(l => l.Name == mode && l.ParentGroupId == league.Id).FirstOrDefault();
                            if (league2 != null)
                            {
                                league3 = groupService.Queryable().Where(l => l.ForeignId == program.programId && l.GroupTypeId == leagueGroupType.Id && l.ParentGroupId == league2.Id).FirstOrDefault();
                            }
                        }
                    }
                    Guid guid  = Guid.NewGuid();
                    Guid guid2 = Guid.NewGuid();
                    Guid guid3 = Guid.NewGuid();

                    if (league == null)
                    {
                        // Create league grandparent Group
                        Group leagueGPG = new Group();
                        leagueGPG.Name           = grandparentgroup;
                        leagueGPG.GroupTypeId    = yearGroupType.Id;
                        leagueGPG.ParentGroupId  = parentGroup.Id;
                        leagueGPG.IsSystem       = false;
                        leagueGPG.IsActive       = true;
                        leagueGPG.IsSecurityRole = false;
                        leagueGPG.Order          = 0;
                        leagueGPG.Guid           = guid;
                        groupService.Add(leagueGPG);

                        // Now save the league grandparent group
                        dbContext.SaveChanges();
                        league = leagueGPG;
                    }

                    if (league2 == null)
                    {
                        // Create league parent Group
                        Group leaguePG = new Group();
                        leaguePG.Name           = mode;
                        leaguePG.GroupTypeId    = categoryGroupType.Id;
                        leaguePG.ParentGroupId  = league.Id;
                        leaguePG.IsSystem       = false;
                        leaguePG.IsActive       = true;
                        leaguePG.IsSecurityRole = false;
                        leaguePG.Order          = 0;
                        leaguePG.Guid           = guid2;
                        groupService.Add(leaguePG);

                        // Now save the league parent group
                        dbContext.SaveChanges();
                        league2 = leaguePG;
                    }

                    if (league3 == null)
                    {
                        // Create the league
                        Group leagueG = new Group();
                        leagueG.Name           = program.name;
                        leagueG.GroupTypeId    = leagueGroupType.Id;
                        leagueG.ParentGroupId  = league2.Id;
                        leagueG.IsSystem       = false;
                        leagueG.IsActive       = true;
                        leagueG.IsSecurityRole = false;
                        leagueG.Order          = 0;
                        leagueG.Description    = HTMLConvertor.Convert(program.description);
                        leagueG.ForeignId      = program.programId;
                        groupService.Add(leagueG);

                        // Now save the league
                        dbContext.SaveChanges();
                        league3 = leagueG;
                    }
                    else
                    {
                        groups.Remove(league3);
                    }
                    league3.LoadAttributes();
                    var sport       = definedValueService.Queryable().Where(d => d.Value == program.sport && d.DefinedTypeId == sportsType.Id).FirstOrDefault();
                    var season      = definedValueService.Queryable().Where(d => d.Value == program.season && d.DefinedTypeId == seasonsType.Id).FirstOrDefault();
                    var groupgender = definedValueService.Queryable().Where(d => d.Value == program.gender && d.DefinedTypeId == gendersType.Id).FirstOrDefault();

                    if (!sport.IsNull())
                    {
                        league3.SetAttributeValue("Sport", sport.Guid);
                    }

                    if (!season.IsNull())
                    {
                        league3.SetAttributeValue("Season", season.Guid);
                    }
                    league3.SetAttributeValue("ExperienceLevel", program.experienceLevel);

                    if (!groupgender.IsNull())
                    {
                        league3.SetAttributeValue("Gender", groupgender.Guid);
                    }

                    if (startdate != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("StartTime", startdate);
                    }

                    if (program.publicRegistrationTime != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("PublicRegistrationTime", program.publicRegistrationTime);
                    }

                    if (program.ageLimitEffectiveDate != DateTime.MinValue)
                    {
                        league3.SetAttributeValue("AgeLimitDate", program.ageLimitEffectiveDate.Date.ToString("d"));
                    }
                    league3.SetAttributeValue("ProgramURL", program.programUrlHtml);
                    league3.SetAttributeValue("RegisterURL", program.registerUrlHtml);
                    league3.SetAttributeValue("ScheduleURL", program.scheduleUrlHtml);
                    league3.SetAttributeValue("StandingsURL", program.standingsUrlHtml);
                    league3.SetAttributeValue("ProgramLogo", program.programLogo150);
                    league3.SaveAttributeValues();
                    dbContext.SaveChanges();

                    var applicants = apiClient.GetPrivate <List <Registrations> >("/v2/sites/{siteid}/export/registrations-2?last-updated=0&last-id=0&program-id=" + program.programId);

                    context.UpdateLastStatusMessage("Processing league " + (processed + 1) + " of " + programs.Count + ": " + program.startTime.Year + " > " + program.mode + " > " + program.name + " (" + applicants.Count + " members).");

                    foreach (Contracts.Registrations applicant in applicants)
                    {
                        // Use a fresh RockContext on every person/groupmember to keep things moving quickly
                        using (var rockContext = new RockContext())
                        {
                            PersonService      personService      = new PersonService(rockContext);
                            GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                            LocationService    locationService    = new LocationService(rockContext);

                            Person person = null;

                            // 1. Try to load the person using the LeagueApps UserId
                            var attributevalue = applicant.userId.ToString();
                            var personIds      = attributeValueService.Queryable().Where(av => av.AttributeId == personattribute.Id &&
                                                                                         (av.Value == attributevalue ||
                                                                                          av.Value.Contains("|" + attributevalue + "|") ||
                                                                                          av.Value.StartsWith(attributevalue + "|"))).Select(av => av.EntityId);
                            if (personIds.Count() == 1)
                            {
                                person = personService.Get(personIds.FirstOrDefault().Value);
                            }

                            // 2. If we don't have a person match then
                            //    just use the standard person match/create logic
                            if (person == null)
                            {
                                var member = apiClient.GetPrivate <Member>("/v2/sites/{siteid}/members/" + applicant.userId);
                                person = LeagueAppsHelper.CreatePersonFromMember(member, connectionStatus);
                            }

                            // Check to see if the group member already exists
                            var groupmember = groupMemberService.GetByGroupIdAndPersonId(league3.Id, person.Id).FirstOrDefault();

                            if (groupmember == null)
                            {
                                Guid guid5 = Guid.NewGuid();
                                groupmember          = new GroupMember();
                                groupmember.PersonId = person.Id;
                                groupmember.GroupId  = league3.Id;
                                groupmember.IsSystem = false;
                                groupmember.Guid     = guid5;

                                if (!String.IsNullOrEmpty(applicant.role))
                                {
                                    var role = applicant.role.Split('(')[0].Trim();

                                    if (role == "FREEAGENT" || role == "PLAYER")
                                    {
                                        role = "Member";
                                    }
                                    else if (role == "CAPTAIN")
                                    {
                                        role = "Captain";
                                    }
                                    else if (role == "HEAD COACH" || role == "Head Coach")
                                    {
                                        role = "Head Coach";
                                    }
                                    else if (role == "ASST. COACH" || role == "Asst. Coach")
                                    {
                                        role = "Asst. Coach";
                                    }
                                    else
                                    {
                                        role = "Member";
                                    }
                                    var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == leagueGroupType.Id && r.Name == role).FirstOrDefault().Id;
                                    groupmember.GroupRoleId = grouprole;
                                }
                                else
                                {
                                    groupmember.GroupRoleId = leagueGroupType.DefaultGroupRoleId.Value;
                                }
                                groupmember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMemberService.Add(groupmember);
                                rockContext.SaveChanges();
                            }

                            // Make sure we update the team if necessary
                            groupmember.LoadAttributes();
                            groupmember.SetAttributeValue(groupMemberAttribute.Key, applicant.team);
                            groupmember.SaveAttributeValues(rockContext);
                        }
                    }
                    processed++;
                }

                foreach (Group sportsleague in groups)
                {
                    sportsleague.IsActive = false;
                    dbContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("LeagueApps Job Failed", ex);
            }
            finally
            {
                dbContext.SaveChanges();
            }

            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " leagues.";
        }
Exemplo n.º 30
0
        protected void AddDynamicControls(ContentChannel channel)
        {
            // Remove all columns
            gContentChannelItems.Columns.Clear();
            phAttributeFilters.Controls.Clear();

            if (channel != null)
            {
                // Add Reorder column
                var reorderField = new ReorderField();
                gContentChannelItems.Columns.Add(reorderField);

                // Add Title column
                var titleField = new BoundField();
                titleField.DataField      = "Title";
                titleField.HeaderText     = "Title";
                titleField.SortExpression = "Title";
                gContentChannelItems.Columns.Add(titleField);

                // Add Attribute columns
                int    entityTypeId  = EntityTypeCache.Get(typeof(Rock.Model.ContentChannelItem)).Id;
                string channelId     = channel.Id.ToString();
                string channelTypeId = channel.ContentChannelTypeId.ToString();
                foreach (var attribute in AvailableAttributes)
                {
                    var control = attribute.FieldType.Field.FilterControl(attribute.QualifierValues, "filter_" + attribute.Id.ToString(), false, Rock.Reporting.FilterMode.SimpleFilter);
                    if (control != null)
                    {
                        if (control is IRockControl)
                        {
                            var rockControl = (IRockControl)control;
                            rockControl.Label = attribute.Name;
                            rockControl.Help  = attribute.Description;
                            phAttributeFilters.Controls.Add(control);
                        }
                        else
                        {
                            var wrapper = new RockControlWrapper();
                            wrapper.ID    = control.ID + "_wrapper";
                            wrapper.Label = attribute.Name;
                            wrapper.Controls.Add(control);
                            phAttributeFilters.Controls.Add(wrapper);
                        }

                        string savedValue = gfFilter.GetUserPreference(MakeKeyUniqueToChannel(channel.Id, attribute.Key));
                        if (!string.IsNullOrWhiteSpace(savedValue))
                        {
                            try
                            {
                                var values = JsonConvert.DeserializeObject <List <string> >(savedValue);
                                attribute.FieldType.Field.SetFilterValues(control, attribute.QualifierValues, values);
                            }
                            catch
                            {
                                // intentionally ignore
                            }
                        }
                    }

                    string dataFieldExpression = attribute.Key;
                    bool   columnExists        = gContentChannelItems.Columns.OfType <AttributeField>().FirstOrDefault(a => a.DataField.Equals(dataFieldExpression)) != null;
                    if (!columnExists)
                    {
                        AttributeField boundField = new AttributeField();
                        boundField.DataField   = dataFieldExpression;
                        boundField.AttributeId = attribute.Id;
                        boundField.HeaderText  = attribute.Name;
                        boundField.ItemStyle.HorizontalAlign = attribute.FieldType.Field.AlignValue;
                        gContentChannelItems.Columns.Add(boundField);
                    }
                }

                if (channel.ContentChannelType.DateRangeType != ContentChannelDateType.NoDates)
                {
                    RockBoundField startDateTimeField;
                    RockBoundField expireDateTimeField;
                    if (channel.ContentChannelType.IncludeTime)
                    {
                        startDateTimeField  = new DateTimeField();
                        expireDateTimeField = new DateTimeField();
                    }
                    else
                    {
                        startDateTimeField  = new DateField();
                        expireDateTimeField = new DateField();
                    }

                    startDateTimeField.DataField      = "StartDateTime";
                    startDateTimeField.HeaderText     = channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Date";
                    startDateTimeField.SortExpression = "StartDateTime";
                    gContentChannelItems.Columns.Add(startDateTimeField);

                    expireDateTimeField.DataField      = "ExpireDateTime";
                    expireDateTimeField.HeaderText     = "Expire";
                    expireDateTimeField.SortExpression = "ExpireDateTime";
                    if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                    {
                        gContentChannelItems.Columns.Add(expireDateTimeField);
                    }
                }

                if (!channel.ContentChannelType.DisablePriority)
                {
                    // Priority column
                    var priorityField = new BoundField();
                    priorityField.DataField                 = "Priority";
                    priorityField.HeaderText                = "Priority";
                    priorityField.SortExpression            = "Priority";
                    priorityField.DataFormatString          = "{0:N0}";
                    priorityField.ItemStyle.HorizontalAlign = HorizontalAlign.Right;
                    gContentChannelItems.Columns.Add(priorityField);
                }

                // Status column
                if (channel.RequiresApproval)
                {
                    var statusField = new BoundField();
                    gContentChannelItems.Columns.Add(statusField);
                    statusField.DataField      = "Status";
                    statusField.HeaderText     = "Status";
                    statusField.SortExpression = "Status";
                    statusField.HtmlEncode     = false;
                }

                // Add occurrences Count column
                var occurrencesField = new BoolField();
                occurrencesField.DataField  = "Occurrences";
                occurrencesField.HeaderText = "Event Occurrences";
                gContentChannelItems.Columns.Add(occurrencesField);

                // Add Created By column
                var createdByPersonNameField = new BoundField();
                createdByPersonNameField.DataField  = "CreatedByPersonName";
                createdByPersonNameField.HeaderText = "Created By";
                createdByPersonNameField.HtmlEncode = false;
                gContentChannelItems.Columns.Add(createdByPersonNameField);

                // Add Tag Field
                if (channel.IsTaggingEnabled)
                {
                    var tagField = new BoundField();
                    gContentChannelItems.Columns.Add(tagField);
                    tagField.DataField          = "Tags";
                    tagField.HeaderText         = "Tags";
                    tagField.ItemStyle.CssClass = "taglist";
                    tagField.HtmlEncode         = false;
                }

                bool canEditChannel = channel.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson);
                gContentChannelItems.Actions.ShowAdd = canEditChannel;
                gContentChannelItems.IsDeleteEnabled = canEditChannel;
                if (canEditChannel)
                {
                    var deleteField = new DeleteField();
                    gContentChannelItems.Columns.Add(deleteField);
                    deleteField.Click += gContentChannelItems_Delete;
                }
            }
        }