Esempio n. 1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EventItemPicker" /> class.
        /// </summary>
        public EventItemOccurrencePicker()
        {
            Items.Clear();
            Items.Add(new ListItem());

            using (var rockContext = new RockContext())
            {
                var calendarItemOccurrences = new EventItemOccurrenceService(rockContext).Queryable()
                                              .Where(i => i.EventItem.IsActive)
                                              .ToList()
                                              .Where(i => i.NextStartDateTime > DateTime.Now)
                                              .Select(i => new
                {
                    Event = i.EventItem.Name,
                    Id    = i.EventItem.Id,
                    Name  = "[" + i.Id + "] " + i.NextStartDateTime
                })
                                              .OrderBy(i => i.Event)
                                              .ToList();

                foreach (var calendarItemOccurrence in calendarItemOccurrences)
                {
                    ListItem listItem = new ListItem(calendarItemOccurrence.Name, calendarItemOccurrence.Id.ToString());
                    listItem.Attributes["OptionGroup"] = calendarItemOccurrence.Event;
                    Items.Add(listItem);
                }
            }
        }
Esempio n. 2
0
        private EventItemOccurrence EventItemOccurrenceAddOrUpdateInstance(RockContext rockContext, Guid scheduleGuid, bool deleteExistingInstance)
        {
            // Get existing schedules.
            var scheduleService = new ScheduleService(rockContext);
            var schedule        = scheduleService.Get(scheduleGuid);

            // Get Event "Rock Solid Finances".
            var eventItemService           = new EventItemService(rockContext);
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

            var financeEvent = eventItemService.Get(EventFinancesClassGuid.AsGuid());

            // Add a new occurrence of this event.
            var financeEvent1 = eventItemOccurrenceService.Get(FinancesClassOccurrenceTestGuid.AsGuid());

            if (financeEvent1 != null && deleteExistingInstance)
            {
                eventItemOccurrenceService.Delete(financeEvent1);
                rockContext.SaveChanges();
            }
            financeEvent1 = new EventItemOccurrence();

            var mainCampusId = CampusCache.GetId(MainCampusGuidString.AsGuid());

            financeEvent1.Location   = "Meeting Room 1";
            financeEvent1.ForeignKey = TestDataForeignKey;
            financeEvent1.ScheduleId = schedule.Id;
            financeEvent1.Guid       = FinancesClassOccurrenceTestGuid.AsGuid();
            financeEvent1.CampusId   = mainCampusId;

            financeEvent.EventItemOccurrences.Add(financeEvent1);

            return(financeEvent1);
        }
        private void RunRockCleanupTaskUpdateEventNextOccurrenceDatesAndVerify(DateTime referenceDate)
        {
            // Execute the process to update the Event Occurrence next dates.
            var rockContext = new RockContext();

            Rock.Jobs.RockCleanup.UpdateEventNextOccurrenceDates(rockContext, referenceDate);

            // Verify the results of the cleanup.
            rockContext = new RockContext();

            var eventOccurrenceService = new EventItemOccurrenceService(rockContext);

            // Event 1.1 should be updated to the next occurrence after the reference date.
            var event11 = eventOccurrenceService.Get(testEventOccurrence11Guid);

            Assert.AreEqual(event11.NextStartDateTime, event11.Schedule.GetNextStartDateTime(referenceDate));

            // Event 1.2 should be updated to the next occurrence after the reference date.
            var event12 = eventOccurrenceService.Get(testEventOccurrence12Guid);

            Assert.AreEqual(event12.NextStartDateTime, event12.Schedule.GetNextStartDateTime(referenceDate));

            // Event 1.3 should be set to null because the schedule is inactive.
            var event13 = eventOccurrenceService.Get(testEventOccurrence13Guid);

            Assert.IsNull(event13.NextStartDateTime);

            // Event 2.1 should be set to null because the Event is inactive.
            var event21 = eventOccurrenceService.Get(testEventOccurrence21Guid);

            Assert.IsNull(event21.NextStartDateTime);
        }
Esempio n. 4
0
        /// <summary>
        /// Handles the Click event of the btnEdit 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 btnEdit_Click(object sender, EventArgs e)
        {
            var rockContext         = new RockContext();
            var eventItemOccurrence = new EventItemOccurrenceService(rockContext).Get(hfEventItemOccurrenceId.Value.AsInteger());

            ShowEditDetails(eventItemOccurrence);
        }
        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);
        }
Esempio n. 6
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>";
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Shows the results.
        /// </summary>
        private void ShowResults()
        {
            RockContext rockContext = new RockContext();

            var qry = new EventItemOccurrenceService(rockContext).Queryable().Where(e => e.EventItem.IsActive);

            int?eventCalendarId = this.PageParameter("EventCalendarId").AsIntegerOrNull();

            if (eventCalendarId.HasValue)
            {
                qry = qry.Where(e => e.EventItem.EventCalendarItems.Any(x => x.EventCalendarId == eventCalendarId));
            }

            // filter by Campus (filter)
            if (cpCampusPicker.SelectedCampusId.HasValue)
            {
                int campusId = cpCampusPicker.SelectedCampusId.Value;

                // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                qry = qry.Where(a => a.CampusId == null || a.CampusId == campusId);
            }

            // retrieve occurrences into a List so we can do additional filtering against the Calendar data
            List <EventItemOccurrence> itemOccurrences = qry.ToList();

            // filter by date range
            var dateRange = new DateRange(pDateRange.LowerValue, pDateRange.UpperValue);

            if (dateRange.Start != null && dateRange.End != null)
            {
                itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0);
            }
            else
            {
                // default show all future
                itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, DateTime.Now.AddDays(365)).Count() == 0);
            }

            // sort results
            itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).ToList();

            // make lava merge fields
            var mergeFields = new Dictionary <string, object>();

            mergeFields.Add("EventDetailPage", LinkedPageRoute("EventDetailPage"));

            mergeFields.Add("EventItemOccurrences", itemOccurrences);

            if (eventCalendarId.HasValue)
            {
                mergeFields.Add("EventCalendar", new EventCalendarService(rockContext).Get(eventCalendarId.Value));
            }

            lResults.Text = GetAttributeValue("ResultsLavaTemplate").ResolveMergeFields(mergeFields);
        }
Esempio n. 8
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        public void ShowDetail(int eventItemOccurrenceId)
        {
            pnlDetails.Visible = true;

            EventItemOccurrence eventItemOccurrence = null;

            var rockContext = new RockContext();

            if (!eventItemOccurrenceId.Equals(0))
            {
                eventItemOccurrence = new EventItemOccurrenceService(rockContext).Get(eventItemOccurrenceId);
            }

            if (eventItemOccurrence == null)
            {
                eventItemOccurrence = new EventItemOccurrence {
                    Id = 0
                };
            }

            bool canEdit  = UserCanEdit || eventItemOccurrence.IsAuthorized(Authorization.EDIT, CurrentPerson);
            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;

            if (!canEdit)
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(EventItemOccurrence.FriendlyTypeName);
            }

            if (readOnly)
            {
                btnEdit.Visible   = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails(eventItemOccurrence);
            }
            else
            {
                btnEdit.Visible   = true;
                btnDelete.Visible = true;

                if (!eventItemOccurrenceId.Equals(0))
                {
                    ShowReadonlyDetails(eventItemOccurrence);
                }
                else
                {
                    ShowEditDetails(eventItemOccurrence);
                }
            }
        }
        /// <summary>
        /// Gets the occurrences that should be displayed.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns>
        /// An enumerable of <see cref="EventItemOccurrence" /> items to be displayed.
        /// </returns>
        private IEnumerable <EventItemOccurrence> GetOccurrences(RockContext rockContext)
        {
            if (!Audience.HasValue)
            {
                return(null);
            }

            // get event occurrences
            var qry = new EventItemOccurrenceService(rockContext).Queryable()
                      .Where(e => e.EventItem.EventItemAudiences.Any(a => a.DefinedValue.Guid == Audience.Value) && e.EventItem.IsActive);

            // filter by campus
            var campusIds = GetFilteredCampuses().Select(a => a.Id).ToList();

            if (campusIds.Any())
            {
                // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                qry = qry.Where(e => !e.CampusId.HasValue || campusIds.Contains(e.CampusId.Value));
            }

            // filter by calendar
            if (Calendar.HasValue)
            {
                qry = qry.Where(e => e.EventItem.EventCalendarItems.Any(c => c.EventCalendar.Guid == Calendar));
            }

            // retrieve occurrences
            var itemOccurrences = qry.ToList();

            // filter by date range
            var dateRange = DateRange;

            if (dateRange.Start != null && dateRange.End != null)
            {
                itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0);
            }
            else
            {
                // default show all future
                itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddDays(365)).Count() == 0);
            }

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

            itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList();

            return(itemOccurrences);
        }
