private IQueryable <EventItemOccurrence> GetBaseEventOccurrenceQuery(RockContext rockContext)
        {
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Get active and approved Event Occurrences.
            var qryOccurrences = eventItemOccurrenceService
                                 .Queryable("EventItem, EventItem.EventItemAudiences,Schedule");

            return(qryOccurrences);
        }
示例#2
0
        private void DisplayDetails()
        {
            int eventItemOccurrenceId = 0;

            // get the calendarItem id
            if ( !string.IsNullOrWhiteSpace( PageParameter( "EventOccurrenceId" ) ) )
            {
                eventItemOccurrenceId = Convert.ToInt32( PageParameter( "EventOccurrenceId" ) );
            }
            if ( eventItemOccurrenceId > 0 )
            {                                                              
                var eventItemOccurrenceService = new EventItemOccurrenceService( new RockContext() );
                var qry = eventItemOccurrenceService
                    .Queryable( "EventItem, EventItem.Photo, Campus, Linkages" )
                    .Where( i => i.Id == eventItemOccurrenceId );

                var eventItemOccurrence = qry.FirstOrDefault();

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

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

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

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

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
            else
            {
                lOutput.Text = "<div class='alert alert-warning'>No event was available from the querystring.</div>";
            }
        }
        public IQueryable <EventItemOccurrence> GetEventItemOccurencesByCalendarId(int id)
        {
            var rockContext = new RockContext();

            rockContext.Configuration.ProxyCreationEnabled = false;
            EventItemOccurrenceService eventItemOccurenceService = new EventItemOccurrenceService(rockContext);

            IQueryable <EventItemOccurrence> itemOccurences = eventItemOccurenceService.Queryable().AsNoTracking().Join(new EventCalendarItemService(rockContext).Queryable(), occurence => occurence.EventItemId, eventCalendarItem => eventCalendarItem.EventItemId, (occurence, eventCalendarItem) => new
            {
                CalendarId         = eventCalendarItem.EventCalendarId,
                EventItemOccurence = occurence
            }).Where(ec => ec.CalendarId == id).Select(ec => ec.EventItemOccurence);

            return(itemOccurences);
        }
        private void DisplayDetails()
        {
            int         eventItemOccurrenceId = 0;
            RockContext rockContext           = new RockContext();

            // get the calendarItem id
            if (!string.IsNullOrWhiteSpace(PageParameter("EventOccurrenceId")))
            {
                eventItemOccurrenceId = Convert.ToInt32(PageParameter("EventOccurrenceId"));
            }

            if (eventItemOccurrenceId > 0)
            {
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
                var qry = eventItemOccurrenceService
                          .Queryable("EventItem, EventItem.Photo, Campus, Linkages")
                          .Where(i => i.Id == eventItemOccurrenceId);

                var eventItemOccurrence = qry.FirstOrDefault();

                if (eventItemOccurrence != null)
                {
                    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>();
                    foreach (var registrationInstance in eventItemOccurrence.Linkages.Select(a => a.RegistrationInstance).Distinct().ToList())
                    {
                        var maxRegistrantCount       = 0;
                        var currentRegistrationCount = 0;

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


                        int?registrationSpotsAvailable = null;
                        if (maxRegistrantCount != 0)
                        {
                            currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking()
                                                       .Where(r =>
                                                              r.Registration.RegistrationInstanceId == registrationInstance.Id &&
                                                              r.OnWaitList == false)
                                                       .Count();
                            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);
                    }
                }
                else
                {
                    lOutput.Text = "<div class='alert alert-warning'>We could not find that event.</div>";
                }
            }
            else
            {
                lOutput.Text = "<div class='alert alert-warning'>No event was available from the querystring.</div>";
            }
        }
示例#5
0
        /// <summary>
        /// Loads and displays the event item occurrences
        /// </summary>
        private void BindData()
        {
            var rockContext = new RockContext();
            var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );

            // Grab events
            var qry = eventItemOccurrenceService
                    .Queryable( "EventItem, EventItem.EventItemAudiences,Schedule" )
                    .Where( m =>
                        m.EventItem.EventCalendarItems.Any( i => i.EventCalendarId == _calendarId ) &&
                        m.EventItem.IsActive &&
                        m.EventItem.IsApproved );

            // Filter by campus
            List<int> campusIds =  cblCampus.Items.OfType<ListItem>().Where( l => l.Selected ).Select( a => a.Value.AsInteger() ).ToList();
            if ( campusIds.Any() )
            {
                qry = qry
                    .Where( c =>
                        !c.CampusId.HasValue ||    // All
                        campusIds.Contains( c.CampusId.Value ) );
            }

            // Filter by Category
            List<int> categories = cblCategory.Items.OfType<ListItem>().Where( l => l.Selected ).Select( a => a.Value.AsInteger() ).ToList();
            if ( categories.Any() )
            {
                qry = qry
                    .Where( i => i.EventItem.EventItemAudiences
                        .Any( c => categories.Contains( c.DefinedValueId ) ) );
            }

            // Get the beginning and end dates
            var today = RockDateTime.Today;
            var filterStart = FilterStartDate.HasValue ? FilterStartDate.Value : today;
            var monthStart = new DateTime( filterStart.Year, filterStart.Month, 1 );
            var rangeStart = monthStart.AddMonths( -1 );
            var rangeEnd = monthStart.AddMonths( 2 );
            var beginDate = FilterStartDate.HasValue ? FilterStartDate.Value : rangeStart;
            var endDate = FilterEndDate.HasValue ? FilterEndDate.Value : rangeEnd;

            endDate = endDate.AddDays( 1 ).AddMilliseconds( -1 );

            // Get the occurrences
            var occurrences = qry.ToList();
            var occurrencesWithDates = occurrences
                .Select( o => new EventOccurrenceDate
                {
                    EventItemOccurrence = o,
                    Dates = o.GetStartTimes( beginDate, endDate ).ToList()
                } )
                .Where( d => d.Dates.Any() )
                .ToList();

            CalendarEventDates = new List<DateTime>();

            var eventOccurrenceSummaries = new List<EventOccurrenceSummary>();
            foreach ( var occurrenceDates in occurrencesWithDates )
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach ( var datetime in occurrenceDates.Dates )
                {
                    if ( eventItemOccurrence.Schedule.EffectiveEndDate.HasValue && ( eventItemOccurrence.Schedule.EffectiveStartDate != eventItemOccurrence.Schedule.EffectiveEndDate ) )
                    {
                        var multiDate = eventItemOccurrence.Schedule.EffectiveStartDate;
                        while ( multiDate.HasValue && ( multiDate.Value < eventItemOccurrence.Schedule.EffectiveEndDate.Value ))
                        {
                            CalendarEventDates.Add( multiDate.Value.Date );
                            multiDate = multiDate.Value.AddDays( 1 );
                        }
                    }
                    else
                    {
                        CalendarEventDates.Add( datetime.Date );
                    }

                    if ( datetime >= beginDate && datetime < endDate )
                    {
                        eventOccurrenceSummaries.Add( new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            Name = eventItemOccurrence.EventItem.Name,
                            DateTime = datetime,
                            Date = datetime.ToShortDateString(),
                            Time = datetime.ToShortTimeString(),
                            Campus = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Location = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            LocationDescription = eventItemOccurrence.Location,
                            Description = eventItemOccurrence.EventItem.Description,
                            Summary = eventItemOccurrence.EventItem.Summary,
                            OccurrenceNote = eventItemOccurrence.Note.SanitizeHtml(),
                            DetailPage = String.IsNullOrWhiteSpace( eventItemOccurrence.EventItem.DetailsUrl ) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        } );
                    }
                }
            }

            var eventSummaries = eventOccurrenceSummaries
                .OrderBy( e => e.DateTime )
                .GroupBy( e => e.Name )
                .Select( e => e.ToList() )
                .ToList();

            eventOccurrenceSummaries = eventOccurrenceSummaries
                .OrderBy( e => e.DateTime )
                .ThenBy( e => e.Name )
                .ToList();

            var mergeFields = new Dictionary<string, object>();
            mergeFields.Add( "TimeFrame", ViewMode );
            mergeFields.Add( "DetailsPage", LinkedPageUrl( "DetailsPage", null ) );
            mergeFields.Add( "EventItems", eventSummaries );
            mergeFields.Add( "EventItemOccurrences", eventOccurrenceSummaries );
            mergeFields.Add( "CurrentPerson", CurrentPerson );

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

            // show debug info
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lDebug.Visible = true;
                lDebug.Text = mergeFields.lavaDebugInfo();
            }
            else
            {
                lDebug.Visible = false;
                lDebug.Text = string.Empty;
            }
        }
