/// <summary>
        /// Handles the Click event of the DeleteEventCalendarItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param>
        protected void DeleteEventCalendarItem_Click(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            using (RockContext rockContext = new RockContext())
            {
                EventItemService eventItemService = new EventItemService(rockContext);
                EventItem        eventItem        = eventItemService.Get(e.RowKeyId);
                if (eventItem != null)
                {
                    if (_canEdit)
                    {
                        string errorMessage;
                        if (!eventItemService.CanDelete(eventItem, out errorMessage))
                        {
                            mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                            return;
                        }

                        eventItemService.Delete(eventItem);
                        rockContext.SaveChanges();
                    }
                    else
                    {
                        mdGridWarning.Show("You are not authorized to delete this calendar item", ModalAlertType.Warning);
                    }
                }
            }

            BindEventCalendarItemsGrid();
        }
        /// <summary>
        /// Sets the edit value from IEntity.Id value
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="id">The identifier.</param>
        public void SetEditValueFromEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id)
        {
            var item      = new EventItemService(new RockContext()).Get(id ?? 0);
            var guidValue = item != null?item.Guid.ToString() : string.Empty;

            SetEditValue(control, configurationValues, guidValue);
        }
        /// <summary>
        /// Gets the edit value as the IEntity.Id
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <returns></returns>
        public int?GetEditValueAsEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            var guid = GetEditValue(control, configurationValues).AsGuid();
            var item = new EventItemService(new RockContext()).Get(guid);

            return(item != null ? item.Id : ( int? )null);
        }
Beispiel #4
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())
            {
                EventItemService eventItemService = new EventItemService(rockContext);
                EventItem        eventItem        = eventItemService.Get(int.Parse(hfEventItemId.Value));

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

                    eventItemService.Delete(eventItem);

                    rockContext.SaveChanges();
                }
            }

            var qryParams = new Dictionary <string, string>();

            if (_calendarId.HasValue)
            {
                qryParams.Add("EventCalendarId", _calendarId.Value.ToString());
            }
            NavigateToParentPage(qryParams);
        }
Beispiel #5
0
        public void EventItemService_GetActiveEventsAtSpecificDate_ReturnsEventScheduledForSingleDateOnOrAfterSpecifiedDate()
        {
            var rockContext = new RockContext();

            // Get an instance of Event "Warrior Youth Event", which has a single occurrence scheduled for 02-May-2018.
            var eventOccurrenceDate = new DateTime(2018, 5, 2);
            var eventItemService    = new EventItemService(rockContext);

            var warriorEvent = eventItemService.Queryable().FirstOrDefault(x => x.Name == "Warrior Youth Event");

            Assert.That.IsNotNull(warriorEvent, "Target event not found.");

            ForceUpdateScheduleEffectiveDates(rockContext, warriorEvent);

            // The "Warrior Youth Event" has a single occurrence on 02-May-2018.
            // Verify that the filter returns the event on the date of the single occurrence.
            var validEvents = eventItemService.Queryable()
                              .Where(x => x.Name == "Warrior Youth Event")
                              .HasOccurrencesOnOrAfterDate(eventOccurrenceDate)
                              .ToList();

            Assert.That.IsTrue(validEvents.Count() == 1, "Expected Event not found.");

            // ... but not after the date of the single occurrence.
            var invalidEvents = eventItemService.Queryable()
                                .Where(x => x.Name == "Warrior Youth Event")
                                .HasOccurrencesOnOrAfterDate(eventOccurrenceDate.AddDays(1))
                                .ToList();

            Assert.That.IsTrue(invalidEvents.Count() == 0, "Unexpected Event found.");
        }
Beispiel #6
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);
        }
Beispiel #7
0
        public void EventItemOccurrence_UpdatedWithInactiveEvent_HasNullNextDate()
        {
            var rockContext = new RockContext();

            // Get Event "Rock Solid Finances".
            var eventItemService = new EventItemService(rockContext);
            var financeEvent     = eventItemService.Get(EventFinancesClassGuid.AsGuid());

            // Get existing schedules.
            var scheduleService = new ScheduleService(rockContext);
            var scheduleSat1630 = scheduleService.Get(ScheduleSat1630Guid.AsGuid());

            // Set the event to inactive.
            financeEvent.IsActive = false;
            rockContext.SaveChanges();

            // Add an event occurrence for the inactive event.
            var financeEvent1 = EventItemOccurrenceAddOrUpdateInstance(rockContext, ScheduleSat1630Guid.AsGuid(), deleteExistingInstance: true);

            rockContext.SaveChanges();

            // Verify that the NextDateTime is correctly set.
            Assert.IsNull(financeEvent1.NextStartDateTime);

            // Set the event to active.
            financeEvent.IsActive = true;
            rockContext.SaveChanges();
        }
Beispiel #8
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 eventItem   = new EventItemService(rockContext).Get(hfEventItemId.Value.AsInteger());

            ShowEditDetails(eventItem);
        }
Beispiel #9
0
        /// <summary>
        /// Uses the filter information in the CalendarProps object to get a list of events
        /// </summary>
        /// <param name="calendarProps">The calendar props.</param>
        /// <returns></returns>
        private List <EventItem> GetEventItems(CalendarProps calendarProps)
        {
            RockContext rockContext = new RockContext();

            EventCalendarItemService eventCalendarItemService = new EventCalendarItemService(rockContext);
            var eventIdsForCalendar = eventCalendarItemService
                                      .Queryable()
                                      .Where(i => i.EventCalendarId == calendarProps.CalendarId)
                                      .Select(i => i.EventItemId)
                                      .ToList();

            EventItemService eventItemService = new EventItemService(rockContext);
            var eventQueryable = eventItemService
                                 .Queryable("EventItemAudiences, EventItemOccurrences.Schedule")
                                 .Where(e => eventIdsForCalendar.Contains(e.Id))
                                 .Where(e => e.EventItemOccurrences.Any(o => o.Schedule.EffectiveStartDate <= calendarProps.EndDate && calendarProps.StartDate <= o.Schedule.EffectiveEndDate))
                                 .Where(e => e.IsActive == true)
                                 .Where(e => e.IsApproved);

            // For Campus
            if (calendarProps.CampusIds.Any())
            {
                eventQueryable = eventQueryable.Where(e => e.EventItemOccurrences.Any(c => !c.CampusId.HasValue || calendarProps.CampusIds.Contains(c.CampusId.Value)));
            }

            // For Audience
            if (calendarProps.AudienceIds.Any())
            {
                eventQueryable = eventQueryable.Where(e => e.EventItemAudiences.Any(c => calendarProps.AudienceIds.Contains(c.DefinedValueId)));
            }

            return(eventQueryable.ToList());
        }