Esempio n. 10
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        public void ShowDetail( int eventItemOccurrenceId )
        {
            pnlDetails.Visible = true;

            EventItemOccurrence eventItemOccurrence = null;

            var rockContext = new RockContext();

            if ( !eventItemOccurrenceId.Equals( 0 ) )
            {
                eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( eventItemOccurrenceId );
            }

            if ( eventItemOccurrence == null )
            {
                eventItemOccurrence = new EventItemOccurrence { Id = 0 };
            }

            bool canEdit  = UserCanEdit || eventItemOccurrence.IsAuthorized( Authorization.EDIT, CurrentPerson );
            bool readOnly = false;
            nbEditModeMessage.Text = string.Empty;

            if ( !canEdit )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( EventItemOccurrence.FriendlyTypeName );
            }

            if ( readOnly )
            {
                btnEdit.Visible = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails( eventItemOccurrence );
            }
            else
            {
                btnEdit.Visible = true;
                btnDelete.Visible = true;

                if ( !eventItemOccurrenceId.Equals( 0))
                {
                    ShowReadonlyDetails( eventItemOccurrence );
                }
                else
                {
                    ShowEditDetails( eventItemOccurrence );
                }
            }
        }
        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);
        }
 /// <summary>
 /// Handles the RowSelected event of the gCalendarItemOccurrenceList control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
 protected void gCalendarItemOccurrenceList_RowSelected(object sender, RowEventArgs e)
 {
     using (RockContext rockContext = new RockContext())
     {
         EventItemOccurrenceService eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
         EventItemOccurrence        eventItemOccurrence        = eventItemOccurrenceService.Get(e.RowKeyId);
         if (eventItemOccurrence != null)
         {
             var qryParams = new Dictionary <string, string>();
             qryParams.Add("EventCalendarId", PageParameter("EventCalendarId"));
             qryParams.Add("EventItemId", _eventItem.Id.ToString());
             qryParams.Add("EventItemOccurrenceId", eventItemOccurrence.Id.ToString());
             NavigateToLinkedPage("DetailPage", qryParams);
         }
     }
 }
 /// <summary>
 /// Handles the Copy event of the gCalendarItemOccurrenceList control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
 protected void gCalendarItemOccurrenceList_Copy( object sender, RowEventArgs e )
 {
     using ( RockContext rockContext = new RockContext() )
     {
         EventItemOccurrenceService eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );
         EventItemOccurrence eventItemOccurrence = eventItemOccurrenceService.Get( e.RowKeyId );
         if ( eventItemOccurrence != null )
         {
             var qryParams = new Dictionary<string, string>();
             qryParams.Add( "EventCalendarId", PageParameter( "EventCalendarId" ) );
             qryParams.Add( "EventItemId", _eventItem.Id.ToString() );
             qryParams.Add( "EventItemOccurrenceId", "0" );
             qryParams.Add( "CopyFromId", eventItemOccurrence.Id.ToString() );
             NavigateToLinkedPage( "DetailPage", qryParams );
         }
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Handles the Click event of the btnCancel 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 btnCancel_Click(object sender, EventArgs e)
        {
            int eventItemId = hfEventItemOccurrenceId.ValueAsInt();

            if (eventItemId == 0)
            {
                var qryParams = new Dictionary <string, string>();
                qryParams.Add("EventCalendarId", PageParameter("EventCalendarId"));
                qryParams.Add("EventItemId", PageParameter("EventItemId"));
                NavigateToParentPage(qryParams);
            }
            else
            {
                var eventItemOccurrence = new EventItemOccurrenceService(new RockContext()).Get(eventItemId);
                ShowReadonlyDetails(eventItemOccurrence);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var rockContext = new RockContext();

                OccurrenceId    = PageParameter("EventItemOccurrenceId").AsIntegerOrNull();
                ContentChannels = new List <ContentChannel>();
                ExpandedPanels  = new List <int>();

                if (OccurrenceId.HasValue && OccurrenceId.Value != 0)
                {
                    var channels = new Dictionary <int, ContentChannel>();

                    var eventItemOccurrence = new EventItemOccurrenceService(rockContext).Get(OccurrenceId.Value);
                    if (eventItemOccurrence != null && eventItemOccurrence.EventItem != null && eventItemOccurrence.EventItem.EventCalendarItems != null)
                    {
                        eventItemOccurrence.EventItem.EventCalendarItems
                        .SelectMany(i => i.EventCalendar.ContentChannels)
                        .Select(c => c.ContentChannel)
                        .ToList()
                        .ForEach(c => channels.AddOrIgnore(c.Id, c));

                        ExpandedPanels = eventItemOccurrence.ContentChannelItems
                                         .Where(i => i.ContentChannelItem != null)
                                         .Select(i => i.ContentChannelItem.ContentChannelId)
                                         .Distinct()
                                         .ToList();
                    }

                    foreach (var channel in channels)
                    {
                        if (channel.Value.IsAuthorized(Authorization.VIEW, CurrentPerson))
                        {
                            ContentChannels.Add(channel.Value);
                        }
                    }
                }

                CreateGrids(rockContext);
                BindGrids();
            }

            base.OnLoad(e);
        }
Esempio n. 16
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? eventCampusId = PageParameter( pageReference, "EventOccurrenceId" ).AsIntegerOrNull();
            if ( eventCampusId != null )
            {
                EventItemOccurrence eventItemOccurrence = new EventItemOccurrenceService( new RockContext() ).Get( eventCampusId.Value );
                if ( eventItemOccurrence != null )
                {
                    breadCrumbs.Add( new BreadCrumb( eventItemOccurrence.EventItem.Name, pageReference ) );
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? eventCampusId = PageParameter( pageReference, "EventOccurrenceId" ).AsIntegerOrNull();
            if ( eventCampusId != null )
            {
                EventItemOccurrence eventItemOccurrence = new EventItemOccurrenceService( new RockContext() ).Get( eventCampusId.Value );
                if ( eventItemOccurrence != null )
                {
                    breadCrumbs.Add( new BreadCrumb( eventItemOccurrence.EventItem.Name, pageReference ) );
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
        /// <summary>
        /// Handles the Delete event of the gCalendarItemOccurrenceList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gCalendarItemOccurrenceList_Delete(object sender, RowEventArgs e)
        {
            using (RockContext rockContext = new RockContext())
            {
                EventItemOccurrenceService eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
                EventItemOccurrence        eventItemOccurrence        = eventItemOccurrenceService.Get(e.RowKeyId);
                if (eventItemOccurrence != null)
                {
                    string errorMessage;
                    if (!eventItemOccurrenceService.CanDelete(eventItemOccurrence, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    eventItemOccurrenceService.Delete(eventItemOccurrence);
                    rockContext.SaveChanges();
                }
            }

            BindCampusGrid();
        }
        /// <summary>
        /// Handles the SaveClick event of the dlgAddCalendarItemPage3 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 dlgAddCalendarItemPage3_SaveClick(object sender, EventArgs e)
        {
            // Save selection to hidden field
            using (var rockContext = new RockContext())
            {
                int?eventItemOccurrenceId = ddlCalendarItemOccurrence.SelectedValueAsInt();
                if (eventItemOccurrenceId.HasValue)
                {
                    var eventItemOccurrence = new EventItemOccurrenceService(rockContext)
                                              .Queryable("EventItem,Campus").AsNoTracking()
                                              .Where(c => c.Id == eventItemOccurrenceId.Value)
                                              .FirstOrDefault();
                    if (eventItemOccurrence != null)
                    {
                        hfLinkageEventItemOccurrenceId.Value       = eventItemOccurrence.Id.ToString();
                        lLinkageEventItemOccurrence.Text           = eventItemOccurrence.ToString();
                        lbLinkageEventItemOccurrenceAdd.Visible    = false;
                        lbLinkageEventItemOccurrenceRemove.Visible = true;
                    }
                }
            }

            HideDialog();
        }
Esempio n. 20
0
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDelete_Click(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                EventItemOccurrenceService eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
                EventItemOccurrence        eventItemOccurrence        = eventItemOccurrenceService.Get(hfEventItemOccurrenceId.Value.AsInteger());

                if (eventItemOccurrence != null)
                {
                    string errorMessage;
                    if (!eventItemOccurrenceService.CanDelete(eventItemOccurrence, out errorMessage))
                    {
                        mdDeleteWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    eventItemOccurrenceService.Delete(eventItemOccurrence);

                    rockContext.SaveChanges();
                }
            }

            NavigateToParentPage();
        }
        private void LoadContent()
        {
            var audienceGuid = GetAttributeValue("Audience").AsGuid();

            if (audienceGuid != Guid.Empty)
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService(rockContext).Queryable()
                          .Where(e => e.EventItem.EventItemAudiences.Any(a => a.DefinedValue.Guid == audienceGuid) && e.EventItem.IsActive);

                // filter occurrences for campus (always include the "All Campuses" events)
                if (GetAttributeValue("UseCampusContext").AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses")))
                    {
                        var selectedCampusGuids = GetAttributeValue("Campuses").Split(',').AsGuidList();
                        var selectedCampusIds   = selectedCampusGuids.Select(a => CampusCache.Read(a)).Where(a => a != null).Select(a => a.Id);

                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == null || selectedCampusIds.Contains(e.CampusId.Value));
                    }
                }

                // filter by calendar
                var calendarGuid = GetAttributeValue("Calendar").AsGuid();

                if (calendarGuid != Guid.Empty)
                {
                    qry = qry.Where(e => e.EventItem.EventCalendarItems.Any(c => c.EventCalendar.Guid == calendarGuid));
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange"));
                if (dateRange.Start != null && dateRange.End != null)
                {
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0);
                }
                else
                {
                    // default show all future
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, DateTime.Now.AddDays(365)).Count() == 0);
                }

                // limit results
                int maxItems = GetAttributeValue("MaxOccurrences").AsInteger();
                itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList();

                // make lava merge fields
                var mergeFields = new Dictionary <string, object>();

                var contextObjects = new Dictionary <string, object>();
                foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                {
                    var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                    if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                    {
                        var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                        if (type != null)
                        {
                            contextObjects.Add(type.Name, contextEntity);
                        }
                    }
                }

                if (contextObjects.Any())
                {
                    mergeFields.Add("Context", contextObjects);
                }

                mergeFields.Add("ListTitle", GetAttributeValue("ListTitle"));
                mergeFields.Add("EventDetailPage", LinkedPageRoute("EventDetailPage"));
                mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));
                mergeFields.Add("EventItemOccurrences", itemOccurrences);

                lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No audience is configured for this block.</div>";
            }
        }
        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>";
            }
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        public void ShowDetail( int eventItemOccurrenceId )
        {
            pnlDetails.Visible = true;

            EventItemOccurrence eventItemOccurrence = null;

            var rockContext = new RockContext();

            bool canEdit = UserCanEdit;

            if ( !eventItemOccurrenceId.Equals( 0 ) )
            {
                eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( eventItemOccurrenceId );
                pdAuditDetails.SetEntity( eventItemOccurrence, ResolveRockUrl( "~" ) );
            }

            if ( eventItemOccurrence == null )
            {
                eventItemOccurrence = new EventItemOccurrence { Id = 0 };
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            if ( !canEdit )
            {
                int? calendarId = PageParameter( "EventCalendarId" ).AsIntegerOrNull();
                if ( calendarId.HasValue )
                {
                    var calendar = new EventCalendarService( rockContext ).Get( calendarId.Value );
                    if ( calendar != null )
                    {
                        canEdit = calendar.IsAuthorized( Authorization.EDIT, CurrentPerson );
                    }
                }
            }

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;

            if ( !canEdit )
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed( EventItemOccurrence.FriendlyTypeName );
            }

            if ( readOnly )
            {
                btnEdit.Visible = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails( eventItemOccurrence );
            }
            else
            {
                btnEdit.Visible = true;
                btnDelete.Visible = true;

                if ( !eventItemOccurrenceId.Equals( 0))
                {
                    ShowReadonlyDetails( eventItemOccurrence );
                }
                else
                {
                    ShowEditDetails( eventItemOccurrence );
                }
            }
        }