示例#6
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext       = new RockContext();
            var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid();
            var eventCalendar     = new EventCalendarService(rockContext).Get(eventCalendarGuid);

            if (eventCalendar == null)
            {
                lMessages.Text = "<div class='alert alert-warning'>No event calendar is configured for this block.</div>";
                lContent.Text  = string.Empty;
                return;
            }
            else
            {
                lMessages.Text = string.Empty;
            }

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Grab events
            // NOTE: Do not use AsNoTracking() so that things can be lazy loaded if needed
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                      .Where(m =>
                             m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) &&
                             m.EventItem.IsActive);

            // Filter by campus (always include the "All Campuses" events)
            if (GetAttributeValue("UseCampusContext").AsBoolean())
            {
                var campusEntityType = EntityTypeCache.Get <Campus>();
                var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                if (contextCampus != null)
                {
                    qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                }
            }
            else
            {
                var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList();
                if (campusGuidList.Any())
                {
                    qry = qry.Where(e => !e.CampusId.HasValue || campusGuidList.Contains(e.Campus.Guid));
                }
            }

            // make sure they have a date range
            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(this.GetAttributeValue("DateRange"));
            var today     = RockDateTime.Today;

            dateRange.Start = dateRange.Start ?? today;
            if (dateRange.End == null)
            {
                dateRange.End = dateRange.Start.Value.AddDays(1000);
            }

            // Get the occurrences
            var occurrences          = qry.ToList();
            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o,
                Dates = o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).ToList()
            })
                                       .Where(d => d.Dates.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummaryKFS>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var datetime in occurrenceDates.Dates)
                {
                    CalendarEventDates.Add(datetime.Date);

                    if (datetime >= dateRange.Start.Value && datetime < dateRange.End.Value)
                    {
                        var eventAudiences = eventItemOccurrence.EventItem.EventItemAudiences;
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummaryKFS
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            EventItem           = eventItemOccurrence.EventItem,
                            EventItemAudiences  = eventAudiences.Select(o => DefinedValueCache.Get(o.DefinedValueId).Value).ToList(),
                            Name        = eventItemOccurrence.EventItem.Name,
                            DateTime    = datetime,
                            Date        = datetime.ToShortDateString(),
                            Time        = datetime.ToShortTimeString(),
                            Location    = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Description = eventItemOccurrence.EventItem.Description,
                            Summary     = eventItemOccurrence.EventItem.Summary,
                            DetailPage  = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        });
                    }
                }
            }

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

            // limit results
            int?maxItems = GetAttributeValue("MaxOccurrences").AsIntegerOrNull();

            if (maxItems.HasValue)
            {
                eventOccurrenceSummaries = eventOccurrenceSummaries.Take(maxItems.Value).ToList();
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("DetailsPage", LinkedPageUrl("DetailsPage", null));
            mergeFields.Add("EventOccurrenceSummaries", eventOccurrenceSummaries);

            //KFS Custom code to link Channels together
            var items         = GetCacheItem(CONTENT_CACHE_KEY) as List <ContentChannelItem>;
            var errorMessages = new List <string>();

            Guid?channelGuid = GetAttributeValue("ChannelforLava").AsGuidOrNull();

            if (channelGuid.HasValue)
            {
                //var rockContext = new RockContext();
                var service  = new ContentChannelItemService(rockContext);
                var itemType = typeof(Rock.Model.ContentChannelItem);

                ParameterExpression paramExpression = service.ParameterExpression;

                var contentChannel = new ContentChannelService(rockContext).Get(channelGuid.Value);

                if (contentChannel != null)
                {
                    var entityFields = HackEntityFields(contentChannel, rockContext);

                    if (items == null)
                    {
                        items = new List <ContentChannelItem>();

                        var qryChannel = service.Queryable("ContentChannel,ContentChannelType");

                        int?itemId = PageParameter("Item").AsIntegerOrNull();
                        {
                            qryChannel = qryChannel.Where(i => i.ContentChannelId == contentChannel.Id);

                            if (contentChannel.RequiresApproval)
                            {
                                // Check for the configured status and limit query to those
                                var statuses = new List <ContentChannelItemStatus>();

                                foreach (string statusVal in (GetAttributeValue("Status") ?? "2").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    var status = statusVal.ConvertToEnumOrNull <ContentChannelItemStatus>();
                                    if (status != null)
                                    {
                                        statuses.Add(status.Value);
                                    }
                                }
                                if (statuses.Any())
                                {
                                    qryChannel = qryChannel.Where(i => statuses.Contains(i.Status));
                                }
                            }

                            int?dataFilterId = GetAttributeValue("FilterId").AsIntegerOrNull();
                            if (dataFilterId.HasValue)
                            {
                                var        dataFilterService = new DataViewFilterService(rockContext);
                                var        dataFilter        = dataFilterService.Queryable("ChildFilters").FirstOrDefault(a => a.Id == dataFilterId.Value);
                                Expression whereExpression   = dataFilter != null?dataFilter.GetExpression(itemType, service, paramExpression, errorMessages) : null;

                                qryChannel = qryChannel.Where(paramExpression, whereExpression, null);
                            }
                        }

                        // All filtering has been added, now run query and load attributes
                        foreach (var item in qryChannel.ToList())
                        {
                            item.LoadAttributes(rockContext);
                            items.Add(item);
                        }

                        // Order the items
                        SortProperty sortProperty = null;

                        string orderBy = GetAttributeValue("Order");
                        if (!string.IsNullOrWhiteSpace(orderBy))
                        {
                            var fieldDirection = new List <string>();
                            foreach (var itemPair in orderBy.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Split('^')))
                            {
                                if (itemPair.Length == 2 && !string.IsNullOrWhiteSpace(itemPair[0]))
                                {
                                    var sortDirection = SortDirection.Ascending;
                                    if (!string.IsNullOrWhiteSpace(itemPair[1]))
                                    {
                                        sortDirection = itemPair[1].ConvertToEnum <SortDirection>(SortDirection.Ascending);
                                    }
                                    fieldDirection.Add(itemPair[0] + (sortDirection == SortDirection.Descending ? " desc" : ""));
                                }
                            }

                            sortProperty           = new SortProperty();
                            sortProperty.Direction = SortDirection.Ascending;
                            sortProperty.Property  = fieldDirection.AsDelimited(",");

                            string[] columns = sortProperty.Property.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            var itemQry = items.AsQueryable();
                            IOrderedQueryable <ContentChannelItem> orderedQry = null;

                            for (int columnIndex = 0; columnIndex < columns.Length; columnIndex++)
                            {
                                string column = columns[columnIndex].Trim();

                                var direction = sortProperty.Direction;
                                if (column.ToLower().EndsWith(" desc"))
                                {
                                    column    = column.Left(column.Length - 5);
                                    direction = sortProperty.Direction == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
                                }

                                try
                                {
                                    if (column.StartsWith("Attribute:"))
                                    {
                                        string attributeKey = column.Substring(10);

                                        if (direction == SortDirection.Ascending)
                                        {
                                            orderedQry = (columnIndex == 0) ?
                                                         itemQry.OrderBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) :
                                                         orderedQry.ThenBy(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue);
                                        }
                                        else
                                        {
                                            orderedQry = (columnIndex == 0) ?
                                                         itemQry.OrderByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue) :
                                                         orderedQry.ThenByDescending(i => i.AttributeValues.Where(v => v.Key == attributeKey).FirstOrDefault().Value.SortValue);
                                        }
                                    }
                                    else
                                    {
                                        if (direction == SortDirection.Ascending)
                                        {
                                            orderedQry = (columnIndex == 0) ? itemQry.OrderBy(column) : orderedQry.ThenBy(column);
                                        }
                                        else
                                        {
                                            orderedQry = (columnIndex == 0) ? itemQry.OrderByDescending(column) : orderedQry.ThenByDescending(column);
                                        }
                                    }
                                }
                                catch { }
                            }

                            try
                            {
                                if (orderedQry != null)
                                {
                                    items = orderedQry.ToList();
                                }
                            }
                            catch { }
                        }

                        int?cacheDuration = GetAttributeValue("CacheDuration").AsInteger();
                        if (cacheDuration > 0)
                        {
                            AddCacheItem(CONTENT_CACHE_KEY, items, cacheDuration.Value);
                        }
                    }
                }

                if (items != null)
                {
                    mergeFields.Add("ContentChannelItems", items);
                }
            }

            lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
        /// <summary>
        /// Loads and displays the event item occurrences
        /// </summary>
        private string BindData()
        {
            var cacheKey = string.Format("{0}CalendarLava", BlockCache.Id.ToString());

            var cache   = RockMemoryCache.Default;
            var content = ( string )cache.Get(cacheKey);

            var rockContext = new RockContext();
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
            var attributeService           = new AttributeService(rockContext);
            var attributeValueService      = new AttributeValueService(rockContext);

            int calendarItemEntityTypeId = EntityTypeCache.GetId(typeof(EventCalendarItem)).Value;

            // Grab events
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                      .GroupJoin(
                attributeService.Queryable(),
                p => calendarItemEntityTypeId,
                a => a.EntityTypeId,
                (eio, a) => new { EventItemOccurrence = eio, EventCalendarItemAttributes = a }
                )
                      .GroupJoin(
                attributeValueService.Queryable().Where(av => av.Attribute.EntityTypeId == ( int? )calendarItemEntityTypeId),
                obj => obj.EventItemOccurrence.EventItem.EventCalendarItems.Where(i => i.EventCalendarId == _calendarId).Select(i => i.Id).FirstOrDefault(),
                av => av.EntityId,
                (obj, av) => new
            {
                EventItemOccurrence              = obj.EventItemOccurrence,
                EventCalendarItemAttributes      = obj.EventCalendarItemAttributes,
                EventCalendarItemAttributeValues = av,
            }
                )
                      .Where(m =>
                             m.EventItemOccurrence.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == _calendarId) &&
                             m.EventItemOccurrence.EventItem.IsActive &&
                             m.EventItemOccurrence.EventItem.IsApproved);


            // Get the beginning and end dates
            var today       = RockDateTime.Now;
            var filterStart = today;
            var monthStart  = new DateTime(filterStart.Year, filterStart.Month, 1);
            var rangeStart  = monthStart.AddMonths(-1);
            var rangeEnd    = monthStart.AddMonths(2);
            var beginDate   = FilterStartDate.HasValue ? FilterStartDate.Value : rangeStart;
            var endDate     = FilterEndDate.HasValue ? FilterEndDate.Value : rangeEnd;

            endDate = endDate.AddDays(1).AddMilliseconds(-1);

            // Get the occurrences
            var occurrences = qry.ToList();

            foreach (var occ in occurrences)
            {
                occ.EventItemOccurrence.EventItem.LoadAttributes();
            }

            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence              = o.EventItemOccurrence,
                EventCalendarItemAttributes      = o.EventCalendarItemAttributes,
                EventCalendarItemAttributeValues = o.EventCalendarItemAttributeValues,
                Dates = o.EventItemOccurrence.GetStartTimes(beginDate, endDate).ToList()
            })
                                       .Where(d => d.Dates.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var datetime in occurrenceDates.Dates)
                {
                    if (eventItemOccurrence.Schedule.EffectiveEndDate.HasValue && (eventItemOccurrence.Schedule.EffectiveStartDate != eventItemOccurrence.Schedule.EffectiveEndDate))
                    {
                        var multiDate = eventItemOccurrence.Schedule.EffectiveStartDate;
                        while (multiDate.HasValue && (multiDate.Value < eventItemOccurrence.Schedule.EffectiveEndDate.Value))
                        {
                            CalendarEventDates.Add(multiDate.Value.Date);
                            multiDate = multiDate.Value.AddDays(1);
                        }
                    }
                    else
                    {
                        CalendarEventDates.Add(datetime.Date);
                    }

                    if (datetime >= beginDate && datetime < endDate)
                    {
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            Name                = eventItemOccurrence.EventItem.Name,
                            DateTime            = datetime,
                            Date                = datetime.ToShortDateString(),
                            Time                = datetime.ToShortTimeString(),
                            Campus              = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Location            = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            LocationDescription = eventItemOccurrence.Location,
                            Description         = eventItemOccurrence.EventItem.Description,
                            Summary             = eventItemOccurrence.EventItem.Summary,
                            URLSlugs            = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "URLSlugs").Select(av => av.Value).FirstOrDefault(),
                            OccurrenceNote      = eventItemOccurrence.Note.SanitizeHtml(),
                            DetailPage          = String.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl,
                            Priority            = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "EventPriority").Select(av => av.Value).FirstOrDefault().AsIntegerOrNull() ?? int.MaxValue
                        });
                    }
                }
            }

            var eventSummaries = eventOccurrenceSummaries
                                 .OrderBy(e => e.DateTime)
                                 .GroupBy(e => e.Name)
                                 .OrderBy(e => e.First().Priority)
                                 .Select(e => e.ToList())
                                 .ToList();

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

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

            mergeFields.Add("TimeFrame", ViewMode);
            mergeFields.Add("DetailsPage", LinkedPageRoute("DetailsPage"));
            mergeFields.Add("EventItems", eventSummaries);
            mergeFields.Add("EventItemOccurrences", eventOccurrenceSummaries);
            mergeFields.Add("CurrentPerson", CurrentPerson);

            content = ( string )GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands"));

            var minutes = GetAttributeValue("CacheDuration").AsInteger();

            if (minutes > 0)
            {
                var cachePolicy = new CacheItemPolicy();
                cachePolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutes);
                cache.Set(cacheKey, content, cachePolicy);
            }

            return(content);
        }