Beispiel #10
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?eventItemId = PageParameter(pageReference, "EventItemId").AsIntegerOrNull();

            if (eventItemId != null)
            {
                using (var rockContext = new RockContext())
                {
                    EventItem eventItem = new EventItemService(rockContext).Get(eventItemId.Value);
                    if (eventItem != null)
                    {
                        breadCrumbs.Add(new BreadCrumb(eventItem.Name, pageReference));
                    }
                    else
                    {
                        breadCrumbs.Add(new BreadCrumb("New Calendar Item", pageReference));
                    }
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return(breadCrumbs);
        }
        private EventItem ResolveEventSettingOrThrow(RockContext rockContext, string eventSettingValue)
        {
            var eventItemService = new EventItemService(rockContext);

            EventItem eventItem = null;

            // Verify that an Event reference has been provided.
            if (string.IsNullOrWhiteSpace(eventSettingValue))
            {
                throw new Exception($"An Event reference must be specified.");
            }

            // Get by ID.
            var eventId = eventSettingValue.AsIntegerOrNull();

            if (eventId != null)
            {
                eventItem = eventItemService.Get(eventId.Value);
            }

            // Get by Guid.
            if (eventItem == null)
            {
                var eventGuid = eventSettingValue.AsGuidOrNull();

                if (eventGuid != null)
                {
                    eventItem = eventItemService.Get(eventGuid.Value);
                }
            }

            // Get By Name.
            if (eventItem == null)
            {
                var eventName = eventSettingValue.ToString();

                if (!string.IsNullOrWhiteSpace(eventName))
                {
                    eventItem = eventItemService.Queryable()
                                .Where(x => x.Name != null && x.Name.Equals(eventName, StringComparison.OrdinalIgnoreCase))
                                .FirstOrDefault();
                }
            }

            if (eventItem == null)
            {
                throw new Exception($"Cannot find an Event matching the reference \"{ eventSettingValue }\".");
            }

            return(eventItem);
        }
Beispiel #12
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        protected void ShowView(int eventItemId)
        {
            hfEventItemId.Value = eventItemId.ToString();

            var    eventItem         = new EventItemService(new RockContext()).Get(eventItemId);
            string eventLavaTemplate = this.GetAttributeValue("EventLavaTemplate");
            var    mergeFields       = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new Rock.Lava.CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            });

            mergeFields.Add("Event", eventItem);

            lEventDetails.Text = eventLavaTemplate.ResolveMergeFields(mergeFields);
        }
 /// <summary>
 /// Handles the Edit event of the gEventCalendarItems 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 gEventCalendarItems_Edit(object sender, RowEventArgs e)
 {
     using (RockContext rockContext = new RockContext())
     {
         EventItemService eventItemService = new EventItemService(rockContext);
         EventItem        eventItem        = eventItemService.Get(e.RowKeyId);
         if (eventItem != null)
         {
             var qryParams = new Dictionary <string, string>();
             qryParams.Add("EventCalendarId", _eventCalendar.Id.ToString());
             qryParams.Add("EventItemId", eventItem.Id.ToString());
             NavigateToLinkedPage("DetailPage", qryParams);
         }
     }
 }
Beispiel #14
0
        /// <summary>
        /// Gets the eventItem.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        /// <returns></returns>
        private EventItem GetEventItem(int eventItemId, RockContext rockContext = null)
        {
            string    key       = string.Format("EventItem:{0}", eventItemId);
            EventItem eventItem = RockPage.GetSharedItem(key) as EventItem;

            if (eventItem == null)
            {
                rockContext = rockContext ?? new RockContext();
                eventItem   = new EventItemService(rockContext).Queryable()
                              .Where(e => e.Id == eventItemId)
                              .FirstOrDefault();
                RockPage.SaveSharedItem(key, eventItem);
            }

            return(eventItem);
        }
Beispiel #15
0
        public void EventItemService_GetActiveEventsDefault_ReturnsOnlyEventsHavingOccurrencesAfterCurrentDate()
        {
            var rockContext      = new RockContext();
            var eventItemService = new EventItemService(rockContext);
            var events           = eventItemService.GetActiveItems();

            // The Event "Warrior Youth Event" has a single occurrence scheduled in the past.
            // It should not be returned in the list of active items.
            var warriorEvent = events.FirstOrDefault(x => x.Name == "Warrior Youth Event");

            Assert.That.IsNull(warriorEvent, "Unexpected event found in result set.");

            // The Event "Staff Meeting" is endlessly recurring.
            // It should be returned in the list of active items.
            var staffEvent = events.FirstOrDefault(x => x.Name == "Staff Meeting");

            Assert.That.IsNotNull(staffEvent, "Expected event not found in result set.");
        }
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues"></param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            Guid eventItemGuid = Guid.Empty;

            if (Guid.TryParse(value, out eventItemGuid))
            {
                if (control != null && control is EventItemPicker)
                {
                    using (var rockContext = new RockContext())
                    {
                        var eventItem = new EventItemService(rockContext).Get(eventItemGuid);
                        if (eventItem != null)
                        {
                            ((EventItemPicker)control).SetValue(eventItem.Id.ToString());
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Reads new values entered by the user for the field
 /// </summary>
 /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
 /// <param name="configurationValues"></param>
 /// <returns></returns>
 public override string GetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues)
 {
     if (control != null && control is EventItemPicker)
     {
         int id = int.MinValue;
         if (Int32.TryParse(((EventItemPicker)control).SelectedValue, out id))
         {
             using (var rockContext = new RockContext())
             {
                 var eventItem = new EventItemService(rockContext).Get(id);
                 if (eventItem != null)
                 {
                     return(eventItem.Guid.ToString());
                 }
             }
         }
     }
     return(null);
 }
        /// <summary>
        /// Sets the value where value is the EventItem.Guid as a string (or null)
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues"></param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            var picker = control as EventItemPicker;

            if (picker != null)
            {
                EventItem eventItem     = null;
                Guid?     eventItemGuid = value.AsGuidOrNull();
                if (eventItemGuid.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        eventItem = new EventItemService(rockContext).Get(eventItemGuid.Value);
                    }
                }

                picker.SetValue(eventItem);
            }
        }
Beispiel #19
0
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue( Control parentControl, string value, Dictionary<string, ConfigurationValue> configurationValues, bool condensed )
        {
            string formattedValue = string.Empty;

            Guid? eventItemGuid = value.AsGuidOrNull();
            if ( eventItemGuid.HasValue )
            {
                using ( var rockContext = new RockContext() )
                {
                    var eventItem = new EventItemService( rockContext ).Get( eventItemGuid.Value );
                    if ( eventItem != null )
                    {
                        formattedValue = eventItem.Name;
                    }
                }
            }

            return base.FormatValue( parentControl, formattedValue, null, condensed );
        }
        /// <summary>
        /// Returns the field's current value(s)
        /// </summary>
        /// <param name="parentControl">The parent control.</param>
        /// <param name="value">Information about the value</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param>
        /// <returns></returns>
        public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed)
        {
            string formattedValue = string.Empty;

            Guid?eventItemGuid = value.AsGuidOrNull();

            if (eventItemGuid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var eventItem = new EventItemService(rockContext).GetNoTracking(eventItemGuid.Value);
                    if (eventItem != null)
                    {
                        formattedValue = eventItem.Name;
                    }
                }
            }

            return(base.FormatValue(parentControl, formattedValue, null, condensed));
        }