Esempio n. 24
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"));
        }
Esempio n. 25
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")));
            }
        }
        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>";
            }
        }
        private void LoadContent()
        {
            var eventItemGuid = GetAttributeValue( "EventItem" ).AsGuid();

            if ( eventItemGuid != Guid.Empty )
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService( rockContext ).Queryable()
                                            .Where( e => e.EventItem.Guid == eventItemGuid );

                // filter occurrences for campus
                if ( GetAttributeValue( "UseCampusContext" ).AsBoolean() )
                {
                    var campusEntityType = EntityTypeCache.Read( "Rock.Model.Campus" );
                    var contextCampus = RockPage.GetCurrentContext( campusEntityType ) as Campus;

                    if ( contextCampus != null )
                    {
                        qry = qry.Where( e => e.CampusId == contextCampus.Id );
                    }
                }
                else
                {
                    if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "Campuses" ) ) )
                    {
                        var selectedCampuses = Array.ConvertAll( GetAttributeValue( "Campuses" ).Split( ',' ), s => new Guid( s ) ).ToList();
                        qry = qry.Where( e => selectedCampuses.Contains( e.Campus.Guid ) );
                    }
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( GetAttributeValue( "DateRange" ) );
                if ( dateRange.Start != null && dateRange.End != null )
                {
                    itemOccurrences.RemoveAll( o => o.GetStartTimes( dateRange.Start.Value, dateRange.End.Value ).Count() == 0 );
                }
                else
                {
                    // default show all future (max 1 year)
                    itemOccurrences.RemoveAll( o => o.GetStartTimes( RockDateTime.Now, RockDateTime.Now.AddDays(365) ).Count() == 0 );
                }

                // limit results
                int maxItems = GetAttributeValue( "MaxOccurrences" ).AsInteger();
                itemOccurrences = itemOccurrences.OrderBy( i => i.NextStartDateTime ).Take( maxItems ).ToList();

                // load event item
                var eventItem = new EventItemService( rockContext ).Get( eventItemGuid );

                // make lava merge fields
                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "RegistrationPage", LinkedPageUrl( "RegistrationPage", null ) );
                mergeFields.Add( "EventItem", eventItem);
                mergeFields.Add( "EventItemOccurrences", itemOccurrences );

                // add context to merge fields
                var contextEntityTypes = RockPage.GetContextEntityTypes();

                var contextObjects = new Dictionary<string, object>();
                foreach (var conextEntityType in contextEntityTypes)
                {
                    var contextObject = RockPage.GetCurrentContext(conextEntityType);
                    contextObjects.Add(conextEntityType.FriendlyName, contextObject);
                }

                mergeFields.Add("Context", contextObjects);

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

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = @"<div class='alert alert-info'>Due to the size of the lava members the debug info for this block has been supressed. Below are high-level details of
                                    the merge objects available.
                                    <ul>
                                        <li>EventItemOccurrences - A list of EventItemOccurrences. View the EvenItemOccurrence model for these properties.</li>
                                        <li>EventItem - The EventItem that was selected. View the EvenItem model for these properties.</li>
                                        <li>RegistrationPage  - String that contains the relative path to the registration page.</li>
                                        <li>Global Attribute  - Access to the Global Attributes.</li>
                                    </ul>
                                    </div>";
                }
                else
                {
                    lDebug.Visible = false;
                    lDebug.Text = string.Empty;
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No event item is configured for this block.</div>";
            }
        }
        private void ShowEditDetails( EventItemOccurrence eventItemOccurrence )
        {
            LinkageState = new EventItemOccurrenceGroupMap { Guid = Guid.Empty };

            if ( eventItemOccurrence == null )
            {
                eventItemOccurrence = new EventItemOccurrence();
            }

            if ( eventItemOccurrence.Id == 0 )
            {
                lActionTitle.Text = ActionTitle.Add( "Event Occurrence" ).FormatAsHtmlTitle();

                var copyFromOccurrenceId = PageParameter( "CopyFromId" ).AsInteger();
                if ( copyFromOccurrenceId > 0 )
                {
                    var oldOccurrence = new EventItemOccurrenceService( new RockContext() ).Get( copyFromOccurrenceId );
                    if ( oldOccurrence != null )
                    {
                        // clone the workflow type
                        eventItemOccurrence = oldOccurrence.Clone( false );
                        eventItemOccurrence.Schedule = oldOccurrence.Schedule;
                        eventItemOccurrence.EventItem = oldOccurrence.EventItem;
                        eventItemOccurrence.ContactPersonAlias = oldOccurrence.ContactPersonAlias;
                        eventItemOccurrence.CreatedByPersonAlias = null;
                        eventItemOccurrence.CreatedByPersonAliasId = null;
                        eventItemOccurrence.CreatedDateTime = RockDateTime.Now;
                        eventItemOccurrence.ModifiedByPersonAlias = null;
                        eventItemOccurrence.ModifiedByPersonAliasId = null;
                        eventItemOccurrence.ModifiedDateTime = RockDateTime.Now;
                        eventItemOccurrence.Id = 0;
                        eventItemOccurrence.Guid = Guid.NewGuid();

                        // Clone the linkage
                        var linkage = oldOccurrence.Linkages.FirstOrDefault();
                        if ( linkage != null )
                        {
                            LinkageState = linkage.Clone( false );
                            LinkageState.EventItemOccurrenceId = 0;
                            LinkageState.CreatedByPersonAlias = null;
                            LinkageState.CreatedByPersonAliasId = null;
                            LinkageState.CreatedDateTime = RockDateTime.Now;
                            LinkageState.ModifiedByPersonAlias = null;
                            LinkageState.ModifiedByPersonAliasId = null;
                            LinkageState.ModifiedDateTime = RockDateTime.Now;
                            LinkageState.Id = 0;
                            LinkageState.Guid = Guid.NewGuid();
                            LinkageState.RegistrationInstance = linkage.RegistrationInstance != null ? linkage.RegistrationInstance.Clone( false ) : new RegistrationInstance();
                            LinkageState.RegistrationInstance.RegistrationTemplate =
                                linkage.RegistrationInstance != null && linkage.RegistrationInstance.RegistrationTemplate != null ?
                                linkage.RegistrationInstance.RegistrationTemplate.Clone( false ) : new RegistrationTemplate();
                            LinkageState.Group = linkage.Group != null ? linkage.Group.Clone( false ) : new Group();
                        }
                    }
                }
            }
            else
            {
                lActionTitle.Text = ActionTitle.Edit( "Event Occurrence" ).FormatAsHtmlTitle();

                var registration = eventItemOccurrence.Linkages.FirstOrDefault();
                if ( registration != null )
                {
                    LinkageState = registration.Clone( false );
                    LinkageState.RegistrationInstance = registration.RegistrationInstance != null ? registration.RegistrationInstance.Clone( false ) : new RegistrationInstance();
                    LinkageState.RegistrationInstance.RegistrationTemplate =
                        registration.RegistrationInstance != null && registration.RegistrationInstance.RegistrationTemplate != null ?
                        registration.RegistrationInstance.RegistrationTemplate.Clone( false ) : new RegistrationTemplate();
                    LinkageState.Group = registration.Group != null ? registration.Group.Clone( false ) : new Group();
                }
            }

            SetEditMode( true );

            hfEventItemOccurrenceId.Value = eventItemOccurrence.Id.ToString();

            ddlCampus.SetValue( eventItemOccurrence.CampusId ?? -1 );
            tbLocation.Text = eventItemOccurrence.Location;

            if ( eventItemOccurrence.Schedule != null )
            {
                sbSchedule.iCalendarContent = eventItemOccurrence.Schedule.iCalendarContent;
                lScheduleText.Text = eventItemOccurrence.Schedule.FriendlyScheduleText;
            }
            else
            {
                sbSchedule.iCalendarContent = string.Empty;
                lScheduleText.Text = string.Empty;
            }

            ppContact.SetValue( eventItemOccurrence.ContactPersonAlias != null ? eventItemOccurrence.ContactPersonAlias.Person : null );
            pnPhone.Text = eventItemOccurrence.ContactPhone;
            tbEmail.Text = eventItemOccurrence.ContactEmail;

            htmlOccurrenceNote.Text = eventItemOccurrence.Note;

            DisplayRegistration();
        }