示例#8
0
        public object GetEvents(DateTime beginDate, DateTime endDate)
        {
            using (var rockContext = new RockContext())
            {
                var eventCalendar = new EventCalendarService(rockContext).Get(Calendar ?? Guid.Empty);
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

                if (eventCalendar == null)
                {
                    return(new List <object>());
                }

                // Grab events
                var qry = eventItemOccurrenceService
                          .Queryable("EventItem, EventItem.EventItemAudiences, Schedule")
                          .Where(m =>
                                 m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) &&
                                 m.EventItem.IsActive &&
                                 m.EventItem.IsApproved);

                // Check for Campus Parameter or Campus Context.
                if (EnableCampusFiltering)
                {
                    var campusGuid = RequestContext.GetPageParameter("CampusGuid").AsGuidOrNull();
                    if (campusGuid.HasValue)
                    {
                        // Check if there's a campus with this guid.
                        var campus = CampusCache.Get(campusGuid.Value);
                        if (campus != null)
                        {
                            qry = qry.Where(a => !a.CampusId.HasValue || a.CampusId == campus.Id);
                        }
                    }
                    else
                    {
                        var contextCampus = RequestContext.GetContextEntity <Campus>();
                        if (contextCampus != null)
                        {
                            qry = qry.Where(a => !a.CampusId.HasValue || a.Campus.Id == contextCampus.Id);
                        }
                        else if (RequestContext.CurrentPerson != null && RequestContext.CurrentPerson.PrimaryCampusId.HasValue)
                        {
                            var campusId = RequestContext.CurrentPerson.PrimaryCampusId.Value;

                            qry = qry.Where(a => !a.CampusId.HasValue || a.CampusId == campusId);
                        }
                    }
                }

                // Get the occurrences
                var occurrences = qry.ToList()
                                  .SelectMany(a =>
                {
                    var duration = a.Schedule?.DurationInMinutes ?? 0;

                    return(a.GetStartTimes(beginDate, endDate)
                           .Where(b => b >= beginDate && b < endDate)
                           .Select(b => new
                    {
                        Date = b.ToRockDateTimeOffset(),
                        Duration = duration,
                        AudienceGuids = a.EventItem.EventItemAudiences.Select(c => DefinedValueCache.Get(c.DefinedValueId)?.Guid).Where(c => c.HasValue).Select(c => c.Value).ToList(),
                        EventItemOccurrence = a
                    }));
                })
                                  .Select(a => new
                {
                    a.EventItemOccurrence,
                    a.EventItemOccurrence.Guid,
                    a.EventItemOccurrence.Id,
                    a.EventItemOccurrence.EventItem.Name,
                    DateTime            = a.Date,
                    EndDateTime         = a.Duration > 0 ? ( DateTimeOffset? )a.Date.AddMinutes(a.Duration) : null,
                    Date                = a.Date.ToString("d"), // Short date
                    Time                = a.Date.ToString("t"), // Short time
                    Campus              = a.EventItemOccurrence.Campus != null ? a.EventItemOccurrence.Campus.Name : "All Campuses",
                    Location            = a.EventItemOccurrence.Campus != null ? a.EventItemOccurrence.Campus.Name : "All Campuses",
                    LocationDescription = a.EventItemOccurrence.Location,
                    Audiences           = a.AudienceGuids,
                    a.EventItemOccurrence.EventItem.Description,
                    a.EventItemOccurrence.EventItem.Summary,
                    OccurrenceNote = a.EventItemOccurrence.Note.SanitizeHtml()
                });

                var lavaTemplate = CreateLavaTemplate();

                var commonMergeFields = new CommonMergeFieldsOptions
                {
                    GetLegacyGlobalMergeFields = false
                };

                var mergeFields = RequestContext.GetCommonMergeFields(null, commonMergeFields);
                mergeFields.Add("Items", occurrences.ToList());

                var output = lavaTemplate.ResolveMergeFields(mergeFields);

                return(ActionOk(new StringContent(output, Encoding.UTF8, "application/json")));
            }
        }