Beispiel #21
0
        public void InheritedAttributes_ParentEntityAttributeValues_IncludesChildEntityAttributeValues()
        {
            var rockContext      = new RockContext();
            var eventItemService = new EventItemService(rockContext);

            // Verify the values of the test Attribute for Event A and Event B.
            // These Attributes are defined per-Calendar and so are directly linked to the EventItemCalendar entity,
            // but they should also appear as inherited attributes of the EventItem.
            var eventA = eventItemService.Get(EventAGuid.AsGuid());

            eventA.LoadAttributes();
            Assert.IsTrue(eventA.AttributeValues[InternalCalendarAttribute1Key].Value == "Event A Internal");
            Assert.IsTrue(eventA.AttributeValues[PublicCalendarAttribute1Key].Value == "Event A Public");

            var eventB = eventItemService.Get(EventBGuid.AsGuid());

            eventB.LoadAttributes();
            Assert.IsTrue(eventB.AttributeValues[PublicCalendarAttribute1Key].Value == "Event B Public");
            Assert.IsTrue(eventB.AttributeValues[InternalCalendarAttribute1Key].Value == null, $"Unexpected Attribute Value: {InternalCalendarAttribute1Key}.");
        }
Beispiel #22
0
        /// <summary>
        /// Formats the search result.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="displayOptions">The display options.</param>
        /// <param name="mergeFields">The merge fields.</param>
        /// <returns></returns>
        public override FormattedSearchResult FormatSearchResult(Person person, Dictionary <string, object> displayOptions = null, Dictionary <string, object> mergeFields = null)
        {
            var  result             = base.FormatSearchResult(person, displayOptions);
            bool isSecurityDisabled = false;

            if (displayOptions != null)
            {
                if (displayOptions.ContainsKey("EventItem-IsSecurityDisabled"))
                {
                    isSecurityDisabled = displayOptions["EventItem-IsSecurityDisabled"].ToString().AsBoolean();
                }
            }

            // If security is disabled true all items
            if (isSecurityDisabled)
            {
                result.IsViewAllowed = true;
                return(result);
            }

            // Otherwise we're checking security
            var eventItem = new EventItemService(new Data.RockContext()).Get(( int )this.Id);

            // Check if item in database has been deleted
            if (eventItem == null)
            {
                result.IsViewAllowed = false;
                return(result);
            }

            if (eventItem.IsAuthorized("View", person))
            {
                result.IsViewAllowed = true;
                return(result);
            }
            else
            {
                result.IsViewAllowed = false;
                return(result);
            }
        }
        /// <summary>
        /// Reads new values entered by the user for the field
        /// </summary>
        /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
        /// <param name="configurationValues"></param>
        /// <returns></returns>
        public override string GetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            var picker = control as EventItemPicker;

            if (picker != null)
            {
                int? itemId   = picker.SelectedValue.AsIntegerOrNull();
                Guid?itemGuid = null;
                if (itemId.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        itemGuid = new EventItemService(rockContext).Queryable().AsNoTracking().Where(a => a.Id == itemId.Value).Select(a => ( Guid? )a.Guid).FirstOrDefault();
                    }
                }

                return(itemGuid?.ToString());
            }

            return(null);
        }
Beispiel #24
0
        public void EventScheduledInstanceCommand_WithEventAsId_RetrievesOccurrencesInCorrectEvent()
        {
            // Get Event Item Id for "Warrior Youth Event".
            var rockContext = new RockContext();

            var eventItemService = new EventItemService(rockContext);
            var eventId          = eventItemService.GetId(StaffMeetingEventGuidString.AsGuid());

            Assert.That.IsNotNull(eventId, "Expected test data not found.");

            var template = GetTestTemplate($"eventid:{eventId} startdate:'2020-1-1' daterange:'12m' maxoccurrences:2");

            TestHelper.ExecuteForActiveEngines((engine) =>
            {
                var output = TestHelper.GetTemplateOutput(engine, template);

                TestHelper.DebugWriteRenderResult(engine, template, output);

                Assert.That.Contains(output, "<<Staff Meeting|2020-01-01|12:00 AM|All Campuses>>");
                Assert.That.Contains(output, "<<Staff Meeting|2020-01-15|12:00 AM|All Campuses>>");
            });
        }
Beispiel #25
0
        public void InheritedAttributes_SetAttributeOnParentEntity_SetsValueForChildEntity()
        {
            var rockContext          = new RockContext();
            var eventItemService     = new EventItemService(rockContext);
            var eventCalendarService = new EventCalendarItemService(rockContext);

            // Setting the value of an inherited Attribute should persist the value for the child entity.
            var eventA = eventItemService.Get(EventAGuid.AsGuid());

            eventA.LoadAttributes(rockContext);
            eventA.SetAttributeValue(InternalCalendarAttribute1Key, "xyzzy");

            // TODO: SaveAttributeValues does not correctly save inherited values.
            // It wrongly attributes them to the entity on which they are set rather than the inherited entity.
            eventA.SaveAttributeValues(rockContext);

            var calendarItemInternal = eventCalendarService.Get(EventACalendarInternalGuid.AsGuid());
            var calendarItemPublic   = eventCalendarService.Get(EventACalendarPublicGuid.AsGuid());

            calendarItemInternal.LoadAttributes();
            Assert.IsTrue(calendarItemInternal.AttributeValues[InternalCalendarAttribute1Key].Value == "xyzzy");
            calendarItemPublic.LoadAttributes();
            Assert.IsTrue(calendarItemPublic.AttributeValues[InternalCalendarAttribute1Key].Value == "xyzzy");
        }