Esempio n. 29
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>
        /// Handles the Delete event of the gCalendarItemOccurrenceList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gCalendarItemOccurrenceList_Delete( object sender, RowEventArgs e )
        {
            using ( RockContext rockContext = new RockContext() )
            {
                EventItemOccurrenceService eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );
                EventItemOccurrence eventItemOccurrence = eventItemOccurrenceService.Get( e.RowKeyId );
                if ( eventItemOccurrence != null )
                {
                    string errorMessage;
                    if ( !eventItemOccurrenceService.CanDelete( eventItemOccurrence, out errorMessage ) )
                    {
                        mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    eventItemOccurrenceService.Delete( eventItemOccurrence );
                    rockContext.SaveChanges();
                }
            }

            BindCampusGrid();
        }
Esempio n. 31
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            if ( !Page.IsPostBack )
            {
                var rockContext = new RockContext();

                OccurrenceId = PageParameter( "EventItemOccurrenceId" ).AsIntegerOrNull();
                ContentChannels = new List<ContentChannel>();
                ExpandedPanels = new List<int>();

                if ( OccurrenceId.HasValue && OccurrenceId.Value != 0 )
                {
                    var channels = new Dictionary<int, ContentChannel>();

                    var eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( OccurrenceId.Value );
                    if ( eventItemOccurrence != null && eventItemOccurrence.EventItem != null && eventItemOccurrence.EventItem.EventCalendarItems != null )
                    {
                        eventItemOccurrence.EventItem.EventCalendarItems
                            .SelectMany( i => i.EventCalendar.ContentChannels )
                            .Select( c => c.ContentChannel )
                            .ToList()
                            .ForEach( c => channels.AddOrIgnore( c.Id, c ) );

                        ExpandedPanels = eventItemOccurrence.ContentChannelItems
                            .Where( i => i.ContentChannelItem != null )
                            .Select( i => i.ContentChannelItem.ContentChannelId )
                            .Distinct()
                            .ToList();
                    }

                    ContentChannels = channels.Select( c => c.Value ).ToList();
                }

                CreateGrids( rockContext );
                BindGrids();
            }

            base.OnLoad( e );
        }
        /// <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);
        }
Esempio n. 33
0
        /// <summary>
        /// Sets the registration state
        /// </summary>
        private bool SetRegistrationState()
        {
            string registrationSlug = PageParameter( SLUG_PARAM_NAME );
            int? registrationInstanceId = PageParameter( REGISTRATION_INSTANCE_ID_PARAM_NAME ).AsIntegerOrNull();
            int? registrationId = PageParameter( REGISTRATION_ID_PARAM_NAME ).AsIntegerOrNull();
            int? groupId = PageParameter( GROUP_ID_PARAM_NAME ).AsIntegerOrNull();
            int? campusId = PageParameter( CAMPUS_ID_PARAM_NAME ).AsIntegerOrNull();
            int? eventOccurrenceId = PageParameter( EVENT_OCCURRENCE_ID_PARAM_NAME ).AsIntegerOrNull();

            // Not inside a "using" due to serialization needing context to still be active
            var rockContext = new RockContext();

            // An existing registration id was specified
            if ( registrationId.HasValue )
            {
                var registrationService = new RegistrationService( rockContext );
                var registration = registrationService
                    .Queryable( "Registrants.PersonAlias.Person,Registrants.GroupMember,RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" )
                    .Where( r => r.Id == registrationId.Value )
                    .FirstOrDefault();

                if ( registration == null )
                {
                    ShowError( "Error", "Registration not found" );
                    return false;
                }

                if ( CurrentPersonId == null )
                {
                    ShowWarning( "Please log in", "You must be logged in to access this registration." );
                    return false;
                }

                // Only allow the person that was logged in when this registration was created.
                // If the logged in person, registered on someone elses behalf (for example, husband logged in, but entered wife's name as the Registrar),
                // also allow that person to access the regisratiuon
                if ( ( registration.PersonAlias != null && registration.PersonAlias.PersonId == CurrentPersonId.Value ) ||
                    ( registration.CreatedByPersonAlias != null && registration.CreatedByPersonAlias.PersonId == CurrentPersonId.Value ) )
                {
                    RegistrationInstanceState = registration.RegistrationInstance;
                    RegistrationState = new RegistrationInfo( registration, rockContext );
                    RegistrationState.PreviousPaymentTotal = registrationService.GetTotalPayments( registration.Id );
                }
                else
                {
                    ShowWarning( "Sorry", "You are not allowed to view or edit the selected registration since you are not the one who created the registration." );
                    return false;
                }

                // set the max number of steps in the progress bar
                numHowMany.Value = registration.Registrants.Count();
                this.ProgressBarSteps = numHowMany.Value * FormCount + 2;

                // set group id
                if ( groupId.HasValue )
                {
                    GroupId = groupId;
                }
                else if ( !string.IsNullOrWhiteSpace( registrationSlug ) )
                {
                    var dateTime = RockDateTime.Now;
                    var linkage = new EventItemOccurrenceGroupMapService( rockContext )
                        .Queryable().AsNoTracking()
                        .Where( l =>
                            l.UrlSlug == registrationSlug &&
                            l.RegistrationInstance != null &&
                            l.RegistrationInstance.IsActive &&
                            l.RegistrationInstance.RegistrationTemplate != null &&
                            l.RegistrationInstance.RegistrationTemplate.IsActive &&
                            ( !l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) &&
                            ( !l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) )
                        .FirstOrDefault();
                    if ( linkage != null )
                    {
                        GroupId = linkage.GroupId;
                    }
                }
            }

            // A registration slug was specified
            if ( RegistrationState == null && !string.IsNullOrWhiteSpace( registrationSlug ) )
            {
                var dateTime = RockDateTime.Now;
                var linkage = new EventItemOccurrenceGroupMapService( rockContext )
                    .Queryable( "RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" )
                    .Where( l =>
                        l.UrlSlug == registrationSlug &&
                        l.RegistrationInstance != null &&
                        l.RegistrationInstance.IsActive &&
                        l.RegistrationInstance.RegistrationTemplate != null &&
                        l.RegistrationInstance.RegistrationTemplate.IsActive &&
                        ( !l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) &&
                        ( !l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) )
                    .FirstOrDefault();

                if ( linkage != null )
                {
                    RegistrationInstanceState = linkage.RegistrationInstance;
                    GroupId = linkage.GroupId;
                    RegistrationState = new RegistrationInfo( CurrentPerson );
                }
            }

            // A group id and campus id were specified
            if ( RegistrationState == null && groupId.HasValue && campusId.HasValue )
            {
                var dateTime = RockDateTime.Now;
                var linkage = new EventItemOccurrenceGroupMapService( rockContext )
                    .Queryable( "RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" )
                    .Where( l =>
                        l.GroupId == groupId &&
                        l.EventItemOccurrence != null &&
                        l.EventItemOccurrence.CampusId == campusId &&
                        l.RegistrationInstance != null &&
                        l.RegistrationInstance.IsActive &&
                        l.RegistrationInstance.RegistrationTemplate != null &&
                        l.RegistrationInstance.RegistrationTemplate.IsActive &&
                        ( !l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) &&
                        ( !l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) )
                    .FirstOrDefault();

                CampusId = campusId;
                if ( linkage != null )
                {
                    RegistrationInstanceState = linkage.RegistrationInstance;
                    GroupId = linkage.GroupId;
                    RegistrationState = new RegistrationInfo( CurrentPerson );
                }
            }

            // A registration instance id was specified
            if ( RegistrationState == null && registrationInstanceId.HasValue )
            {
                var dateTime = RockDateTime.Now;
                RegistrationInstanceState = new RegistrationInstanceService( rockContext )
                    .Queryable( "Account,RegistrationTemplate.Fees,RegistrationTemplate.Discounts,RegistrationTemplate.Forms.Fields.Attribute,RegistrationTemplate.FinancialGateway" )
                    .Where( r =>
                        r.Id == registrationInstanceId.Value &&
                        r.IsActive &&
                        r.RegistrationTemplate != null &&
                        r.RegistrationTemplate.IsActive &&
                        ( !r.StartDateTime.HasValue || r.StartDateTime <= dateTime ) &&
                        ( !r.EndDateTime.HasValue || r.EndDateTime > dateTime ) )
                    .FirstOrDefault();

                if ( RegistrationInstanceState != null )
                {
                    RegistrationState = new RegistrationInfo( CurrentPerson );
                }
            }

            // If registration instance id and event occurrence were specified, but a group (linkage) hasn't been loaded, find the first group for the event occurrence
            if ( RegistrationInstanceState != null && eventOccurrenceId.HasValue && !groupId.HasValue )
            {
                var eventItemOccurrence = new EventItemOccurrenceService( rockContext )
                    .Queryable()
                    .Where( o => o.Id == eventOccurrenceId.Value )
                    .FirstOrDefault();
                if ( eventItemOccurrence != null )
                {
                    CampusId = eventItemOccurrence.CampusId;

                    var linkage = eventItemOccurrence.Linkages
                        .Where( l => l.RegistrationInstanceId == RegistrationInstanceState.Id )
                        .FirstOrDefault();

                    if ( linkage != null )
                    {
                        GroupId = linkage.GroupId;
                    }
                }
            }

            if ( RegistrationState != null &&
                RegistrationState.FamilyGuid == Guid.Empty &&
                RegistrationTemplate != null &&
                RegistrationTemplate.RegistrantsSameFamily != RegistrantsSameFamily.Ask )
            {
                RegistrationState.FamilyGuid = Guid.NewGuid();
            }

            if ( RegistrationState != null && !RegistrationState.Registrants.Any() )
            {
                SetRegistrantState( 1 );
            }

            if ( RegistrationTemplate != null &&
                RegistrationTemplate.FinancialGateway != null )
            {
                var threeStepGateway = RegistrationTemplate.FinancialGateway.GetGatewayComponent() as ThreeStepGatewayComponent;
                Using3StepGateway = threeStepGateway != null;
                if ( Using3StepGateway )
                {
                    Step2IFrameUrl = ResolveRockUrl( threeStepGateway.Step2FormUrl );
                }
            }

            return true;
        }
        /// <summary>
        /// Handles the Click event of the btnEdit 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 btnEdit_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( hfEventItemOccurrenceId.Value.AsInteger() );

            ShowEditDetails( eventItemOccurrence );
        }