示例#9
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)
        {
            EventItemOccurrence eventItemOccurrence = null;

            using (var rockContext = new RockContext())
            {
                bool newItem = false;
                var  eventItemOccurrenceService         = new EventItemOccurrenceService(rockContext);
                var  eventItemOccurrenceGroupMapService = new EventItemOccurrenceGroupMapService(rockContext);
                var  registrationInstanceService        = new RegistrationInstanceService(rockContext);
                var  scheduleService = new ScheduleService(rockContext);

                int eventItemOccurrenceId = hfEventItemOccurrenceId.ValueAsInt();
                if (eventItemOccurrenceId != 0)
                {
                    eventItemOccurrence = eventItemOccurrenceService
                                          .Queryable("Linkages")
                                          .Where(i => i.Id == eventItemOccurrenceId)
                                          .FirstOrDefault();
                }

                if (eventItemOccurrence == null)
                {
                    newItem             = true;
                    eventItemOccurrence = new EventItemOccurrence {
                        EventItemId = PageParameter("EventItemId").AsInteger()
                    };
                    eventItemOccurrenceService.Add(eventItemOccurrence);
                }

                int?newCampusId = ddlCampus.SelectedValueAsInt();
                if (eventItemOccurrence.CampusId != newCampusId)
                {
                    eventItemOccurrence.CampusId = newCampusId;
                    if (newCampusId.HasValue)
                    {
                        var campus = new CampusService(rockContext).Get(newCampusId.Value);
                        eventItemOccurrence.Campus = campus;
                    }
                    else
                    {
                        eventItemOccurrence.Campus = null;
                    }
                }

                eventItemOccurrence.Location = tbLocation.Text;

                string iCalendarContent = sbSchedule.iCalendarContent;
                var    calEvent         = ScheduleICalHelper.GetCalenderEvent(iCalendarContent);
                if (calEvent != null && calEvent.DTStart != null)
                {
                    if (eventItemOccurrence.Schedule == null)
                    {
                        eventItemOccurrence.Schedule = new Schedule();
                    }
                    eventItemOccurrence.Schedule.iCalendarContent = iCalendarContent;
                }
                else
                {
                    if (eventItemOccurrence.ScheduleId.HasValue)
                    {
                        var oldSchedule = scheduleService.Get(eventItemOccurrence.ScheduleId.Value);
                        if (oldSchedule != null)
                        {
                            scheduleService.Delete(oldSchedule);
                        }
                    }
                }

                if (!eventItemOccurrence.ContactPersonAliasId.Equals(ppContact.PersonAliasId))
                {
                    PersonAlias personAlias = null;
                    eventItemOccurrence.ContactPersonAliasId = ppContact.PersonAliasId;
                    if (eventItemOccurrence.ContactPersonAliasId.HasValue)
                    {
                        personAlias = new PersonAliasService(rockContext).Get(eventItemOccurrence.ContactPersonAliasId.Value);
                    }

                    if (personAlias != null)
                    {
                        eventItemOccurrence.ContactPersonAlias = personAlias;
                    }
                }

                eventItemOccurrence.ContactPhone = PhoneNumber.FormattedNumber(PhoneNumber.DefaultCountryCode(), pnPhone.Number);
                eventItemOccurrence.ContactEmail = tbEmail.Text;
                eventItemOccurrence.Note         = htmlOccurrenceNote.Text;

                // Remove any linkage no longer in UI
                Guid uiLinkageGuid = LinkageState != null ? LinkageState.Guid : Guid.Empty;
                foreach (var linkage in eventItemOccurrence.Linkages.Where(l => !l.Guid.Equals(uiLinkageGuid)).ToList())
                {
                    eventItemOccurrence.Linkages.Remove(linkage);
                    eventItemOccurrenceGroupMapService.Delete(linkage);
                }

                // Add/Update linkage in UI
                if (!uiLinkageGuid.Equals(Guid.Empty))
                {
                    var linkage = eventItemOccurrence.Linkages.Where(l => l.Guid.Equals(uiLinkageGuid)).FirstOrDefault();
                    if (linkage == null)
                    {
                        linkage = new EventItemOccurrenceGroupMap();
                        eventItemOccurrence.Linkages.Add(linkage);
                    }
                    linkage.CopyPropertiesFrom(LinkageState);

                    // update registration instance
                    if (LinkageState.RegistrationInstance != null)
                    {
                        if (LinkageState.RegistrationInstance.Id != 0)
                        {
                            linkage.RegistrationInstance = registrationInstanceService.Get(LinkageState.RegistrationInstance.Id);
                        }

                        if (linkage.RegistrationInstance == null)
                        {
                            var registrationInstance = new RegistrationInstance();
                            registrationInstanceService.Add(registrationInstance);
                            linkage.RegistrationInstance = registrationInstance;
                        }

                        linkage.RegistrationInstance.CopyPropertiesFrom(LinkageState.RegistrationInstance);
                    }
                }

                if (!Page.IsValid)
                {
                    return;
                }

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

                rockContext.SaveChanges();

                var qryParams = new Dictionary <string, string>();
                qryParams.Add("EventCalendarId", PageParameter("EventCalendarId"));
                qryParams.Add("EventItemId", PageParameter("EventItemId"));

                if (newItem)
                {
                    NavigateToParentPage(qryParams);
                }
                else
                {
                    qryParams.Add("EventItemOccurrenceId", eventItemOccurrence.Id.ToString());
                    NavigateToPage(RockPage.Guid, qryParams);
                }
            }
        }