Beispiel #26
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())
            {
                EventItemService eventItemService = new EventItemService(rockContext);
                EventItem        eventItem        = eventItemService.Get(int.Parse(hfEventItemId.Value));

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

                    eventItemService.Delete(eventItem);

                    rockContext.SaveChanges();
                }
            }

            NavigateToParentPage();
        }
Beispiel #27
0
        public void EventItemService_GetActiveEventsByCalendar_ReturnsOnlyEventsInSpecifiedCalendar()
        {
            var rockContext     = new RockContext();
            var calendarService = new EventCalendarService(rockContext);

            var internalCalendar = calendarService.Queryable()
                                   .FirstOrDefault(x => x.Name == "Internal");

            var eventItemService = new EventItemService(rockContext);
            var internalEvents   = eventItemService.GetActiveItemsByCalendarId(internalCalendar.Id)
                                   .ToList();

            // The Event "Staff Meeting" exists in the Internal calendar.
            // It should be returned in the list of active items.
            var staffEvent = internalEvents.FirstOrDefault(x => x.Name == "Staff Meeting");

            Assert.That.IsNotNull(staffEvent, "Expected event not found in result set.");

            // The Event "Warrior Youth Event" only exists in the External calendar.
            // It should not be returned in the list of active items.
            var warriorEvent = internalEvents.FirstOrDefault(x => x.Name == "Warrior Youth Event");

            Assert.That.IsNull(warriorEvent, "Unexpected event found in result set.");
        }
Beispiel #28
0
 /// <summary>
 /// Sets the value.
 /// </summary>
 /// <param name="control">The control.</param>
 /// <param name="configurationValues"></param>
 /// <param name="value">The value.</param>
 public override void SetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues, string value )
 {
     Guid eventItemGuid = Guid.Empty;
     if ( Guid.TryParse( value, out eventItemGuid ) )
     {
         if ( control != null && control is EventItemPicker )
         {
             using ( var rockContext = new RockContext() )
             {
                 var eventItem = new EventItemService( rockContext ).Get( eventItemGuid );
                 if ( eventItem != null )
                 {
                     ( (EventItemPicker)control ).SetValue( eventItem.Id.ToString() );
                 }
             }
         }
     }
 }
Beispiel #29
0
        private void DisplayDetails()
        {
            RockContext rockContext = new RockContext();

            EventItemService eventItemService = new EventItemService(rockContext);
            var qry = eventItemService
                      .Queryable();

            // get the eventItem id if the event item is set via block attribute
            var eventItemAttGuid = GetAttributeValue("EventItem").AsGuid();
            int eventItemId      = qry.Where(i => i.Guid == eventItemAttGuid).Select(i => i.Id).FirstOrDefault();

            // get the eventItem id if the event item block attribute isn't set
            if (eventItemId == 0 && !string.IsNullOrWhiteSpace(PageParameter("EventItemId")))
            {
                eventItemId = Convert.ToInt32(PageParameter("EventItemId"));
            }
            if (eventItemId > 0)
            {
                /*var qry = eventItemService
                 *  .Queryable()
                 *  ;*/
                qry = qry.Where(i => i.Id == eventItemId);
            }
            else
            {
                // Get the Slug Attribute
                var slugAttribute = AttributeCache.Get(GetAttributeValue("URLSlugAttribute").AsGuid());

                // get the slug
                if (!string.IsNullOrWhiteSpace(PageParameter("URLSlug")) && slugAttribute != null)
                {
                    int slugAttributeId = slugAttribute.Id;
                    EventCalendarItemService eventCalendarItemService = new EventCalendarItemService(rockContext);
                    AttributeValueService    attributeValueService    = new AttributeValueService(rockContext);

                    var tmQry = qry.Join(eventCalendarItemService.Queryable(),
                                         ei => ei.Id,
                                         aci => aci.EventItemId,
                                         (ei, aci) => new { EventItem = ei, EventCalendarItem = aci }
                                         )
                                .Join(attributeValueService.Queryable(),
                                      ei => new { Id = ei.EventCalendarItem.Id, AttributeId = slugAttributeId },
                                      av => new { Id = av.EntityId ?? 0, AttributeId = av.AttributeId },
                                      (ei, av) => new { EventItem = ei.EventItem, EventCalendarItem = ei.EventCalendarItem, Slug = av });

                    string urlSlug = PageParameter("URLSlug");

                    tmQry = tmQry.Where(obj => obj.Slug.Value.Contains(urlSlug));

                    // The page parameter could contain something like 'camp' while the slug value list contains 'camp-freedom' so we need to double-check
                    // to make sure we have an exact match
                    qry = tmQry.ToList().AsQueryable().Where(obj => obj.Slug.Value.ToLower().Split('|').Contains(urlSlug.ToLower())).Select(obj => obj.EventItem);
                }
                else
                {
                    // If we don't have an eventItemId or slug we shouldn't get the first item in the database.  That would be . . . not good
                    qry = null;
                }
            }

            if (qry != null)
            {
                var eventItem = qry.FirstOrDefault();

                if (eventItem != null)
                {
                    // removing any occurrences that don't have a start time in the next twelve months
                    var occurrenceList = eventItem.EventItemOccurrences.ToList();
                    occurrenceList.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddYears(1)).Count() == 0);

                    //Check for Campus Id Parameter
                    var campusId = PageParameter("CampusId").AsIntegerOrNull();
                    if (campusId.HasValue)
                    {
                        //check if there's a campus with this id.
                        var campus = CampusCache.Get(campusId.Value);
                        if (campus != null)
                        {
                            occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                        }
                    }

                    //Check for Campus
                    var campusStr = PageParameter("Campus");
                    if (!string.IsNullOrEmpty(campusStr))
                    {
                        //check if there's a campus with this name.
                        var campus = CampusCache.All().Where(c => c.Name.ToLower().RemoveSpaces() == campusStr.ToLower().RemoveSpaces()).FirstOrDefault();
                        if (campus != null)
                        {
                            occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                        }
                        else
                        {
                            // check one more time to see if there's a campus slug that matches
                            campus = CampusCache.All().Where(c => c.AttributeValues["Slug"].ToString() == campusStr.ToLower()).FirstOrDefault();
                            if (campus != null)
                            {
                                occurrenceList.RemoveAll(o => o.CampusId != null && o.CampusId != campus.Id);
                            }
                        }
                    }

                    eventItem.EventItemOccurrences = occurrenceList.OrderBy(o => o.NextStartDateTime.HasValue ? o.NextStartDateTime : DateTime.Now).ToList();

                    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 occurance in eventItem.EventItemOccurrences)
                    {
                        foreach (var registrationInstance in occurance.Linkages.Select(a => a.RegistrationInstance).Distinct().ToList())
                        {
                            if (registrationStatusLabels.ContainsKey(registrationInstance.Id))
                            {
                                continue;
                            }
                            int?maxRegistrantCount       = 0;
                            var currentRegistrationCount = 0;

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


                            int?registrationSpotsAvailable = null;
                            if (maxRegistrantCount.HasValue && 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 each registration instance
                    mergeFields.Add("RegistrationStatusLabels", registrationStatusLabels);

                    mergeFields.Add("Event", eventItem);
                    mergeFields.Add("CurrentPerson", CurrentPerson);

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

                    if (GetAttributeValue("SetPageTitle").AsBoolean())
                    {
                        string pageTitle = eventItem != null ? 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 = EventNotFoundLava();
                }
            }
            else
            {
                lOutput.Text = EventNotFoundLava();
            }
        }
        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>";
            }
        }