Esempio n. 35
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;
            }
        }
        /// <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 );
                }
            }
        }
Esempio n. 37
0
        private void LoadContent()
        {
            var eventItemGuid = GetAttributeValue( "EventItem" ).AsGuid();

            if ( eventItemGuid != Guid.Empty )
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService( rockContext ).Queryable()
                                            .Where( e => e.EventItem.Guid == eventItemGuid );

                // filter occurrences for campus
                if ( GetAttributeValue( "UseCampusContext" ).AsBoolean() )
                {
                    var campusEntityType = EntityTypeCache.Read( "Rock.Model.Campus" );
                    var contextCampus = RockPage.GetCurrentContext( campusEntityType ) as Campus;

                    qry = qry.Where( e => e.CampusId == contextCampus.Id );
                }
                else
                {
                    if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "Campuses" ) ) )
                    {
                        var selectedCampuses = Array.ConvertAll( GetAttributeValue( "Campuses" ).Split( ',' ), s => new Guid( s ) ).ToList();
                        qry = qry.Where( e => selectedCampuses.Contains( e.Campus.Guid ) );
                    }
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( GetAttributeValue( "DateRange" ) );
                if ( dateRange.Start != null && dateRange.End != null )
                {
                    foreach ( var occurrence in itemOccurrences )
                    {
                        if ( occurrence.GetStartTimes( dateRange.Start.Value, dateRange.End.Value ).Count() == 0 )
                        {
                            itemOccurrences.Remove( occurrence );
                        }
                    }
                }

                // limit results
                int maxItems = GetAttributeValue( "MaxOccurrences" ).AsInteger();
                itemOccurrences = itemOccurrences.OrderBy( i => i.NextStartDateTime ).Take( maxItems ).ToList();

                // make lava merge fields
                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "RegistrationPage", LinkedPageUrl( "RegistrationPage", null ) );
                mergeFields.Add( "EventItem", new EventItemService( rockContext ).Get( eventItemGuid ) );
                mergeFields.Add( "EventItemOccurrences", itemOccurrences );

                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;
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No event item is configured for this block.</div>";
            }
        }
Esempio n. 38
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;
            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>";
            }
        }
Esempio n. 40
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                // Get any querystring variables
                ContentItemId         = PageParameter("ContentItemId").AsIntegerOrNull();
                EventItemOccurrenceId = PageParameter("EventItemOccurrenceId").AsIntegerOrNull();
                EventItemId           = PageParameter("EventItemId").AsIntegerOrNull();
                EventCalendarId       = PageParameter("EventCalendarId").AsIntegerOrNull();

                // Determine current page number based on querystring values
                if (ContentItemId.HasValue)
                {
                    PageNumber = 5;
                }
                else if (EventItemOccurrenceId.HasValue)
                {
                    PageNumber = 4;
                }
                else if (EventItemId.HasValue)
                {
                    PageNumber = 3;
                }
                else if (EventCalendarId.HasValue)
                {
                    PageNumber = 2;
                }
                else
                {
                    PageNumber = 1;
                }

                // Load objects neccessary to display names
                using (var rockContext = new RockContext())
                {
                    ContentChannelItem  contentItem         = null;
                    EventItemOccurrence eventItemOccurrence = null;
                    EventItem           eventItem           = null;
                    EventCalendar       eventCalendar       = null;

                    if (ContentItemId.HasValue && ContentItemId.Value > 0)
                    {
                        var contentChannel = new ContentChannelItemService(rockContext).Get(ContentItemId.Value);
                    }

                    if (EventItemOccurrenceId.HasValue && EventItemOccurrenceId.Value > 0)
                    {
                        eventItemOccurrence = new EventItemOccurrenceService(rockContext).Get(EventItemOccurrenceId.Value);
                        if (eventItemOccurrence != null)
                        {
                            eventItem = eventItemOccurrence.EventItem;
                            if (eventItem != null && !EventItemId.HasValue)
                            {
                                EventItemId = eventItem.Id;
                            }
                        }
                    }

                    if (eventItem == null && EventItemId.HasValue && EventItemId.Value > 0)
                    {
                        eventItem = new EventItemService(rockContext).Get(EventItemId.Value);
                    }

                    if (EventCalendarId.HasValue && EventCalendarId.Value > 0)
                    {
                        eventCalendar = new EventCalendarService(rockContext).Get(EventCalendarId.Value);
                    }

                    // Set the names based on current object values
                    lCalendarName.Text        = eventCalendar != null ? eventCalendar.Name : "Calendar";
                    lCalendarItemName.Text    = eventItem != null ? eventItem.Name : "Event";
                    lEventOccurrenceName.Text = eventItemOccurrence != null ?
                                                (eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses") :
                                                "Event Occurrence";
                    lContentItemName.Text = contentItem != null ? contentItem.Title : "Content Item";
                }
            }

            divCalendars.Attributes["class"]       = GetDivClass(1);
            divCalendar.Attributes["class"]        = GetDivClass(2);
            divCalendarItem.Attributes["class"]    = GetDivClass(3);
            divEventOccurrence.Attributes["class"] = GetDivClass(4);
            divContentItem.Attributes["class"]     = GetDivClass(5);
        }
        private void LoadContent()
        {
            var audienceGuid = GetAttributeValue( "Audience" ).AsGuid();

            if ( audienceGuid != Guid.Empty )
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService( rockContext ).Queryable()
                                            .Where(e => e.EventItem.EventItemAudiences.Any(a => a.DefinedValue.Guid == audienceGuid) && e.EventItem.IsActive);

                // filter occurrences for campus (always include the "All Campuses" events)
                if ( GetAttributeValue( "UseCampusContext" ).AsBoolean() )
                {
                    var campusEntityType = EntityTypeCache.Read( "Rock.Model.Campus" );
                    var contextCampus = RockPage.GetCurrentContext( campusEntityType ) as Campus;

                    if ( contextCampus != null )
                    {
                        qry = qry.Where( e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue );
                    }
                }
                else
                {
                    if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "Campuses" ) ) )
                    {
                        var selectedCampuses = Array.ConvertAll( GetAttributeValue( "Campuses" ).Split( ',' ), s => new Guid( s ) ).ToList();
                        qry = qry.Where( e => selectedCampuses.Contains(e.Campus.Guid) || !e.CampusId.HasValue );
                    }
                }

                // filter by calendar
                var calendarGuid = GetAttributeValue( "Calendar" ).AsGuid();

                if ( calendarGuid != Guid.Empty )
                {
                    qry = qry.Where( e => e.EventItem.EventCalendarItems.Any( c => c.EventCalendar.Guid == calendarGuid ) );
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( GetAttributeValue( "DateRange" ) );
                if ( dateRange.Start != null && dateRange.End != null )
                {
                    itemOccurrences.RemoveAll( o => o.GetStartTimes( dateRange.Start.Value, dateRange.End.Value ).Count() == 0 );
                }
                else
                {
                    // default show all future
                    itemOccurrences.RemoveAll( o => o.GetStartTimes( RockDateTime.Now, DateTime.Now.AddDays( 365 ) ).Count() == 0 );
                }

                // limit results
                int maxItems = GetAttributeValue( "MaxOccurrences" ).AsInteger();
                itemOccurrences = itemOccurrences.OrderBy( i => i.NextStartDateTime ).Take( maxItems ).ToList();

                // make lava merge fields
                var mergeFields = new Dictionary<string, object>();

                var contextObjects = new Dictionary<string, object>();
                foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                {
                    var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                    if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                    {
                        var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                        if (type != null)
                        {
                            contextObjects.Add(type.Name, contextEntity);
                        }
                    }

                }

                if (contextObjects.Any())
                {
                    mergeFields.Add("Context", contextObjects);
                }

                mergeFields.Add( "ListTitle", GetAttributeValue("ListTitle") );
                mergeFields.Add( "EventDetailPage", LinkedPageRoute( "EventDetailPage" ) );
                mergeFields.Add( "RegistrationPage", LinkedPageRoute( "RegistrationPage" ) );
                mergeFields.Add( "EventItemOccurrences", itemOccurrences );

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

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = @"<div class='alert alert-info'>Due to the size of the lava members the debug info for this block has been supressed. Below are high-level details of
                                    the merge objects available.
                                    <ul>
                                        <li>List Title - The title to pass to lava.
                                        <li>EventItemOccurrences - A list of EventItemOccurrences. View the EvenItemOccurrence model for these properties.</li>
                                        <li>RegistrationPage  - String that contains the relative path to the registration page.</li>
                                        <li>EventDetailPage  - String that contains the relative path to the event detail page.</li>
                                        <li>Global Attribute  - Access to the Global Attributes.</li>
                                    </ul>
                                    </div>";
                }
                else
                {
                    lDebug.Visible = false;
                    lDebug.Text = string.Empty;
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No audience is configured for this block.</div>";
            }
        }