示例#10
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext = new RockContext();
            var eventCalendarGuid = GetAttributeValue( "EventCalendar" ).AsGuid();
            var eventCalendar = new EventCalendarService( rockContext ).Get( eventCalendarGuid );

            if ( eventCalendar == null )
            {
                lMessages.Text = "<div class='alert alert-warning'>No event calendar is configured for this block.</div>";
                lContent.Text = string.Empty;
                return;
            }
            else
            {
                lMessages.Text = string.Empty;
            }

            var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );

            // Grab events
            // NOTE: Do not use AsNoTracking() so that things can be lazy loaded if needed
            var qry = eventItemOccurrenceService
                    .Queryable( "EventItem, EventItem.EventItemAudiences,Schedule" )
                    .Where( m =>
                        m.EventItem.EventCalendarItems.Any( i => i.EventCalendarId == eventCalendar.Id ) &&
                        m.EventItem.IsActive );

            // Filter by campus (always include the "All Campuses" events)
            if ( GetAttributeValue( "UseCampusContext" ).AsBoolean() )
            {
                var campusEntityType = EntityTypeCache.Read<Campus>();
                var contextCampus = RockPage.GetCurrentContext( campusEntityType ) as Campus;

                if ( contextCampus != null )
                {
                    qry = qry.Where( e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue );
                }
            }
            else
            {
                var campusGuidList = GetAttributeValue( "Campuses" ).Split( ',' ).AsGuidList();
                if ( campusGuidList.Any() )
                {
                    qry = qry.Where( e => !e.CampusId.HasValue ||  campusGuidList.Contains( e.Campus.Guid ) );
                }
            }

            // make sure they have a date range
            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( this.GetAttributeValue( "DateRange" ) );
            var today = RockDateTime.Today;
            dateRange.Start = dateRange.Start ?? today;
            if ( dateRange.End == null )
            {
                dateRange.End = dateRange.Start.Value.AddDays( 1000 );
            }

            // Get the occurrences
            var occurrences = qry.ToList();
            var occurrencesWithDates = occurrences
                .Select( o => new EventOccurrenceDate
                {
                    EventItemOccurrence = o,
                    Dates = o.GetStartTimes( dateRange.Start.Value, dateRange.End.Value ).ToList()
                } )
                .Where( d => d.Dates.Any() )
                .ToList();

            CalendarEventDates = new List<DateTime>();

            var eventOccurrenceSummaries = new List<EventOccurrenceSummary>();
            foreach ( var occurrenceDates in occurrencesWithDates )
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach ( var datetime in occurrenceDates.Dates )
                {
                    CalendarEventDates.Add( datetime.Date );

                    if ( datetime >= dateRange.Start.Value && datetime < dateRange.End.Value )
                    {
                        eventOccurrenceSummaries.Add( new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            EventItem = eventItemOccurrence.EventItem,
                            Name = eventItemOccurrence.EventItem.Name,
                            DateTime = datetime,
                            Date = datetime.ToShortDateString(),
                            Time = datetime.ToShortTimeString(),
                            Location = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Description = eventItemOccurrence.EventItem.Description,
                            Summary = eventItemOccurrence.EventItem.Summary,
                            DetailPage = string.IsNullOrWhiteSpace( eventItemOccurrence.EventItem.DetailsUrl ) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        } );
                    }
                }
            }

            eventOccurrenceSummaries = eventOccurrenceSummaries
                .OrderBy( e => e.DateTime )
                .ThenBy( e => e.Name )
                .ToList();

            // limit results
            int? maxItems = GetAttributeValue( "MaxOccurrences" ).AsIntegerOrNull();
            if ( maxItems.HasValue )
            {
                eventOccurrenceSummaries = eventOccurrenceSummaries.Take( maxItems.Value ).ToList();
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
            mergeFields.Add( "DetailsPage", LinkedPageRoute( "DetailsPage" ) );
            mergeFields.Add( "EventOccurrenceSummaries", eventOccurrenceSummaries );

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

            // show debug info
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lDebug.Visible = true;
                lDebug.Text = mergeFields.lavaDebugInfo();
            }
            else
            {
                lDebug.Visible = false;
                lDebug.Text = string.Empty;
            }
        }
        private void DisplayDetails()
        {
            int eventItemOccurrenceId = 0;

            // get the calendarItem id
            if ( !string.IsNullOrWhiteSpace( PageParameter( "EventOccurrenceId" ) ) )
            {
                eventItemOccurrenceId = Convert.ToInt32( PageParameter( "EventOccurrenceId" ) );
            }
            if ( eventItemOccurrenceId > 0 )
            {
                var eventItemOccurrenceService = new EventItemOccurrenceService( new RockContext() );
                var qry = eventItemOccurrenceService
                    .Queryable( "EventItem, EventItem.Photo, Campus, Linkages" )
                    .Where( i => i.Id == eventItemOccurrenceId );

                var eventItemOccurrence = qry.FirstOrDefault();

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

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

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

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

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
            else
            {
                lOutput.Text = "<div class='alert alert-warning'>No event was available from the querystring.</div>";
            }
        }
        /// <summary>
        /// Loads and displays the event item occurrences
        /// </summary>
        private void BindData()
        {
            var rockContext = new RockContext();
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Grab events
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                      .Where(m =>
                             m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == _calendarId) &&
                             m.EventItem.IsActive &&
                             m.EventItem.IsApproved);

            // Filter by campus
            List <int> campusIds = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            if (campusIds.Any())
            {
                qry = qry
                      .Where(c =>
                             !c.CampusId.HasValue || // All
                             campusIds.Contains(c.CampusId.Value));
            }

            // Filter by Category
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            if (categories.Any())
            {
                qry = qry
                      .Where(i => i.EventItem.EventItemAudiences
                             .Any(c => categories.Contains(c.DefinedValueId)));
            }

            // Get the beginning and end dates
            var today       = RockDateTime.Today;
            var filterStart = FilterStartDate.HasValue ? FilterStartDate.Value : today;
            var monthStart  = new DateTime(filterStart.Year, filterStart.Month, 1);
            var rangeStart  = monthStart.AddMonths(-1);
            var rangeEnd    = monthStart.AddMonths(7); //featured events within the next 6 months
            //var beginDate = FilterStartDate.HasValue ? FilterStartDate.Value : rangeStart;
            var beginDate = today;
            //var endDate = FilterEndDate.HasValue ? FilterEndDate.Value : rangeEnd;
            var endDate = rangeEnd;

            endDate = endDate.AddDays(1).AddMilliseconds(-1);

            // Get the occurrences
            var occurrences          = qry.ToList();
            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o,
                Dates = o.GetStartTimes(rangeStart, rangeEnd).ToList()
            })
                                       .Where(d => d.Dates.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var datetime in occurrenceDates.Dates)
                {
                    if (eventItemOccurrence.Schedule.EffectiveEndDate.HasValue && (eventItemOccurrence.Schedule.EffectiveStartDate != eventItemOccurrence.Schedule.EffectiveEndDate))
                    {
                        var multiDate = eventItemOccurrence.Schedule.EffectiveStartDate;
                        while (multiDate.HasValue && (multiDate.Value < eventItemOccurrence.Schedule.EffectiveEndDate.Value))
                        {
                            CalendarEventDates.Add(multiDate.Value.Date);
                            multiDate = multiDate.Value.AddDays(1);
                        }
                    }
                    else
                    {
                        CalendarEventDates.Add(datetime.Date);
                    }

                    if (datetime >= beginDate && datetime < endDate)
                    {
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            Name                = eventItemOccurrence.EventItem.Name,
                            DateTime            = datetime,
                            Date                = datetime.ToShortDateString(),
                            Time                = datetime.ToShortTimeString(),
                            Campus              = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Location            = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            LocationDescription = eventItemOccurrence.Location,
                            Description         = eventItemOccurrence.EventItem.Description,
                            Summary             = eventItemOccurrence.EventItem.Summary,
                            OccurrenceNote      = eventItemOccurrence.Note != null ? eventItemOccurrence.Note.SanitizeHtml() : null,
                            DetailPage          = String.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        });
                    }
                }
            }

            var eventSummaries = eventOccurrenceSummaries
                                 .OrderBy(e => e.DateTime)
                                 .GroupBy(e => e.Name)
                                 .Select(e => e.ToList())
                                 .ToList();

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

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

            mergeFields.Add("TimeFrame", ViewMode);
            mergeFields.Add("DetailsPage", LinkedPageUrl("DetailsPage", null));
            mergeFields.Add("EventItems", eventSummaries);
            mergeFields.Add("EventItemOccurrences", eventOccurrenceSummaries);
            mergeFields.Add("CurrentPerson", CurrentPerson);

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

            // show debug info
            if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }
            else
            {
                lDebug.Visible = false;
                lDebug.Text    = string.Empty;
            }
        }
示例#13
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);
                }
            }
        }