Beispiel #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 )
        {
            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 );
        }
        public void RockCleanup_Execute_ShouldUpdateEventItemOccurrences()
        {
            var referenceDate = new DateTime(2020, 1, 1);

            // Get the sample data schedule for Saturday 4:30pm.
            var rockContext = new RockContext();

            var scheduleService = new ScheduleService(rockContext);
            var schedule        = scheduleService.Get(TestGuids.Schedules.ScheduleSat1630Guid.AsGuid());

            // Create a new inactive schedule.
            var scheduleInactive = scheduleService.Get(testScheduleGuid);

            if (scheduleInactive == null)
            {
                scheduleInactive = new Schedule();
                scheduleService.Add(scheduleInactive);
            }
            scheduleInactive.Name     = "Test Schedule";
            scheduleInactive.Guid     = testScheduleGuid;
            scheduleInactive.IsActive = false;

            rockContext.SaveChanges();

            // Create the Test Events.
            var eventItemService = new EventItemService(rockContext);

            // Test Event 1 (active)
            var testEvent1 = eventItemService.Get(testEvent1Guid);

            if (testEvent1 != null)
            {
                eventItemService.Delete(testEvent1);
                rockContext.SaveChanges();
            }

            testEvent1      = new EventItem();
            testEvent1.Guid = testEvent1Guid;
            testEvent1.Name = "Test Event 1";
            eventItemService.Add(testEvent1);

            // Add an occurrence with a future schedule and no NextDateTime value.
            // When the cleanup task executes, this should be updated to the next occurrence after the reference date.
            var testOccurrence11 = new EventItemOccurrence();

            testOccurrence11.ScheduleId        = schedule.Id;
            testOccurrence11.Guid              = testEventOccurrence11Guid;
            testOccurrence11.NextStartDateTime = null;
            testEvent1.EventItemOccurrences.Add(testOccurrence11);

            // Add an occurrence with a NextDateTime that is prior to the reference date.
            // When the cleanup task executes, this should be updated to the next occurrence after the reference date.
            var testOccurrence12 = new EventItemOccurrence();

            testOccurrence12.ScheduleId        = schedule.Id;
            testOccurrence12.Guid              = testEventOccurrence12Guid;
            testOccurrence12.NextStartDateTime = referenceDate.AddDays(-1);
            testEvent1.EventItemOccurrences.Add(testOccurrence12);

            // Add an occurrence with a NextDateTime and an inactive Schedule.
            // When the cleanup task executes, the NextDateTime should be set to null.
            var testOccurrence13 = new EventItemOccurrence();

            testOccurrence13.ScheduleId        = scheduleInactive.Id;
            testOccurrence13.Guid              = testEventOccurrence13Guid;
            testOccurrence13.NextStartDateTime = referenceDate.AddDays(7);
            testEvent1.EventItemOccurrences.Add(testOccurrence13);

            // Test Event 2 (inactive)
            var testEvent2 = eventItemService.Get(testEvent2Guid);

            if (testEvent2 != null)
            {
                eventItemService.Delete(testEvent2);
                rockContext.SaveChanges();
            }

            testEvent2          = new EventItem();
            testEvent2.Guid     = testEvent2Guid;
            testEvent2.Name     = "Test Event 2";
            testEvent2.IsActive = false;
            eventItemService.Add(testEvent2);

            // Add an occurrence with a future schedule and a NextDateTime value.
            // When the cleanup task executes, the NextDateTime should be set to null.
            var testOccurrence21 = new EventItemOccurrence();

            testOccurrence21.ScheduleId        = schedule.Id;
            testOccurrence21.Guid              = testEventOccurrence21Guid;
            testOccurrence21.NextStartDateTime = referenceDate;
            testEvent2.EventItemOccurrences.Add(testOccurrence21);

            // Save changes without triggering the pre-save, to avoid updating the NextEventDate field.
            rockContext.SaveChanges(new SaveChangesArgs {
                DisablePrePostProcessing = true
            });

            // Run the cleanup task to verify the results for the reference date.
            RunRockCleanupTaskUpdateEventNextOccurrenceDatesAndVerify(referenceDate);

            // Re-run the task to verify that the results are adjusted for the current date.
            RunRockCleanupTaskUpdateEventNextOccurrenceDatesAndVerify(RockDateTime.Now);
        }
Beispiel #33
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() )
            {
                EventItemService eventItemService = new EventItemService( rockContext );
                EventItem eventItem = eventItemService.Get( int.Parse( hfEventItemId.Value ) );

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

                    eventItemService.Delete( eventItem );

                    rockContext.SaveChanges();
                }
            }

            NavigateToParentPage();
        }