Esempio n. 42
0
        private void LoadContent()
        {
            var eventItemGuid = GetAttributeValue("EventItem").AsGuid();

            if (eventItemGuid != Guid.Empty)
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService(rockContext).Queryable()
                          .Where(e => e.EventItem.Guid == eventItemGuid);

                // filter occurrences for campus
                if (GetAttributeValue("UseCampusContext").AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Get("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == null || e.CampusId == contextCampus.Id);
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses")))
                    {
                        var selectedCampusGuids = GetAttributeValue("Campuses").Split(',').AsGuidList();
                        var selectedCampusIds   = selectedCampusGuids.Select(a => CampusCache.Get(a)).Where(a => a != null).Select(a => a.Id);

                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == null || selectedCampusIds.Contains(e.CampusId.Value));
                    }
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange"));
                if (dateRange.Start != null && dateRange.End != null)
                {
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0);
                }
                else
                {
                    // default show all future (max 1 year)
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddDays(365)).Count() == 0);
                }

                // limit results
                int maxItems = GetAttributeValue("MaxOccurrences").AsInteger();
                itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList();

                // load event item
                var eventItem = new EventItemService(rockContext).Get(eventItemGuid);

                // make lava merge fields
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));
                mergeFields.Add("EventItem", eventItem);
                mergeFields.Add("EventItemOccurrences", itemOccurrences);

                // add context to merge fields
                var contextEntityTypes = RockPage.GetContextEntityTypes();

                var contextObjects = new Dictionary <string, object>();
                foreach (var conextEntityType in contextEntityTypes)
                {
                    var contextObject = RockPage.GetCurrentContext(conextEntityType);
                    contextObjects.Add(conextEntityType.FriendlyName, contextObject);
                }

                mergeFields.Add("Context", contextObjects);

                lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No event item is configured for this block.</div>";
            }
        }
Esempio n. 43
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);
                }
            }
        }
Esempio n. 44
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                // Get any querystring variables
                ContentItemId = PageParameter( "ContentItemId" ).AsIntegerOrNull();
                EventItemOccurrenceId = PageParameter( "EventItemOccurrenceId" ).AsIntegerOrNull();
                EventItemId = PageParameter( "EventItemId" ).AsIntegerOrNull();
                EventCalendarId = PageParameter( "EventCalendarId" ).AsIntegerOrNull();

                // Determine current page number based on querystring values
                if ( ContentItemId.HasValue )
                {
                    PageNumber = 5;
                }
                else if ( EventItemOccurrenceId.HasValue )
                {
                    PageNumber = 4;
                }
                else if ( EventItemId.HasValue )
                {
                    PageNumber = 3;
                }
                else if ( EventCalendarId.HasValue )
                {
                    PageNumber = 2;
                }
                else
                {
                    PageNumber = 1;
                }

                // Load objects neccessary to display names
                using ( var rockContext = new RockContext() )
                {
                    ContentChannelItem contentItem = null;
                    EventItemOccurrence eventItemOccurrence = null;
                    EventItem eventItem = null;
                    EventCalendar eventCalendar = null;

                    if ( ContentItemId.HasValue && ContentItemId.Value > 0 )
                    {
                        var contentChannel = new ContentChannelItemService( rockContext ).Get( ContentItemId.Value );
                    }

                    if ( EventItemOccurrenceId.HasValue && EventItemOccurrenceId.Value > 0 )
                    {
                        eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( EventItemOccurrenceId.Value );
                        if ( eventItemOccurrence != null )
                        {
                            eventItem = eventItemOccurrence.EventItem;
                            if ( eventItem != null && !EventItemId.HasValue )
                            {
                                EventItemId = eventItem.Id;
                            }
                        }
                    }

                    if ( eventItem == null && EventItemId.HasValue && EventItemId.Value > 0 )
                    {
                        eventItem = new EventItemService( rockContext ).Get( EventItemId.Value );
                    }

                    if ( EventCalendarId.HasValue && EventCalendarId.Value > 0 )
                    {
                        eventCalendar = new EventCalendarService( rockContext ).Get( EventCalendarId.Value );
                    }

                    // Set the names based on current object values
                    lCalendarName.Text = eventCalendar != null ? eventCalendar.Name : "Calendar";
                    lCalendarItemName.Text = eventItem != null ? eventItem.Name : "Event";
                    lEventOccurrenceName.Text = eventItemOccurrence != null ?
                        ( eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses" ) :
                        "Event Occurrence";
                    lContentItemName.Text = contentItem != null ? contentItem.Title : "Content Item";
                }
            }

            divCalendars.Attributes["class"] = GetDivClass( 1 );
            divCalendar.Attributes["class"] = GetDivClass( 2 );
            divCalendarItem.Attributes["class"] = GetDivClass( 3 );
            divEventOccurrence.Attributes["class"] = GetDivClass( 4 );
            divContentItem.Attributes["class"] = GetDivClass( 5 );
        }
        private void LoadContent()
        {
            var eventItemGuid = GetAttributeValue("EventItem").AsGuid();

            if (eventItemGuid != Guid.Empty)
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService(rockContext).Queryable()
                          .Where(e => e.EventItem.Guid == eventItemGuid);

                // filter occurrences for campus
                if (GetAttributeValue("UseCampusContext").AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        qry = qry.Where(e => e.CampusId == contextCampus.Id);
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses")))
                    {
                        var selectedCampuses = Array.ConvertAll(GetAttributeValue("Campuses").Split(','), s => new Guid(s)).ToList();
                        qry = qry.Where(e => selectedCampuses.Contains(e.Campus.Guid));
                    }
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange"));
                if (dateRange.Start != null && dateRange.End != null)
                {
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0);
                }
                else
                {
                    // default show all future (max 1 year)
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddDays(365)).Count() == 0);
                }

                // limit results
                int maxItems = GetAttributeValue("MaxOccurrences").AsInteger();
                itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList();

                // load event item
                var eventItem = new EventItemService(rockContext).Get(eventItemGuid);

                // make lava merge fields
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));
                mergeFields.Add("EventItem", eventItem);
                mergeFields.Add("EventItemOccurrences", itemOccurrences);

                // add context to merge fields
                var contextEntityTypes = RockPage.GetContextEntityTypes();

                var contextObjects = new Dictionary <string, object>();
                foreach (var conextEntityType in contextEntityTypes)
                {
                    var contextObject = RockPage.GetCurrentContext(conextEntityType);
                    contextObjects.Add(conextEntityType.FriendlyName, contextObject);
                }

                mergeFields.Add("Context", contextObjects);

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

                // show debug info
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = @"<div class='alert alert-info'>Due to the size of the lava members the debug info for this block has been supressed. Below are high-level details of
                                    the merge objects available.
                                    <ul>
                                        <li>EventItemOccurrences - A list of EventItemOccurrences. View the EvenItemOccurrence model for these properties.</li>
                                        <li>EventItem - The EventItem that was selected. View the EvenItem model for these properties.</li>
                                        <li>RegistrationPage  - String that contains the relative path to the registration page.</li>
                                        <li>Global Attribute  - Access to the Global Attributes.</li>
                                    </ul>
                                    </div>";
                }
                else
                {
                    lDebug.Visible = false;
                    lDebug.Text    = string.Empty;
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No event item is configured for this block.</div>";
            }
        }