示例#14
0
        /// <summary>
        /// Loads and displays the event item occurrences
        /// </summary>
        private void BindData()
        {
            List <int> campusIds  = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            var cacheKey = string.Format("{0}^{1}^{2}CalendarLava",
                                         string.Join("-", campusIds),
                                         string.Join("-", categories),
                                         BlockCache.Id.ToString());
            var content = RockCache.Get(cacheKey, System.Globalization.CultureInfo.CurrentCulture.ToString());

            if (content != null && !string.IsNullOrWhiteSpace(( string )content))
            {
                lOutput.Text = ( string )content;
                return;
            }

            var rockContext = new RockContext();
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
            var attributeService           = new AttributeService(rockContext);
            var attributeValueService      = new AttributeValueService(rockContext);

            int calendarItemEntityTypeId        = EntityTypeCache.GetId(typeof(EventCalendarItem)).Value;
            int eventItemOccurrenceEntityTypeId = EntityTypeCache.GetId(typeof(EventItemOccurrence)).Value;

            // Grab events
            var firstQry = eventItemOccurrenceService
                           .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                           .Where(e =>
                                  e.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == _calendarId) &&
                                  e.EventItem.IsActive &&
                                  e.EventItem.IsApproved).ToList();

            var qry = firstQry
                      .GroupJoin(
                attributeValueService.Queryable().Where(av => av.Attribute.EntityTypeId == ( int? )calendarItemEntityTypeId || av.Attribute.EntityTypeId == ( int? )eventItemOccurrenceEntityTypeId),
                obj => obj.EventItem.EventCalendarItems.Where(i => i.EventCalendarId == _calendarId).Select(i => i.Id).FirstOrDefault(),
                av => av.EntityId,
                (obj, av) => new
            {
                EventItemOccurrence = obj,
                EventCalendarItemAttributeValues = av,
            })
                      .GroupJoin(
                attributeValueService.Queryable().Where(av => av.Attribute.EntityTypeId == ( int? )eventItemOccurrenceEntityTypeId),
                obj => obj.EventItemOccurrence.Id,
                av => av.EntityId,
                (obj, av) => new
            {
                EventItemOccurrence = obj.EventItemOccurrence,
                EventCalendarItemAttributeValues   = obj.EventCalendarItemAttributeValues,
                EventItemOccurrenceAttributeValues = av
            }
                );


            // Filter by campus
            if (campusIds.Any())
            {
                qry = qry
                      .Where(c =>
                             !c.EventItemOccurrence.CampusId.HasValue || // All
                             campusIds.Contains(c.EventItemOccurrence.CampusId.Value));
            }

            // Filter by Category
            if (categories.Any())
            {
                qry = qry
                      .Where(i => i.EventItemOccurrence.EventItem.EventItemAudiences
                             .Any(c => categories.Contains(c.DefinedValueId)));
            }

            // Get the beginning and end dates
            var today       = RockDateTime.Now;
            var filterStart = FilterStartDate.HasValue ? FilterStartDate.Value : today;
            var monthStart  = new DateTime(filterStart.Year, filterStart.Month, 1);
            var rangeStart  = monthStart.AddMonths(-1);
            var rangeEnd    = monthStart.AddMonths(2);
            var beginDate   = FilterStartDate.HasValue ? FilterStartDate.Value : rangeStart;
            var endDate     = FilterEndDate.HasValue ? FilterEndDate.Value : rangeEnd;

            endDate = endDate.AddDays(1).AddMilliseconds(-1);

            var scheduleEntityType = EntityTypeCache.Get(Rock.SystemGuid.EntityType.SCHEDULE).Id;
            var attributeId        = attributeService.Queryable()
                                     .Where(a => a.EntityTypeId == scheduleEntityType && a.Key == "NextStartDate")
                                     .FirstOrDefault()
                                     .Id;

            // Get the occurrences
            var occurrences = qry
                              .Where(o => o.EventItemOccurrence.Schedule != null)
                              .ToList();

            var eventSchedules = occurrences.Select(o => o.EventItemOccurrence.Schedule.Id).ToList();

            var schedules = attributeValueService.Queryable()
                            .Where(av => av.AttributeId == attributeId)
                            .Where(av => eventSchedules.Contains(av.EntityId ?? 0))
                            .ToDictionary(av => av.EntityId, av => av.Value);

            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o.EventItemOccurrence,
                EventCalendarItemAttributeValues   = o.EventCalendarItemAttributeValues,
                EventItemOccurrenceAttributeValues = o.EventItemOccurrenceAttributeValues,
                Date = schedules.ContainsKey(o.EventItemOccurrence.Schedule.Id) ? schedules[o.EventItemOccurrence.Schedule.Id].AsDateTime() ?? new DateTime() : new DateTime()
            })
                                       .Where(d => d.Date >= RockDateTime.Today)
                                       .ToList();

            var priorityAttributeKey = GetAttributeValue("PriorityAttributeKey");

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;

                if (occurrenceDates.Date >= beginDate && occurrenceDates.Date < endDate)
                {
                    var primaryMinistry          = DefinedValueCache.Get(occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "PrimaryMinistry").Select(av => av.Value).FirstOrDefault());
                    var primaryMinistryImageGuid = "";
                    var primaryMinistryName      = "";
                    if (primaryMinistry != null)
                    {
                        primaryMinistryName      = primaryMinistry.Value;
                        primaryMinistryImageGuid = primaryMinistry.GetAttributeValue("CalendarImage");
                    }

                    eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                    {
                        EventItemOccurrence = eventItemOccurrence,
                        EventItem           = eventItemOccurrence.EventItem,
                        EventItemPhotoId    = eventItemOccurrence.EventItem.PhotoId ?? 0,
                        ICalendarContent    = eventItemOccurrence.Schedule.iCalendarContent,
                        Name                     = eventItemOccurrence.EventItem.Name,
                        DateTime                 = occurrenceDates.Date,
                        Date                     = occurrenceDates.Date.ToShortDateString(),
                        Time                     = occurrenceDates.Date.ToShortTimeString(),
                        Campus                   = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                        Location                 = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                        LocationDescription      = eventItemOccurrence.Location,
                        Description              = eventItemOccurrence.EventItem.Description,
                        Summary                  = eventItemOccurrence.EventItem.Summary,
                        OccurrenceNote           = eventItemOccurrence.Note.SanitizeHtml(),
                        DetailPage               = String.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl,
                        PrimaryMinistryImageGuid = primaryMinistryImageGuid,
                        PrimaryMinstryTitle      = primaryMinistryName,
                        URLSlugs                 = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "URLSlugs").Select(av => av.Value).FirstOrDefault(),
                        Priority                 = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == priorityAttributeKey).Select(av => av.Value).FirstOrDefault().AsIntegerOrNull() ?? int.MaxValue,
                        ImageHeaderText          = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "ImageHeaderText").Select(av => av.Value).FirstOrDefault(),
                        ImageHeaderTextSmall     = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "ImageHeaderTextSmall").Select(av => av.Value).FirstOrDefault(),
                        EventDatesHide           = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "EventDatesHide").Select(av => av.Value).FirstOrDefault(),
                        AttChildcareAvailable    = occurrenceDates.EventItemOccurrenceAttributeValues.Where(av => av.AttributeKey == "ChildcareAvailable").Select(av => av.Value).FirstOrDefault(),
                        AttScheduleText          = occurrenceDates.EventItemOccurrenceAttributeValues.Where(av => av.AttributeKey == "ScheduleText").Select(av => av.Value).FirstOrDefault(),
                        AttUseOnlyScheduleText   = occurrenceDates.EventItemOccurrenceAttributeValues.Where(av => av.AttributeKey == "UseOnlyScheduleText").Select(av => av.Value).FirstOrDefault(),
                        CustomDateText           = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "CustomDateText").Select(av => av.Value).FirstOrDefault(),
                        CustomLocationText       = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "CustomLocationText").Select(av => av.Value).FirstOrDefault(),
                    });
                }
            }

            var eventSummaries = eventOccurrenceSummaries
                                 .OrderBy(e => e.DateTime)
                                 .GroupBy(e => e.Name)
                                 .OrderBy(e => e.First().Priority)
                                 .Select(e => e.ToList())
                                 .Take(GetAttributeValue("Limit").AsInteger())
                                 .ToList();

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

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

            mergeFields.Add("TimeFrame", ViewMode);
            mergeFields.Add("DetailsPage", LinkedPageRoute("DetailsPage"));
            mergeFields.Add("EventItems", eventSummaries);
            mergeFields.Add("EventItemOccurrences", eventOccurrenceSummaries);
            mergeFields.Add("CurrentPerson", CurrentPerson);

            var text     = GetAttributeValue("LavaTemplate");
            var commands = GetAttributeValue("EnabledLavaCommands");

            lOutput.Text = text.ResolveMergeFields(mergeFields, commands);

            var minutes = GetAttributeValue("CacheDuration").AsInteger();

            if (minutes > 0)
            {
                string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;
                RockCache.AddOrUpdate(cacheKey,
                                      System.Globalization.CultureInfo.CurrentCulture.ToString(),
                                      lOutput.Text, RockDateTime.Now.AddMinutes(minutes),
                                      cacheTags);
            }
        }