Beispiel #34
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 )
        {
            EventItem eventItem = null;

            using ( var rockContext = new RockContext() )
            {
                var validationMessages = new List<string>();

                var eventItemService = new EventItemService( rockContext );
                var eventCalendarItemService = new EventCalendarItemService( rockContext );
                var eventItemAudienceService = new EventItemAudienceService( rockContext );

                int eventItemId = hfEventItemId.ValueAsInt();
                if ( eventItemId != 0 )
                {
                    eventItem = eventItemService
                        .Queryable( "EventItemAudiences,EventItemOccurrences.Linkages,EventItemOccurrences" )
                        .Where( i => i.Id == eventItemId )
                        .FirstOrDefault();
                }

                if ( eventItem == null )
                {
                    eventItem = new EventItem();
                    eventItemService.Add( eventItem );
                }

                eventItem.Name = tbName.Text;
                eventItem.IsActive = cbIsActive.Checked;

                if ( !eventItem.IsApproved && cbIsApproved.Checked )
                {
                    eventItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    eventItem.ApprovedOnDateTime = RockDateTime.Now;
                }
                eventItem.IsApproved = cbIsApproved.Checked;
                if ( !eventItem.IsApproved )
                {
                    eventItem.ApprovedByPersonAliasId = null;
                    eventItem.ApprovedByPersonAlias = null;
                    eventItem.ApprovedOnDateTime = null;
                }
                eventItem.Description = htmlDescription.Text;
                eventItem.Summary = tbSummary.Text;
                eventItem.DetailsUrl = tbDetailUrl.Text;

                int? orphanedImageId = null;
                if ( eventItem.PhotoId != imgupPhoto.BinaryFileId )
                {
                    orphanedImageId = eventItem.PhotoId;
                    eventItem.PhotoId = imgupPhoto.BinaryFileId;
                }

                // Remove any audiences that were removed in the UI
                foreach ( var eventItemAudience in eventItem.EventItemAudiences.Where( r => !AudiencesState.Contains( r.DefinedValueId ) ).ToList() )
                {
                    eventItem.EventItemAudiences.Remove( eventItemAudience );
                    eventItemAudienceService.Delete( eventItemAudience );
                }

                // Add or Update audiences from the UI
                foreach ( int audienceId in AudiencesState )
                {
                    EventItemAudience eventItemAudience = eventItem.EventItemAudiences.Where( a => a.DefinedValueId == audienceId ).FirstOrDefault();
                    if ( eventItemAudience == null )
                    {
                        eventItemAudience = new EventItemAudience();
                        eventItemAudience.DefinedValueId = audienceId;
                        eventItem.EventItemAudiences.Add( eventItemAudience );
                    }
                }

                // remove any calendar items that removed in the UI
                var calendarIds = new List<int>();
                calendarIds.AddRange( cblCalendars.SelectedValuesAsInt );
                var uiCalendarGuids = ItemsState.Where( i => calendarIds.Contains( i.EventCalendarId ) ).Select( a => a.Guid );
                foreach ( var eventCalendarItem in eventItem.EventCalendarItems.Where( a => !uiCalendarGuids.Contains( a.Guid ) ).ToList() )
                {
                    // Make sure user is authorized to remove calendar (they may not have seen every calendar due to security)
                    if ( UserCanEdit || eventCalendarItem.EventCalendar.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                    {
                        eventItem.EventCalendarItems.Remove( eventCalendarItem );
                        eventCalendarItemService.Delete( eventCalendarItem );
                    }
                }

                // Add or Update calendar items from the UI
                foreach ( var calendar in ItemsState.Where( i => calendarIds.Contains( i.EventCalendarId ) ) )
                {
                    var eventCalendarItem = eventItem.EventCalendarItems.Where( a => a.Guid == calendar.Guid ).FirstOrDefault();
                    if ( eventCalendarItem == null )
                    {
                        eventCalendarItem = new EventCalendarItem();
                        eventItem.EventCalendarItems.Add( eventCalendarItem );
                    }
                    eventCalendarItem.CopyPropertiesFrom( calendar );
                }

                if ( !eventItem.EventCalendarItems.Any() )
                {
                    validationMessages.Add( "At least one calendar is required." );
                }

                if ( !Page.IsValid )
                {
                    return;
                }

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

                if ( validationMessages.Any() )
                {
                    nbValidation.Text = "Please Correct the Following<ul><li>" + validationMessages.AsDelimited( "</li><li>" ) + "</li></ul>";
                    nbValidation.Visible = true;
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction( () =>
                {
                    rockContext.SaveChanges();
                    foreach ( EventCalendarItem eventCalendarItem in eventItem.EventCalendarItems )
                    {
                        eventCalendarItem.LoadAttributes();
                        Rock.Attribute.Helper.GetEditValues( phAttributes, eventCalendarItem );
                        eventCalendarItem.SaveAttributeValues();
                    }

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

                // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
                var qryParams = new Dictionary<string, string>();
                if ( _calendarId.HasValue )
                {
                    qryParams["EventCalendarId"] = _calendarId.Value.ToString();
                }
                qryParams["EventItemId"] = eventItem.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
        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>";
            }
        }
Beispiel #36
0
 /// <summary>
 /// Reads new values entered by the user for the field
 /// </summary>
 /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param>
 /// <param name="configurationValues"></param>
 /// <returns></returns>
 public override string GetEditValue( Control control, Dictionary<string, ConfigurationValue> configurationValues )
 {
     if ( control != null && control is EventItemPicker )
     {
         int id = int.MinValue;
         if ( Int32.TryParse( ( (EventItemPicker)control ).SelectedValue, out id ) )
         {
             using ( var rockContext = new RockContext() )
             {
                 var eventItem = new EventItemService( rockContext ).Get( id );
                 if ( eventItem != null )
                 {
                     return eventItem.Guid.ToString();
                 }
             }
         }
     }
     return null;
 }
Beispiel #37
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            EventItem eventItem = null;

            using (var rockContext = new RockContext())
            {
                var validationMessages = new List <string>();

                var eventItemService         = new EventItemService(rockContext);
                var eventCalendarItemService = new EventCalendarItemService(rockContext);
                var eventItemAudienceService = new EventItemAudienceService(rockContext);

                int eventItemId = hfEventItemId.ValueAsInt();
                if (eventItemId != 0)
                {
                    eventItem = eventItemService
                                .Queryable("EventItemAudiences,EventItemOccurrences.Linkages,EventItemOccurrences")
                                .Where(i => i.Id == eventItemId)
                                .FirstOrDefault();
                }

                if (eventItem == null)
                {
                    eventItem = new EventItem();
                    eventItemService.Add(eventItem);
                }

                eventItem.Name     = tbName.Text;
                eventItem.IsActive = cbIsActive.Checked;

                if (!eventItem.IsApproved && cbIsApproved.Checked)
                {
                    eventItem.ApprovedByPersonAliasId = CurrentPersonAliasId;
                    eventItem.ApprovedOnDateTime      = RockDateTime.Now;
                }
                eventItem.IsApproved = cbIsApproved.Checked;
                if (!eventItem.IsApproved)
                {
                    eventItem.ApprovedByPersonAliasId = null;
                    eventItem.ApprovedByPersonAlias   = null;
                    eventItem.ApprovedOnDateTime      = null;
                }
                eventItem.Description = htmlDescription.Text;
                eventItem.Summary     = tbSummary.Text;
                eventItem.DetailsUrl  = tbDetailUrl.Text;

                int?orphanedImageId = null;
                if (eventItem.PhotoId != imgupPhoto.BinaryFileId)
                {
                    orphanedImageId   = eventItem.PhotoId;
                    eventItem.PhotoId = imgupPhoto.BinaryFileId;
                }

                // Remove any audiences that were removed in the UI
                foreach (var eventItemAudience in eventItem.EventItemAudiences.Where(r => !AudiencesState.Contains(r.DefinedValueId)).ToList())
                {
                    eventItem.EventItemAudiences.Remove(eventItemAudience);
                    eventItemAudienceService.Delete(eventItemAudience);
                }

                // Add or Update audiences from the UI
                foreach (int audienceId in AudiencesState)
                {
                    EventItemAudience eventItemAudience = eventItem.EventItemAudiences.Where(a => a.DefinedValueId == audienceId).FirstOrDefault();
                    if (eventItemAudience == null)
                    {
                        eventItemAudience = new EventItemAudience();
                        eventItemAudience.DefinedValueId = audienceId;
                        eventItem.EventItemAudiences.Add(eventItemAudience);
                    }
                }

                // remove any calendar items that removed in the UI
                var calendarIds = new List <int>();
                calendarIds.AddRange(cblCalendars.SelectedValuesAsInt);
                var uiCalendarGuids = ItemsState.Where(i => calendarIds.Contains(i.EventCalendarId)).Select(a => a.Guid);
                foreach (var eventCalendarItem in eventItem.EventCalendarItems.Where(a => !uiCalendarGuids.Contains(a.Guid)).ToList())
                {
                    // Make sure user is authorized to remove calendar (they may not have seen every calendar due to security)
                    if (UserCanEdit || eventCalendarItem.EventCalendar.IsAuthorized(Authorization.EDIT, CurrentPerson))
                    {
                        eventItem.EventCalendarItems.Remove(eventCalendarItem);
                        eventCalendarItemService.Delete(eventCalendarItem);
                    }
                }

                // Add or Update calendar items from the UI
                foreach (var calendar in ItemsState.Where(i => calendarIds.Contains(i.EventCalendarId)))
                {
                    var eventCalendarItem = eventItem.EventCalendarItems.Where(a => a.Guid == calendar.Guid).FirstOrDefault();
                    if (eventCalendarItem == null)
                    {
                        eventCalendarItem = new EventCalendarItem();
                        eventItem.EventCalendarItems.Add(eventCalendarItem);
                    }
                    eventCalendarItem.CopyPropertiesFrom(calendar);
                }

                if (!eventItem.EventCalendarItems.Any())
                {
                    validationMessages.Add("At least one calendar is required.");
                }

                if (!Page.IsValid)
                {
                    return;
                }

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

                if (validationMessages.Any())
                {
                    nbValidation.Text    = "Please Correct the Following<ul><li>" + validationMessages.AsDelimited("</li><li>") + "</li></ul>";
                    nbValidation.Visible = true;
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    foreach (EventCalendarItem eventCalendarItem in eventItem.EventCalendarItems)
                    {
                        eventCalendarItem.LoadAttributes();
                        Rock.Attribute.Helper.GetEditValues(phAttributes, eventCalendarItem);
                        eventCalendarItem.SaveAttributeValues();
                    }

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


                // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
                var qryParams = new Dictionary <string, string>();
                if (_calendarId.HasValue)
                {
                    qryParams["EventCalendarId"] = _calendarId.Value.ToString();
                }
                qryParams["EventItemId"] = eventItem.Id.ToString();
                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
Beispiel #38
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() )
            {
                EventItemService eventItemService = new EventItemService( rockContext );
                EventItem eventItem = eventItemService.Get( int.Parse( hfEventItemId.Value ) );

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

                    eventItemService.Delete( eventItem );

                    rockContext.SaveChanges();
                }
            }

            var qryParams = new Dictionary<string, string>();
            if ( _calendarId.HasValue )
            {
                qryParams.Add( "EventCalendarId", _calendarId.Value.ToString() );
            }
            NavigateToParentPage( qryParams );
        }
Beispiel #39
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? eventItemId = PageParameter( pageReference, "EventItemId" ).AsIntegerOrNull();
            if ( eventItemId != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    EventItem eventItem = new EventItemService( rockContext ).Get( eventItemId.Value );
                    if ( eventItem != null )
                    {
                        breadCrumbs.Add( new BreadCrumb( eventItem.Name, pageReference ) );
                    }
                    else
                    {
                        breadCrumbs.Add( new BreadCrumb( "New Calendar Item", pageReference ) );
                    }
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
Beispiel #40
0
        /// <summary>
        /// Gets the eventItem.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        /// <returns></returns>
        private EventItem GetEventItem( int eventItemId, RockContext rockContext = null )
        {
            string key = string.Format( "EventItem:{0}", eventItemId );
            EventItem eventItem = RockPage.GetSharedItem( key ) as EventItem;
            if ( eventItem == null )
            {
                rockContext = rockContext ?? new RockContext();
                eventItem = new EventItemService( rockContext ).Queryable()
                    .Where( e => e.Id == eventItemId )
                    .FirstOrDefault();
                RockPage.SaveSharedItem( key, eventItem );
            }

            return eventItem;
        }
        private void LoadContent()
        {
            Person person = null;
            EventItem eventItem = null;

            // get person
            Guid personGuid = Guid.Empty;
            if ( Request["PersonGuid"] != null )
            {
                personGuid = Request["PersonGuid"].AsGuid();

                person = new PersonService( _rockContext ).Get( personGuid );
            }

            if ( person == null )
            {
                lErrors.Text = "<div class='alert alert-warning'>Invalid person guid was passed.</div>";
                return;
            }

            // get calendar item id

            if ( Request["EventItemId"] != null )
            {
                int calendarItemId = 0;
                int.TryParse( Request["EventItemId"], out calendarItemId );

                eventItem = new EventItemService( _rockContext ).Get( calendarItemId );
            }

            if ( eventItem == null )
            {
                lErrors.Text = "<div class='alert alert-warning'>Invalid calendar item id.</div>";
                return;
            }

            lEventIntro.Text = string.Format( "<h4>Select An Upcoming {0}</h4><p>", eventItem.Name );

            lBlockTitle.Text = string.Format( "{0} Registration", eventItem.Name );

            var families = person.GetFamilies();
            var familyMembers = person.GetFamilyMembers().ToList();

            // sort family members
            familyMembers = familyMembers.OrderBy( f => f.GroupRole.Order )
                                    .OrderBy( f => f.Person.Gender ).ToList();

            if ( _campusId == 0 )
            {
                _campusId = families.FirstOrDefault().CampusId ?? 1;
                cpCampus.SelectedCampusId = _campusId;
            }

            // enter reminder email
            if (! string.IsNullOrWhiteSpace(person.Email))
            {
                ebEmailReminder.Text = person.Email;
            } else
            {
                // find email from one of the family members
                ebEmailReminder.Text = familyMembers.Where( f => f.Person.Email != "" ).Select( f => f.Person.Email ).FirstOrDefault();
            }

            // add family registrants
            if ( GetAttributeValue( "IncludeFamilyMembers" ).AsBoolean() )
            {
                cblRegistrants.DataSource = familyMembers.Select( f => f.Person );
                cblRegistrants.DataValueField = "PrimaryAliasId";
                cblRegistrants.DataTextField = "FullName";
                cblRegistrants.DataBind();
            }

            cblRegistrants.Items.Insert( 0, new ListItem( person.FullName, person.PrimaryAliasId.ToString() ) );
            cblRegistrants.SelectedIndex = 0;

            if ( cblRegistrants.Items.Count == 1 )
            {
                cblRegistrants.Visible = false;
            }

            // get list of upcoming events for the current campus
            var eventItemOccurrences = eventItem.EventItemOccurrences
                                    .Where( c => c.CampusId == _campusId || c.CampusId == null).ToList();

            List<EventSummary> eventSummaries = new List<EventSummary>();

            // go through campus event schedules looking for upcoming dates
            foreach ( var eventItemOccurrence in eventItemOccurrences )
            {
                var startDate = eventItemOccurrence.GetFirstStartDateTime();

                if ( startDate.HasValue && startDate > RockDateTime.Now )
                {
                    EventSummary eventSummary = new EventSummary();
                    eventSummary.StartDate = startDate.Value;
                    eventSummary.Name = eventItemOccurrence.EventItem.Name;
                    eventSummary.Location = eventItemOccurrence.Location;
                    eventSummary.Id = eventItemOccurrence.Id;

                    if ( eventItemOccurrence.Campus != null )
                    {
                        eventSummary.Campus = eventItemOccurrence.Campus.Name;
                    }
                    else
                    {
                        eventSummary.Campus = "All";
                    }

                    eventSummary.ContactEmail = eventItemOccurrence.ContactEmail;
                    eventSummary.ContactPhone = eventItemOccurrence.ContactPhone;

                    if ( eventItemOccurrence.ContactPersonAlias != null )
                    {
                        eventSummary.ContactName = eventItemOccurrence.ContactPersonAlias.Person.FullName;
                    }
                    else
                    {
                        eventSummary.ContactName = string.Empty;
                    }

                    eventSummary.Note = eventItemOccurrence.Note;

                    eventSummaries.Add( eventSummary );
                }

            }

            int maxDisplayItems = GetAttributeValue( "MaxDisplayEvents" ).AsInteger();

            eventSummaries = eventSummaries.OrderBy( e => e.StartDate ).Take( maxDisplayItems ).ToList();
            rptEvents.DataSource = eventSummaries;
            rptEvents.DataBind();

            if ( eventSummaries.Count > 0 )
            {
                lbRegister.Enabled = true;
                lEventIntro.Visible = true;
                cblRegistrants.Visible = true;
                lbRegister.Visible = true;
                lMessages.Text = string.Empty;
                hfSelectedEventId.Value = eventSummaries.FirstOrDefault().Id.ToString();
            }
            else
            {
                lbRegister.Visible = false;
                lEventIntro.Visible = false;
                cblRegistrants.Visible = false;
                var campus = CampusCache.Read( _campusId );
                lMessages.Text = string.Format( "<div class='alert alert-info'>There are no {0} events for the {1} campus in the next {2} days.</div>",
                                    eventItem.Name,
                                    campus != null ? campus.Name : string.Empty,
                                    _daysInRange.ToString() );
            }
        }
 /// <summary>
 /// Handles the Edit event of the gEventCalendarItems 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 gEventCalendarItems_Edit( object sender, RowEventArgs e )
 {
     using ( RockContext rockContext = new RockContext() )
     {
         EventItemService eventItemService = new EventItemService( rockContext );
         EventItem eventItem = eventItemService.Get( e.RowKeyId );
         if ( eventItem != null )
         {
             var qryParams = new Dictionary<string, string>();
             qryParams.Add( "EventCalendarId", _eventCalendar.Id.ToString() );
             qryParams.Add( "EventItemId", eventItem.Id.ToString() );
             NavigateToLinkedPage( "DetailPage", qryParams );
         }
     }
 }
Beispiel #43
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 eventItem = new EventItemService( rockContext ).Get( hfEventItemId.Value.AsInteger() );

            ShowEditDetails( eventItem );
        }
        /// <summary>
        /// Handles the Click event of the DeleteEventCalendarItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param>
        protected void DeleteEventCalendarItem_Click( object sender, Rock.Web.UI.Controls.RowEventArgs e )
        {
            using ( RockContext rockContext = new RockContext() )
            {
                EventItemService eventItemService = new EventItemService( rockContext );
                EventItem eventItem = eventItemService.Get( e.RowKeyId );
                if ( eventItem != null )
                {
                    if ( _canEdit )
                    {
                        string errorMessage;
                        if ( !eventItemService.CanDelete( eventItem, out errorMessage ) )
                        {
                            mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                            return;
                        }

                        eventItemService.Delete( eventItem );
                        rockContext.SaveChanges();
                    }
                    else
                    {
                        mdGridWarning.Show( "You are not authorized to delete this calendar item", ModalAlertType.Warning );
                    }
                }
            }

            BindEventCalendarItemsGrid();
        }
        /// <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 );
        }