Esempio n. 46
0
        private void LoadContent()
        {
            var audienceGuid = GetAttributeValue("Audience").AsGuid();

            if (audienceGuid != Guid.Empty)
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService(rockContext).Queryable()
                          .Where(e => e.EventItem.EventItemAudiences.Any(a => a.DefinedValue.Guid == audienceGuid) && e.EventItem.IsActive);

                // filter occurrences for campus (always include the "All Campuses" events)
                if (GetAttributeValue("UseCampusContext").AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Read("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses")))
                    {
                        var selectedCampuses = Array.ConvertAll(GetAttributeValue("Campuses").Split(','), s => new Guid(s)).ToList();
                        qry = qry.Where(e => selectedCampuses.Contains(e.Campus.Guid) || !e.CampusId.HasValue);
                    }
                }

                // filter by calendar
                var calendarGuid = GetAttributeValue("Calendar").AsGuid();

                if (calendarGuid != Guid.Empty)
                {
                    qry = qry.Where(e => e.EventItem.EventCalendarItems.Any(c => c.EventCalendar.Guid == calendarGuid));
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange"));
                if (dateRange.Start != null && dateRange.End != null)
                {
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0);
                }
                else
                {
                    // default show all future
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, DateTime.Now.AddDays(365)).Count() == 0);
                }

                // limit results
                int maxItems = GetAttributeValue("MaxOccurrences").AsInteger();
                itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList();

                // make lava merge fields
                var mergeFields = new Dictionary <string, object>();

                var contextObjects = new Dictionary <string, object>();
                foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                {
                    var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                    if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                    {
                        var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                        if (type != null)
                        {
                            contextObjects.Add(type.Name, contextEntity);
                        }
                    }
                }

                if (contextObjects.Any())
                {
                    mergeFields.Add("Context", contextObjects);
                }

                mergeFields.Add("ListTitle", GetAttributeValue("ListTitle"));
                mergeFields.Add("EventDetailPage", LinkedPageUrl("EventDetailPage", null));
                mergeFields.Add("RegistrationPage", LinkedPageUrl("RegistrationPage", null));
                mergeFields.Add("EventItemOccurrences", itemOccurrences);

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

                // show debug info
                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = @"<div class='alert alert-info'>Due to the size of the lava members the debug info for this block has been supressed. Below are high-level details of
                                    the merge objects available.
                                    <ul>
                                        <li>List Title - The title to pass to lava.
                                        <li>EventItemOccurrences - A list of EventItemOccurrences. View the EvenItemOccurrence model for these properties.</li>
                                        <li>RegistrationPage  - String that contains the relative path to the registration page.</li>
                                        <li>EventDetailPage  - String that contains the relative path to the event detail page.</li>
                                        <li>Global Attribute  - Access to the Global Attributes.</li>
                                    </ul>
                                    </div>";
                }
                else
                {
                    lDebug.Visible = false;
                    lDebug.Text    = string.Empty;
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No audience is configured for this block.</div>";
            }
        }
Esempio n. 47
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                // Get any querystring variables
                ContentItemId         = PageParameter("ContentItemId").AsIntegerOrNull();
                EventItemOccurrenceId = PageParameter("EventItemOccurrenceId").AsIntegerOrNull();
                EventItemId           = PageParameter("EventItemId").AsIntegerOrNull();
                EventCalendarId       = PageParameter("EventCalendarId").AsIntegerOrNull();

                // Load objects necessary to display names
                using (var rockContext = new RockContext())
                {
                    ContentChannelItem  contentItem         = null;
                    EventItemOccurrence eventItemOccurrence = null;
                    EventItem           eventItem           = null;
                    EventCalendar       eventCalendar       = null;

                    if (ContentItemId.HasValue && ContentItemId.Value > 0)
                    {
                        PageNumber = 5;
                        var contentChannel = new ContentChannelItemService(rockContext).Get(ContentItemId.Value);
                    }

                    if (EventItemOccurrenceId.HasValue && EventItemOccurrenceId.Value > 0)
                    {
                        PageNumber          = PageNumber ?? 4;
                        eventItemOccurrence = new EventItemOccurrenceService(rockContext).Get(EventItemOccurrenceId.Value);
                        if (eventItemOccurrence != null)
                        {
                            eventItem = eventItemOccurrence.EventItem;
                            if (eventItem != null && !EventItemId.HasValue)
                            {
                                EventItemId = eventItem.Id;
                            }
                        }
                    }

                    if (EventItemId.HasValue && EventItemId.Value > 0)
                    {
                        PageNumber = PageNumber ?? 3;
                        if (eventItem == null)
                        {
                            eventItem = new EventItemService(rockContext).Get(EventItemId.Value);
                        }

                        if (!EventCalendarId.HasValue)
                        {
                            foreach (var cal in eventItem.EventCalendarItems)
                            {
                                EventCalendarId = EventCalendarId ?? cal.EventCalendarId;
                                if (cal.EventCalendar.IsAuthorized(Authorization.EDIT, CurrentPerson))
                                {
                                    EventCalendarId = cal.EventCalendarId;
                                    break;
                                }
                            }
                        }
                    }

                    if (EventCalendarId.HasValue && EventCalendarId.Value > 0)
                    {
                        PageNumber    = PageNumber ?? 2;
                        eventCalendar = new EventCalendarService(rockContext).Get(EventCalendarId.Value);
                    }

                    PageNumber = PageNumber ?? 1;

                    // Set the names based on current object values
                    lCalendarName.Text        = eventCalendar != null ? eventCalendar.Name : "Calendar";
                    lCalendarItemName.Text    = eventItem != null ? eventItem.Name : "Event";
                    lEventOccurrenceName.Text = eventItemOccurrence != null ?
                                                (eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses") :
                                                "Event Occurrence";
                    lContentItemName.Text = contentItem != null ? contentItem.Title : "Content Item";
                }
            }

            divCalendars.Attributes["class"]       = GetDivClass(1);
            divCalendar.Attributes["class"]        = GetDivClass(2);
            divCalendarItem.Attributes["class"]    = GetDivClass(3);
            divEventOccurrence.Attributes["class"] = GetDivClass(4);
            divContentItem.Attributes["class"]     = GetDivClass(5);
        }