示例#15
0
        public object GetEvents(DateTime beginDate, DateTime endDate)
        {
            using (var rockContext = new RockContext())
            {
                var eventCalendar = new EventCalendarService(rockContext).Get(Calendar ?? Guid.Empty);
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

                if (eventCalendar == null)
                {
                    return(new List <object>());
                }

                // Grab events
                var qry = eventItemOccurrenceService
                          .Queryable("EventItem, EventItem.EventItemAudiences, Schedule")
                          .Where(m =>
                                 m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) &&
                                 m.EventItem.IsActive &&
                                 m.EventItem.IsApproved);

                // Get the occurrences
                var occurrences = qry.ToList()
                                  .SelectMany(a =>
                {
                    var duration = a.Schedule?.DurationInMinutes ?? 0;

                    return(a.GetStartTimes(beginDate, endDate)
                           .Where(b => b >= beginDate && b < endDate)
                           .Select(b => new
                    {
                        Date = b,
                        Duration = duration,
                        AudienceGuids = a.EventItem.EventItemAudiences.Select(c => DefinedValueCache.Get(c.DefinedValueId)?.Guid).Where(c => c.HasValue).Select(c => c.Value).ToList(),
                        EventItemOccurrence = a
                    }));
                })
                                  .Select(a => new
                {
                    a.EventItemOccurrence,
                    a.EventItemOccurrence.Guid,
                    a.EventItemOccurrence.Id,
                    a.EventItemOccurrence.EventItem.Name,
                    DateTime            = a.Date,
                    EndDateTime         = a.Duration > 0 ? ( DateTime? )a.Date.AddMinutes(a.Duration) : null,
                    Date                = a.Date.ToShortDateString(),
                    Time                = a.Date.ToShortTimeString(),
                    Campus              = a.EventItemOccurrence.Campus != null ? a.EventItemOccurrence.Campus.Name : "All Campuses",
                    Location            = a.EventItemOccurrence.Campus != null ? a.EventItemOccurrence.Campus.Name : "All Campuses",
                    LocationDescription = a.EventItemOccurrence.Location,
                    Audiences           = a.AudienceGuids,
                    a.EventItemOccurrence.EventItem.Description,
                    a.EventItemOccurrence.EventItem.Summary,
                    OccurrenceNote = a.EventItemOccurrence.Note.SanitizeHtml()
                });

                var lavaTemplate = CreateLavaTemplate();

                var commonMergeFields = new CommonMergeFieldsOptions
                {
                    GetLegacyGlobalMergeFields = false
                };

                var mergeFields = RequestContext.GetCommonMergeFields(null, commonMergeFields);
                mergeFields.Add("Items", occurrences.ToList());

                var output = lavaTemplate.ResolveMergeFields(mergeFields);

                return(ActionOk(new StringContent(output, Encoding.UTF8, "application/json")));
            }
        }
        /// <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 )
        {
            EventItemOccurrence eventItemOccurrence = null;

            using ( var rockContext = new RockContext() )
            {
                bool newItem = false;
                var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );
                var eventItemOccurrenceGroupMapService = new EventItemOccurrenceGroupMapService( rockContext );
                var registrationInstanceService = new RegistrationInstanceService( rockContext );
                var scheduleService = new ScheduleService( rockContext );

                int eventItemOccurrenceId = hfEventItemOccurrenceId.ValueAsInt();
                if ( eventItemOccurrenceId != 0 )
                {
                    eventItemOccurrence = eventItemOccurrenceService
                        .Queryable( "Linkages" )
                        .Where( i => i.Id == eventItemOccurrenceId )
                        .FirstOrDefault();
                }

                if ( eventItemOccurrence == null )
                {
                    newItem = true;
                    eventItemOccurrence = new EventItemOccurrence{ EventItemId = PageParameter("EventItemId").AsInteger() };
                    eventItemOccurrenceService.Add( eventItemOccurrence );
                }

                int? newCampusId = ddlCampus.SelectedValueAsInt();
                if ( eventItemOccurrence.CampusId != newCampusId )
                {
                    eventItemOccurrence.CampusId = newCampusId;
                    if ( newCampusId.HasValue )
                    {
                        var campus = new CampusService( rockContext ).Get( newCampusId.Value );
                        eventItemOccurrence.Campus = campus;
                    }
                    else
                    {
                        eventItemOccurrence.Campus = null;
                    }
                }

                eventItemOccurrence.Location = tbLocation.Text;

                string iCalendarContent = sbSchedule.iCalendarContent;
                var calEvent = ScheduleICalHelper.GetCalenderEvent( iCalendarContent );
                if ( calEvent != null && calEvent.DTStart != null )
                {
                    if ( eventItemOccurrence.Schedule == null )
                    {
                        eventItemOccurrence.Schedule = new Schedule();
                    }
                    eventItemOccurrence.Schedule.iCalendarContent = iCalendarContent;
                }
                else
                {
                    if ( eventItemOccurrence.ScheduleId.HasValue )
                    {
                        var oldSchedule = scheduleService.Get( eventItemOccurrence.ScheduleId.Value );
                        if ( oldSchedule != null )
                        {
                            scheduleService.Delete( oldSchedule );
                        }
                    }
                }

                if ( !eventItemOccurrence.ContactPersonAliasId.Equals( ppContact.PersonAliasId ))
                {
                    PersonAlias personAlias = null;
                    eventItemOccurrence.ContactPersonAliasId = ppContact.PersonAliasId;
                    if ( eventItemOccurrence.ContactPersonAliasId.HasValue )
                    {
                        personAlias = new PersonAliasService( rockContext ).Get( eventItemOccurrence.ContactPersonAliasId.Value );
                    }

                    if ( personAlias != null )
                    {
                        eventItemOccurrence.ContactPersonAlias = personAlias;
                    }
                }

                eventItemOccurrence.ContactPhone = PhoneNumber.FormattedNumber( PhoneNumber.DefaultCountryCode(), pnPhone.Number );
                eventItemOccurrence.ContactEmail = tbEmail.Text;
                eventItemOccurrence.Note = htmlOccurrenceNote.Text;

                // Remove any linkage no longer in UI
                Guid uiLinkageGuid = LinkageState != null ? LinkageState.Guid : Guid.Empty;
                foreach( var linkage in eventItemOccurrence.Linkages.Where( l => !l.Guid.Equals(uiLinkageGuid)).ToList())
                {
                    eventItemOccurrence.Linkages.Remove( linkage );
                    eventItemOccurrenceGroupMapService.Delete( linkage );
                }

                // Add/Update linkage in UI
                if ( !uiLinkageGuid.Equals( Guid.Empty ))
                {
                    var linkage = eventItemOccurrence.Linkages.Where( l => l.Guid.Equals( uiLinkageGuid)).FirstOrDefault();
                    if ( linkage == null )
                    {
                        linkage = new EventItemOccurrenceGroupMap();
                        eventItemOccurrence.Linkages.Add( linkage );
                    }
                    linkage.CopyPropertiesFrom( LinkageState );

                    // update registration instance
                    if ( LinkageState.RegistrationInstance != null )
                    {
                        if ( LinkageState.RegistrationInstance.Id != 0 )
                        {
                            linkage.RegistrationInstance = registrationInstanceService.Get( LinkageState.RegistrationInstance.Id );
                        }

                        if ( linkage.RegistrationInstance == null )
                        {
                            var registrationInstance = new RegistrationInstance();
                            registrationInstanceService.Add( registrationInstance );
                            linkage.RegistrationInstance = registrationInstance;
                        }

                        linkage.RegistrationInstance.CopyPropertiesFrom( LinkageState.RegistrationInstance );
                    }

                }

                if ( !Page.IsValid )
                {
                    return;
                }

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

                rockContext.SaveChanges();

                var qryParams = new Dictionary<string, string>();
                qryParams.Add( "EventCalendarId", PageParameter( "EventCalendarId" ) );
                qryParams.Add( "EventItemId", PageParameter( "EventItemId" ) );

                if ( newItem )
                {
                    NavigateToParentPage( qryParams );
                }
                else
                {
                    qryParams.Add( "EventItemOccurrenceId", eventItemOccurrence.Id.ToString() );
                    NavigateToPage( RockPage.Guid, qryParams );
                }
            }
        }
示例#17
0
        /// <summary>
        /// Loads and displays the event item occurrences
        /// </summary>
        private void BindData()
        {
            var rockContext = new RockContext();
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Grab events
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                      .Where(m =>
                             m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == _calendarId) &&
                             m.EventItem.IsActive &&
                             m.EventItem.IsApproved);

            // Filter by campus
            var campusGuidList       = GetAttributeValue("Campuses").Split(',').AsGuidList();
            var campusIdList         = CampusCache.All().Where(c => campusGuidList.Contains(c.Guid)).Select(c => c.Id);
            var selectedCampusIdList = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            if (selectedCampusIdList.Any())
            {
                // No value gets them all, otherwise get the ones selected
                // Block level campus filtering has already been performed on cblCampus, so no need to do it again here
                // If CampusId is null, then the event is an 'All Campuses' event, so include those
                qry = qry.Where(c => !c.CampusId.HasValue || selectedCampusIdList.Contains(c.CampusId.Value));
            }
            else if (campusIdList.Any())
            {
                // If no campus filter is selected then check the block filtering
                // If CampusId is null, then the event is an 'All Campuses' event, so include those
                qry = qry.Where(c => !c.CampusId.HasValue || campusIdList.Contains(c.CampusId.Value));
            }

            // Filter by Category
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            if (categories.Any())
            {
                qry = qry.Where(i => i.EventItem.EventItemAudiences.Any(c => categories.Contains(c.DefinedValueId)));
            }

            // Get the beginning and end dates
            var today       = RockDateTime.Today;
            var filterStart = FilterStartDate.HasValue ? FilterStartDate.Value : today;
            var monthStart  = new DateTime(filterStart.Year, filterStart.Month, 1);
            var rangeStart  = monthStart.AddMonths(-1);
            var rangeEnd    = monthStart.AddMonths(2);
            var beginDate   = FilterStartDate.HasValue ? FilterStartDate.Value : rangeStart;
            var endDate     = FilterEndDate.HasValue ? FilterEndDate.Value : rangeEnd;

            endDate = endDate.AddDays(1).AddMilliseconds(-1);

            // Get the occurrences
            var occurrences          = qry.ToList();
            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o,
                Dates = o.GetStartTimes(beginDate, endDate).ToList()
            })
                                       .Where(d => d.Dates.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var datetime in occurrenceDates.Dates)
                {
                    if (eventItemOccurrence.Schedule.EffectiveEndDate.HasValue && (eventItemOccurrence.Schedule.EffectiveStartDate != eventItemOccurrence.Schedule.EffectiveEndDate))
                    {
                        var multiDate = eventItemOccurrence.Schedule.EffectiveStartDate;
                        while (multiDate.HasValue && (multiDate.Value < eventItemOccurrence.Schedule.EffectiveEndDate.Value))
                        {
                            CalendarEventDates.Add(multiDate.Value.Date);
                            multiDate = multiDate.Value.AddDays(1);
                        }
                    }
                    else
                    {
                        CalendarEventDates.Add(datetime.Date);
                    }

                    if (datetime >= beginDate && datetime < endDate)
                    {
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            Name                = eventItemOccurrence.EventItem.Name,
                            DateTime            = datetime,
                            Date                = datetime.ToShortDateString(),
                            Time                = datetime.ToShortTimeString(),
                            Campus              = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Location            = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            LocationDescription = eventItemOccurrence.Location,
                            Description         = eventItemOccurrence.EventItem.Description,
                            Summary             = eventItemOccurrence.EventItem.Summary,
                            OccurrenceNote      = eventItemOccurrence.Note.SanitizeHtml(),
                            DetailPage          = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        });
                    }
                }
            }

            var eventSummaries = eventOccurrenceSummaries
                                 .OrderBy(e => e.DateTime)
                                 .GroupBy(e => e.Name)
                                 .Select(e => e.ToList())
                                 .ToList();

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

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

            mergeFields.Add("TimeFrame", ViewMode);
            mergeFields.Add("StartDate", FilterStartDate);
            mergeFields.Add("EndDate", FilterEndDate);
            mergeFields.Add("DetailsPage", LinkedPageRoute("DetailsPage"));
            mergeFields.Add("EventItems", eventSummaries);
            mergeFields.Add("EventItemOccurrences", eventOccurrenceSummaries);
            mergeFields.Add("CurrentPerson", CurrentPerson);

            lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands"));
        }
        private void DisplayDetails()
        {
            int eventItemOccurrenceId = 0;
            RockContext rockContext = new RockContext();

            // get the calendarItem id
            if ( !string.IsNullOrWhiteSpace( PageParameter( "EventOccurrenceId" ) ) )
            {
                eventItemOccurrenceId = Convert.ToInt32( PageParameter( "EventOccurrenceId" ) );
            }
            if ( eventItemOccurrenceId > 0 )
            {
                var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );
                var qry = eventItemOccurrenceService
                    .Queryable( "EventItem, EventItem.Photo, Campus, Linkages" )
                    .Where( i => i.Id == eventItemOccurrenceId );

                var eventItemOccurrence = qry.FirstOrDefault();

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

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

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

                // determine if the registration is full
                var maxRegistrantCount = 0;
                var currentRegistrationCount = 0;
                var linkage = eventItemOccurrence.Linkages.FirstOrDefault();
                if (linkage != null )
                {
                    if (linkage.RegistrationInstance != null )
                    {
                        if ( linkage.RegistrationInstance.MaxAttendees != 0 )
                        {
                            maxRegistrantCount = linkage.RegistrationInstance.MaxAttendees;
                        }
                    }

                    if ( maxRegistrantCount != 0 )
                    {
                        currentRegistrationCount = new RegistrationRegistrantService( rockContext ).Queryable().AsNoTracking()
                                                        .Where( r =>
                                                            r.Registration.RegistrationInstanceId == linkage.RegistrationInstanceId
                                                            && r.OnWaitList == false )
                                                        .Count();
                    }
                }

                mergeFields.Add( "RegistrationStatusLabel", (maxRegistrantCount - currentRegistrationCount > 0) ? "Register" :  "Join Wait List");
                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 );
                }

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
            else
            {
                lOutput.Text = "<div class='alert alert-warning'>No event was available from the querystring.</div>";
            }
        }
示例#19
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext       = new RockContext();
            var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid();
            var eventCalendar     = new EventCalendarService(rockContext).Get(eventCalendarGuid);

            if (eventCalendar == null)
            {
                lMessages.Text = "<div class='alert alert-warning'>No event calendar is configured for this block.</div>";
                lContent.Text  = string.Empty;
                return;
            }
            else
            {
                lMessages.Text = string.Empty;
            }

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Grab events
            // NOTE: Do not use AsNoTracking() so that things can be lazy loaded if needed
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.EventItemAudiences,Schedule")
                      .Where(m =>
                             m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) &&
                             m.EventItem.IsActive);

            // Filter by campus (always include the "All Campuses" events)
            if (GetAttributeValue("UseCampusContext").AsBoolean())
            {
                var campusEntityType = EntityTypeCache.Get <Campus>();
                var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                if (contextCampus != null)
                {
                    qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                }
            }
            else
            {
                var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList();
                if (campusGuidList.Any())
                {
                    qry = qry.Where(e => !e.CampusId.HasValue || campusGuidList.Contains(e.Campus.Guid));
                }
            }

            // make sure they have a date range
            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(this.GetAttributeValue("DateRange"));
            var today     = RockDateTime.Today;

            dateRange.Start = dateRange.Start ?? today;
            if (dateRange.End == null)
            {
                dateRange.End = dateRange.Start.Value.AddDays(1000);
            }

            // Get the occurrences
            var occurrences          = qry.ToList();
            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o,
                Dates = o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).ToList()
            })
                                       .Where(d => d.Dates.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var datetime in occurrenceDates.Dates)
                {
                    CalendarEventDates.Add(datetime.Date);

                    if (datetime >= dateRange.Start.Value && datetime < dateRange.End.Value)
                    {
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            EventItem           = eventItemOccurrence.EventItem,
                            Name        = eventItemOccurrence.EventItem.Name,
                            DateTime    = datetime,
                            Date        = datetime.ToShortDateString(),
                            Time        = datetime.ToShortTimeString(),
                            Location    = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Description = eventItemOccurrence.EventItem.Description,
                            Summary     = eventItemOccurrence.EventItem.Summary,
                            DetailPage  = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        });
                    }
                }
            }

            eventOccurrenceSummaries = eventOccurrenceSummaries
                                       .OrderBy(e => e.DateTime)
                                       .ThenBy(e => e.Name)
                                       .ToList();

            // limit results
            int?maxItems = GetAttributeValue("MaxOccurrences").AsIntegerOrNull();

            if (maxItems.HasValue)
            {
                eventOccurrenceSummaries = eventOccurrenceSummaries.Take(maxItems.Value).ToList();
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("DetailsPage", LinkedPageRoute("DetailsPage"));
            mergeFields.Add("EventOccurrenceSummaries", eventOccurrenceSummaries);

            lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
示例#20
0
        private string GetContent()
        {
            Guid        eventItemOccurrenceGuid = Guid.Empty;
            RockContext rockContext             = new RockContext();

            // get the calendarItem id
            if (!string.IsNullOrWhiteSpace(RequestContext.GetPageParameter("EventOccurrenceGuid")))
            {
                eventItemOccurrenceGuid = RequestContext.GetPageParameter("EventOccurrenceGuid").AsGuid();
            }

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
            var qry = eventItemOccurrenceService
                      .Queryable("EventItem, EventItem.Photo, Campus, Linkages")
                      .Where(i => i.Guid == eventItemOccurrenceGuid);

            var eventItemOccurrence = qry.FirstOrDefault();

            if (eventItemOccurrence == null)
            {
                return("<Rock:NotificationBox NotificationType=\"Warning\" Text=\"We could not find that event.\" />");
            }

            var mergeFields = new Dictionary <string, object>
            {
                { "RegistrationUrl", RegistrationUrl },
                { "EventItemOccurrence", eventItemOccurrence },
                { "Event", eventItemOccurrence?.EventItem },
                { "CurrentPerson", RequestContext.CurrentPerson }
            };

            //var campusEntityType = EntityTypeCache.Get( "Rock.Model.Campus" );
            var contextCampus = RequestContext.GetContextEntity <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>();

            foreach (var registrationInstance in eventItemOccurrence.Linkages.Select(a => a.RegistrationInstance).Distinct().ToList())
            {
                int?maxRegistrantCount       = null;
                var currentRegistrationCount = 0;

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


                int?registrationSpotsAvailable = null;
                if (maxRegistrantCount.HasValue)
                {
                    currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable()
                                               .AsNoTracking()
                                               .Where(r => r.Registration.RegistrationInstanceId == registrationInstance.Id && r.OnWaitList == false)
                                               .Count();
                    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);

            return(Template.ResolveMergeFields(mergeFields));
        }