Esempio n. 48
0
        /// <summary>
        /// Handles the SaveClick event of the dlgAddCalendarItemPage3 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 dlgAddCalendarItemPage3_SaveClick( object sender, EventArgs e )
        {
            // Save selection to hidden field
            using ( var rockContext = new RockContext() )
            {
                int? eventItemOccurrenceId = ddlCalendarItemOccurrence.SelectedValueAsInt();
                if ( eventItemOccurrenceId.HasValue )
                {
                    var eventItemOccurrence = new EventItemOccurrenceService( rockContext )
                        .Queryable( "EventItem,Campus" ).AsNoTracking()
                        .Where( c => c.Id == eventItemOccurrenceId.Value )
                        .FirstOrDefault();
                    if ( eventItemOccurrence != null )
                    {
                        hfLinkageEventItemOccurrenceId.Value = eventItemOccurrence.Id.ToString();
                        lLinkageEventItemOccurrence.Text = eventItemOccurrence.ToString();
                        lbLinkageEventItemOccurrenceAdd.Visible = false;
                        lbLinkageEventItemOccurrenceRemove.Visible = true;
                    }
                }
            }

            HideDialog();
        }
 /// <summary>
 /// Handles the Click event of the btnCancel 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 btnCancel_Click( object sender, EventArgs e )
 {
     int eventItemId = hfEventItemOccurrenceId.ValueAsInt();
     if ( eventItemId == 0 )
     {
         var qryParams = new Dictionary<string, string>();
         qryParams.Add( "EventCalendarId", PageParameter( "EventCalendarId" ) );
         qryParams.Add( "EventItemId", PageParameter( "EventItemId" ) );
         NavigateToParentPage( qryParams );
     }
     else
     {
         var eventItemOccurrence = new EventItemOccurrenceService( new RockContext() ).Get( eventItemId );
         ShowReadonlyDetails( eventItemOccurrence );
     }
 }
        /// <summary>
        /// Binds the campus grid.
        /// </summary>
        private void BindCampusGrid()
        {
            if ( _eventItem != null )
            {
                pnlEventCalendarCampusItems.Visible = true;

                var rockContext = new RockContext();

                var qry = new EventItemOccurrenceService( rockContext )
                    .Queryable().AsNoTracking()
                    .Where( c => c.EventItemId == _eventItem.Id );

                // Filter by Campus
                List<int> campusIds = cblCampus.SelectedValuesAsInt;
                if ( campusIds.Any() )
                {
                    qry = qry
                        .Where( i =>
                            !i.CampusId.HasValue ||
                            campusIds.Contains( i.CampusId.Value ) );
                }

                SortProperty sortProperty = gCalendarItemOccurrenceList.SortProperty;

                // Sort and query db
                List<EventItemOccurrence> eventItemOccurrences = null;
                if ( sortProperty != null )
                {
                    // If sorting on date, wait until after checking to see if date range was specified
                    if ( sortProperty.Property == "Date" )
                    {
                        eventItemOccurrences = qry.ToList();
                    }
                    else
                    {
                        eventItemOccurrences = qry.Sort( sortProperty ).ToList();
                    }
                }
                else
                {
                    eventItemOccurrences = qry.ToList().OrderBy( a => a.NextStartDateTime ).ToList();
                }

                // Contact filter
                if ( !string.IsNullOrWhiteSpace( tbContact.Text ) )
                {
                    eventItemOccurrences = eventItemOccurrences
                        .Where( i =>
                            i.ContactPersonAlias != null &&
                            i.ContactPersonAlias.Person != null &&
                            i.ContactPersonAlias.Person.FullName.Contains( tbContact.Text ) )
                        .ToList();
                }

                // Now that items have been loaded and ordered from db, calculate the next start date for each item
                var eventItemOccurrencesWithDates = eventItemOccurrences
                    .Select( i => new EventItemOccurrenceWithDates
                    {
                        EventItemOccurrence = i,
                        NextStartDateTime = i.NextStartDateTime,
                    } )
                    .ToList();

                var dateCol = gCalendarItemOccurrenceList.Columns.OfType<BoundField>().Where( c => c.DataField == "Date" ).FirstOrDefault();

                // if a date range was specified, need to get all dates for items and filter based on any that have an occurrence withing the date range
                DateTime? lowerDateRange = drpDate.LowerValue;
                DateTime? upperDateRange = drpDate.UpperValue;
                if ( lowerDateRange.HasValue || upperDateRange.HasValue )
                {
                    // If only one value was included, default the other to be a years difference
                    lowerDateRange = lowerDateRange ?? upperDateRange.Value.AddYears( -1 ).AddDays( 1 );
                    upperDateRange = upperDateRange ?? lowerDateRange.Value.AddYears( 1 ).AddDays( -1 );

                    // Get the start datetimes within the selected date range
                    eventItemOccurrencesWithDates.ForEach( i => i.StartDateTimes = i.EventItemOccurrence.GetStartTimes( lowerDateRange.Value, upperDateRange.Value.AddDays( 1 ) ) );

                    // Filter out calendar items with no dates within range
                    eventItemOccurrencesWithDates = eventItemOccurrencesWithDates.Where( i => i.StartDateTimes.Any() ).ToList();

                    // Update the Next Start Date to be the next date in range instead
                    dateCol.HeaderText = "Next Date In Range";
                    eventItemOccurrencesWithDates.ForEach( i => i.NextStartDateTime = i.StartDateTimes.Min() );
                }
                else
                {
                    dateCol.HeaderText = "Next Start Date";
                }

                // Now sort on date if that is what was selected
                if ( sortProperty != null && sortProperty.Property == "Date" )
                {
                    if ( sortProperty.Direction == SortDirection.Ascending )
                    {
                        eventItemOccurrencesWithDates = eventItemOccurrencesWithDates.OrderBy( a => a.NextStartDateTime ).ToList();
                    }
                    else
                    {
                        eventItemOccurrencesWithDates = eventItemOccurrencesWithDates.OrderByDescending( a => a.NextStartDateTime ).ToList();
                    }
                }

                gCalendarItemOccurrenceList.DataSource = eventItemOccurrencesWithDates
                    .Select( c => new
                    {
                        c.EventItemOccurrence.Id,
                        c.EventItemOccurrence.Guid,
                        Campus = c.EventItemOccurrence.Campus != null ? c.EventItemOccurrence.Campus.Name : "All Campuses",
                        Date = c.NextStartDateTime.HasValue ? c.NextStartDateTime.Value.ToShortDateString() : "N/A",
                        Location = c.EventItemOccurrence.Location,
                        RegistrationInstanceId = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().RegistrationInstanceId : (int?)null,
                        RegistrationInstance = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().RegistrationInstance : null,
                        GroupId = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().GroupId : (int?)null,
                        Group = c.EventItemOccurrence.Linkages.Any() ? c.EventItemOccurrence.Linkages.FirstOrDefault().Group : null,
                        ContentItems = FormatContentItems( c.EventItemOccurrence.ContentChannelItems.Select( i => i.ContentChannelItem ).ToList() ),
                        Contact = c.EventItemOccurrence.ContactPersonAlias != null ? c.EventItemOccurrence.ContactPersonAlias.Person.FullName : "",
                        Phone = c.EventItemOccurrence.ContactPhone,
                        Email = c.EventItemOccurrence.ContactEmail,
                    } )
                    .ToList();
                gCalendarItemOccurrenceList.DataBind();
            }
            else
            {
                pnlEventCalendarCampusItems.Visible = false;
            }
        }
        /// <summary>
        /// Handles the Click event of the btnDelete 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 btnDelete_Click( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                EventItemOccurrenceService eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );
                EventItemOccurrence eventItemOccurrence = eventItemOccurrenceService.Get( hfEventItemOccurrenceId.Value.AsInteger() );

                if ( eventItemOccurrence != null )
                {
                    string errorMessage;
                    if ( !eventItemOccurrenceService.CanDelete( eventItemOccurrence, out errorMessage ) )
                    {
                        mdDeleteWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    eventItemOccurrenceService.Delete( eventItemOccurrence );

                    rockContext.SaveChanges();
                }
            }

            NavigateToParentPage();
        }
Esempio n. 52
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);
        }
Esempio n. 53
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                // Get any querystring variables
                ContentItemId = PageParameter( "ContentItemId" ).AsIntegerOrNull();
                EventItemOccurrenceId = PageParameter( "EventItemOccurrenceId" ).AsIntegerOrNull();
                EventItemId = PageParameter( "EventItemId" ).AsIntegerOrNull();
                EventCalendarId = PageParameter( "EventCalendarId" ).AsIntegerOrNull();

                // Load objects neccessary to display names
                using ( var rockContext = new RockContext() )
                {
                    ContentChannelItem contentItem = null;
                    EventItemOccurrence eventItemOccurrence = null;
                    EventItem eventItem = null;
                    EventCalendar eventCalendar = null;

                    if ( ContentItemId.HasValue && ContentItemId.Value > 0 )
                    {
                        PageNumber = 5;
                        var contentChannel = new ContentChannelItemService( rockContext ).Get( ContentItemId.Value );
                    }

                    if ( EventItemOccurrenceId.HasValue && EventItemOccurrenceId.Value > 0 )
                    {
                        PageNumber = PageNumber ?? 4;
                        eventItemOccurrence = new EventItemOccurrenceService( rockContext ).Get( EventItemOccurrenceId.Value );
                        if ( eventItemOccurrence != null )
                        {
                            eventItem = eventItemOccurrence.EventItem;
                            if ( eventItem != null && !EventItemId.HasValue )
                            {
                                EventItemId = eventItem.Id;
                            }
                        }
                    }

                    if ( EventItemId.HasValue && EventItemId.Value > 0 )
                    {
                        PageNumber = PageNumber ?? 3;
                        if ( eventItem == null )
                        {
                            eventItem = new EventItemService( rockContext ).Get( EventItemId.Value );
                        }

                        if ( !EventCalendarId.HasValue )
                        {
                            foreach ( var cal in eventItem.EventCalendarItems )
                            {
                                EventCalendarId = EventCalendarId ?? cal.EventCalendarId;
                                if ( cal.EventCalendar.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                                {
                                    EventCalendarId = cal.EventCalendarId;
                                    break;
                                }
                            }
                        }
                    }

                    if ( EventCalendarId.HasValue && EventCalendarId.Value > 0 )
                    {
                        PageNumber = PageNumber ?? 2;
                        eventCalendar = new EventCalendarService( rockContext ).Get( EventCalendarId.Value );
                    }

                    PageNumber = PageNumber ?? 1;

                    // Set the names based on current object values
                    lCalendarName.Text = eventCalendar != null ? eventCalendar.Name : "Calendar";
                    lCalendarItemName.Text = eventItem != null ? eventItem.Name : "Event";
                    lEventOccurrenceName.Text = eventItemOccurrence != null ?
                        ( eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses" ) :
                        "Event Occurrence";
                    lContentItemName.Text = contentItem != null ? contentItem.Title : "Content Item";
                }
            }

            divCalendars.Attributes["class"] = GetDivClass( 1 );
            divCalendar.Attributes["class"] = GetDivClass( 2 );
            divCalendarItem.Attributes["class"] = GetDivClass( 3 );
            divEventOccurrence.Attributes["class"] = GetDivClass( 4 );
            divContentItem.Attributes["class"] = GetDivClass( 5 );
        }