/// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _firstDayOfWeek = GetAttributeValue("StartofWeekDay").ConvertToEnum <DayOfWeek>();

            var eventCalendar = new EventCalendarService(new RockContext()).Get(GetAttributeValue("EventCalendar").AsGuid());

            if (eventCalendar != null)
            {
                _calendarId   = eventCalendar.Id;
                _calendarName = eventCalendar.Name;
            }

            CampusPanelOpen     = GetAttributeValue("CampusFilterDisplayMode") == "3";
            CampusPanelClosed   = GetAttributeValue("CampusFilterDisplayMode") == "4";
            CategoryPanelOpen   = !String.IsNullOrWhiteSpace(GetAttributeValue("FilterCategories")) && GetAttributeValue("CategoryFilterDisplayMode") == "3";
            CategoryPanelClosed = !String.IsNullOrWhiteSpace(GetAttributeValue("FilterCategories")) && GetAttributeValue("CategoryFilterDisplayMode") == "4";

            FeaturedEventsPage = GetAttributeValue("FeaturedEventsPage");

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upnlContent);
        }
Esempio n. 2
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())
            {
                EventCalendarService eventCalendarService = new EventCalendarService(rockContext);
                AuthService          authService          = new AuthService(rockContext);
                EventCalendar        eventCalendar        = eventCalendarService.Get(int.Parse(hfEventCalendarId.Value));

                if (eventCalendar != null)
                {
                    bool adminAllowed = UserCanAdministrate || eventCalendar.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson);
                    if (!adminAllowed)
                    {
                        mdDeleteWarning.Show("You are not authorized to delete this calendar.", ModalAlertType.Information);
                        return;
                    }

                    string errorMessage;
                    if (!eventCalendarService.CanDelete(eventCalendar, out errorMessage))
                    {
                        mdDeleteWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    eventCalendarService.Delete(eventCalendar);

                    rockContext.SaveChanges();
                }
            }

            NavigateToParentPage();
        }
Esempio n. 3
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 page reference.</param>
        /// <returns></returns>
        public override List <BreadCrumb> GetBreadCrumbs(PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

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

            if (eventCalendarId != null)
            {
                EventCalendar eventCalendar = new EventCalendarService(new RockContext()).Get(eventCalendarId.Value);
                if (eventCalendar != null)
                {
                    breadCrumbs.Add(new BreadCrumb(eventCalendar.Name, pageReference));
                }
                else
                {
                    breadCrumbs.Add(new BreadCrumb("New Event Calendar", pageReference));
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return(breadCrumbs);
        }
Esempio n. 4
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)
            {
                ShowDetail(PageParameter("EventCalendarId").AsInteger());
            }
            else
            {
                if (pnlDetails.Visible)
                {
                    var           rockContext = new RockContext();
                    EventCalendar eventCalendar;
                    int?          itemId = PageParameter("EventCalendarId").AsIntegerOrNull();
                    if (itemId.HasValue && itemId > 0)
                    {
                        eventCalendar = new EventCalendarService(rockContext).Get(itemId.Value);
                    }
                    else
                    {
                        eventCalendar = new EventCalendar {
                            Id = 0
                        };
                    }

                    eventCalendar.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls(eventCalendar, phAttributes, false, BlockValidationGroup);
                }

                ShowDialog();
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Ensure the current user is authorized to view the calendar. If all are allowed then current user is not evaluated.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private bool ValidateSecurity(HttpContext context)
        {
            int calendarId;

            if (request.QueryString["calendarid"] == null || !int.TryParse(request.QueryString["calendarId"], out calendarId))
            {
                SendNotAuthorized(context);
                return(false);
            }

            RockContext          rockContext          = new RockContext();
            EventCalendarService eventCalendarService = new EventCalendarService(rockContext);
            EventCalendar        eventCalendar        = eventCalendarService.Get(calendarId);

            if (eventCalendar == null)
            {
                SendBadRequest(context);
                return(false);
            }


            // Need to replace CurrentUser with the result of a person token, in the meantime this will always create a null person unless directly downloadng the ical when logged into the site
            UserLogin currentUser   = new UserLoginService(rockContext).GetByUserName(UserLogin.GetCurrentUserName());
            Person    currentPerson = currentUser != null ? currentUser.Person : null;
            var       isAuthorized  = eventCalendar.IsAuthorized(Rock.Security.Authorization.VIEW, currentPerson);

            if (isAuthorized)
            {
                return(true);
            }

            SendNotAuthorized(context);
            return(false);
        }
Esempio n. 6
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 eventCalendar = new EventCalendarService(rockContext).Get(hfEventCalendarId.Value.AsInteger());

            LoadStateDetails(eventCalendar, rockContext);
            ShowEditDetails(eventCalendar, rockContext);
        }
        public void EventCalendarTest()
        {
            EventCalendarService newsService = new EventCalendarService("http://www.idx.co.id");

            var data = newsService.EventCalendar("umbraco/Surface/Home/GetCalendar?range=m&date=20180509");

            Assert.Greater(data.Results.Count(), 0);
            Console.WriteLine(data.Results.Count());
        }
Esempio n. 8
0
        private static int LoadByGuid2(Guid guid, RockContext rockContext)
        {
            var eventCalendarService = new EventCalendarService(rockContext);

            return(eventCalendarService
                   .Queryable().AsNoTracking()
                   .Where(c => c.Guid.Equals(guid))
                   .Select(c => c.Id)
                   .FirstOrDefault());
        }
        private EventCalendar ResolveCalendarSettingOrThrow(RockContext rockContext, string calendarSettingValue)
        {
            var calendarService = new EventCalendarService(rockContext);

            EventCalendar calendar = null;

            // Verify that a calendar reference has been provided.
            if (string.IsNullOrWhiteSpace(calendarSettingValue))
            {
                throw new Exception($"A calendar reference must be specified.");
            }

            // Get by ID.
            var calendarId = calendarSettingValue.AsIntegerOrNull();

            if (calendarId != null)
            {
                calendar = calendarService.Get(calendarId.Value);
            }

            // Get by Guid.
            if (calendar == null)
            {
                var calendarGuid = calendarSettingValue.AsGuidOrNull();

                if (calendarGuid != null)
                {
                    calendar = calendarService.Get(calendarGuid.Value);
                }
            }

            // Get By Name.
            if (calendar == null)
            {
                var calendarName = calendarSettingValue.ToString();

                if (!string.IsNullOrWhiteSpace(calendarName))
                {
                    calendar = calendarService.Queryable()
                               .Where(x => x.Name != null && x.Name.Equals(calendarName, StringComparison.OrdinalIgnoreCase))
                               .FirstOrDefault();
                }
            }

            if (calendar == null)
            {
                throw new Exception($"Cannot find a calendar matching the reference \"{ calendarSettingValue }\".");
            }

            return(calendar);
        }
Esempio n. 10
0
        private static EventCalendarCache LoadById2(int id, RockContext rockContext)
        {
            var eventCalendarService = new EventCalendarService(rockContext);
            var eventCalendarModel   = eventCalendarService
                                       .Queryable().AsNoTracking()
                                       .FirstOrDefault(c => c.Id == id);

            if (eventCalendarModel != null)
            {
                return(new EventCalendarCache(eventCalendarModel));
            }

            return(null);
        }
Esempio n. 11
0
        /// <summary>
        /// Gets the event calendar.
        /// </summary>
        /// <param name="eventCalendarId">The event calendar identifier.</param>
        /// <returns></returns>
        private EventCalendar GetEventCalendar(int eventCalendarId, RockContext rockContext = null)
        {
            string        key           = string.Format("EventCalendar:{0}", eventCalendarId);
            EventCalendar eventCalendar = RockPage.GetSharedItem(key) as EventCalendar;

            if (eventCalendar == null)
            {
                rockContext   = rockContext ?? new RockContext();
                eventCalendar = new EventCalendarService(rockContext).Queryable()
                                .Where(c => c.Id == eventCalendarId)
                                .FirstOrDefault();
                RockPage.SaveSharedItem(key, eventCalendar);
            }

            return(eventCalendar);
        }
        public override MobileBlock GetMobile(string parameter)
        {
            _firstDayOfWeek = GetAttributeValue("StartofWeekDay").ConvertToEnum <DayOfWeek>();

            var eventCalendar = new EventCalendarService(new RockContext()).Get(GetAttributeValue("EventCalendar").AsGuid());

            if (eventCalendar != null)
            {
                _calendarId   = eventCalendar.Id;
                _calendarName = eventCalendar.Name;
            }

            CampusPanelOpen     = GetAttributeValue("CampusFilterDisplayMode") == "3";
            CampusPanelClosed   = GetAttributeValue("CampusFilterDisplayMode") == "4";
            CategoryPanelOpen   = !String.IsNullOrWhiteSpace(GetAttributeValue("FilterCategories")) && GetAttributeValue("CategoryFilterDisplayMode") == "3";
            CategoryPanelClosed = !String.IsNullOrWhiteSpace(GetAttributeValue("FilterCategories")) && GetAttributeValue("CategoryFilterDisplayMode") == "4";

            AvalancheUtilities.SetActionItems(GetAttributeValue("ActionItem"),
                                              CustomAttributes,
                                              CurrentPerson, AvalancheUtilities.GetMergeFields(CurrentPerson),
                                              GetAttributeValue("EnabledLavaCommands"),
                                              parameter);

            var valueGuid = GetAttributeValue("Component");
            var value     = DefinedValueCache.Read(valueGuid);

            if (value != null)
            {
                CustomAttributes["Component"] = value.GetAttributeValue("ComponentType");
            }


            var data = BindData();

            CustomAttributes["Content"]        = data;
            CustomAttributes["InitialRequest"] = parameter;

            return(new MobileBlock()
            {
                BlockType = "Avalanche.Blocks.ListViewBlock",
                Attributes = CustomAttributes
            });
        }
Esempio n. 13
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)
            {
                var calendarEventId = PageParameter("EventCalendarId").AsInteger();

                // Set URL in feed button
                var globalAttributes = GlobalAttributesCache.Get();
                btnCopyToClipboard.Attributes["data-clipboard-text"] = string.Format("{0}GetEventCalendarFeed.ashx?CalendarId={1}", globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash(), calendarEventId);
                btnCopyToClipboard.Disabled = false;


                ShowDetail(calendarEventId);
            }
            else
            {
                if (pnlDetails.Visible)
                {
                    var           rockContext = new RockContext();
                    EventCalendar eventCalendar;
                    int?          itemId = PageParameter("EventCalendarId").AsIntegerOrNull();
                    if (itemId.HasValue && itemId > 0)
                    {
                        eventCalendar = new EventCalendarService(rockContext).Get(itemId.Value);
                    }
                    else
                    {
                        eventCalendar = new EventCalendar {
                            Id = 0
                        };
                    }

                    eventCalendar.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls(eventCalendar, phAttributes, false, BlockValidationGroup);
                }

                ShowDialog();
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Ensure the current user is authorized to view the calendar. If all are allowed then current user is not evaluated.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private bool ValidateSecurity(HttpContext context)
        {
            int calendarId;

            if (request.QueryString["calendarid"] == null || !int.TryParse(request.QueryString["calendarId"], out calendarId))
            {
                SendNotAuthorized(context);
                return(false);
            }

            RockContext          rockContext          = new RockContext();
            EventCalendarService eventCalendarService = new EventCalendarService(rockContext);
            EventCalendar        eventCalendar        = eventCalendarService.Get(calendarId);

            if (eventCalendar == null)
            {
                SendBadRequest(context);
                return(false);
            }

            // If this is a public calendar then just return true
            if (eventCalendar.IsAllowedByDefault("View"))
            {
                return(true);
            }

            UserLogin currentUser   = new UserLoginService(rockContext).GetByUserName(UserLogin.GetCurrentUserName());
            Person    currentPerson = currentUser != null ? currentUser.Person : null;

            if (currentPerson != null && eventCalendar.IsAuthorized(Rock.Security.Authorization.VIEW, currentPerson))
            {
                return(true);
            }

            SendNotAuthorized(context);
            return(false);
        }
Esempio n. 15
0
        /// <summary>
        /// Shows the item attributes.
        /// </summary>
        private void ShowItemAttributes()
        {
            var eventCalendarList = new List <int> {
                (_calendarId ?? 0)
            };

            eventCalendarList.AddRange(cblCalendars.SelectedValuesAsInt);

            wpAttributes.Visible = false;
            phAttributes.Controls.Clear();

            using (var rockContext = new RockContext())
            {
                var eventCalendarService = new EventCalendarService(rockContext);

                foreach (int eventCalendarId in eventCalendarList.Distinct())
                {
                    EventCalendarItem eventCalendarItem = ItemsState.FirstOrDefault(i => i.EventCalendarId == eventCalendarId);
                    if (eventCalendarItem == null)
                    {
                        eventCalendarItem = new EventCalendarItem();
                        eventCalendarItem.EventCalendarId = eventCalendarId;
                        ItemsState.Add(eventCalendarItem);
                    }

                    eventCalendarItem.LoadAttributes();

                    if (eventCalendarItem.Attributes.Count > 0)
                    {
                        wpAttributes.Visible = true;
                        phAttributes.Controls.Add(new LiteralControl(String.Format("<h3>{0}</h3>", eventCalendarService.Get(eventCalendarId).Name)));
                        PlaceHolder phcalAttributes = new PlaceHolder();
                        Rock.Attribute.Helper.AddEditControls(eventCalendarItem, phAttributes, true, BlockValidationGroup);
                    }
                }
            }
        }
Esempio n. 16
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.");
        }
Esempio n. 17
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 page reference.</param>
        /// <returns></returns>
        public override List<BreadCrumb> GetBreadCrumbs( PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();

            int? eventCalendarId = PageParameter( pageReference, "EventCalendarId" ).AsIntegerOrNull();
            if ( eventCalendarId != null )
            {
                EventCalendar eventCalendar = new EventCalendarService( new RockContext() ).Get( eventCalendarId.Value );
                if ( eventCalendar != null )
                {
                    breadCrumbs.Add( new BreadCrumb( eventCalendar.Name, pageReference ) );
                }
                else
                {
                    breadCrumbs.Add( new BreadCrumb( "New Event Calendar", pageReference ) );
                }
            }
            else
            {
                // don't show a breadcrumb if we don't have a pageparam to work with
            }

            return breadCrumbs;
        }
Esempio n. 18
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);
        }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        public void ShowDetail( int eventItemOccurrenceId )
        {
            pnlDetails.Visible = true;

            EventItemOccurrence eventItemOccurrence = null;

            var rockContext = new RockContext();

            bool canEdit = UserCanEdit;

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

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

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

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;

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

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

                if ( !eventItemOccurrenceId.Equals( 0))
                {
                    ShowReadonlyDetails( eventItemOccurrence );
                }
                else
                {
                    ShowEditDetails( eventItemOccurrence );
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext = new RockContext();
            var eventCalendarGuid = GetAttributeValue( "EventCalendar" ).AsGuid();
            var eventCalendar = new EventCalendarService( rockContext ).Get( eventCalendarGuid );

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

            var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext );

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

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

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

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

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

            CalendarEventDates = new List<DateTime>();

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

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

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

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

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

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

            // show debug info
            if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
            {
                lDebug.Visible = true;
                lDebug.Text = mergeFields.lavaDebugInfo();
            }
            else
            {
                lDebug.Visible = false;
                lDebug.Text = string.Empty;
            }
        }
Esempio n. 21
0
        public object GetEvents(DateTime beginDate, DateTime endDate)
        {
            using (var rockContext = new RockContext())
            {
                var eventCalendar = new EventCalendarService(rockContext).Get(Calendar ?? Guid.Empty);
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

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

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

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

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

                var lavaTemplate = CreateLavaTemplate();

                var commonMergeFields = new CommonMergeFieldsOptions
                {
                    GetLegacyGlobalMergeFields = false
                };

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

                var output = lavaTemplate.ResolveMergeFields(mergeFields);

                return(ActionOk(new StringContent(output, Encoding.UTF8, "application/json")));
            }
        }
Esempio n. 22
0
        public object GetEvents(DateTime beginDate, DateTime endDate)
        {
            using (var rockContext = new RockContext())
            {
                var eventCalendar = new EventCalendarService(rockContext).Get(Calendar ?? Guid.Empty);
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

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

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

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

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

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

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

                var lavaTemplate = CreateLavaTemplate();

                var commonMergeFields = new CommonMergeFieldsOptions
                {
                    GetLegacyGlobalMergeFields = false
                };

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

                var output = lavaTemplate.ResolveMergeFields(mergeFields);

                return(ActionOk(new StringContent(output, Encoding.UTF8, "application/json")));
            }
        }
Esempio n. 23
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() )
            {
                EventCalendarService eventCalendarService = new EventCalendarService( rockContext );
                AuthService authService = new AuthService( rockContext );
                EventCalendar eventCalendar = eventCalendarService.Get( int.Parse( hfEventCalendarId.Value ) );

                if ( eventCalendar != null )
                {
                    bool adminAllowed = UserCanAdministrate || eventCalendar.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson );
                    if ( !adminAllowed )
                    {
                        mdDeleteWarning.Show( "You are not authorized to delete this calendar.", ModalAlertType.Information );
                        return;
                    }

                    string errorMessage;
                    if ( !eventCalendarService.CanDelete( eventCalendar, out errorMessage ) )
                    {
                        mdDeleteWarning.Show( errorMessage, ModalAlertType.Information );
                        return;
                    }

                    eventCalendarService.Delete( eventCalendar );

                    rockContext.SaveChanges();
                }
            }

            NavigateToParentPage();
        }
Esempio n. 24
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext       = new RockContext();
            var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid();
            var eventCalendar     = new EventCalendarService(rockContext).Get(eventCalendarGuid);

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

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

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

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

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

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

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

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

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

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

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

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

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

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

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

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

            lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
Esempio n. 25
0
        /// <summary>
        /// Loads the content.
        /// </summary>
        private void LoadContent()
        {
            var rockContext       = new RockContext();
            var eventCalendarGuid = GetAttributeValue("EventCalendar").AsGuid();
            var eventCalendar     = new EventCalendarService(rockContext).Get(eventCalendarGuid);

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

            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

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

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

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

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

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

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

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummaryKFS>();

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

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

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

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

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

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

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

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

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

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

                ParameterExpression paramExpression = service.ParameterExpression;

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

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

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

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

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

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

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

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

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

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

                        // Order the items
                        SortProperty sortProperty = null;

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

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

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

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

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

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

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

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

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

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

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

            lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
        }
Esempio n. 26
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            _firstDayOfWeek = GetAttributeValue( "StartofWeekDay" ).ConvertToEnum<DayOfWeek>();

            var eventCalendar = new EventCalendarService( new RockContext() ).Get( GetAttributeValue( "EventCalendar" ).AsGuid() );
            if ( eventCalendar != null )
            {
                _calendarId = eventCalendar.Id;
                _calendarName = eventCalendar.Name;
            }

            CampusPanelOpen = GetAttributeValue( "CampusFilterDisplayMode" ) == "3";
            CampusPanelClosed = GetAttributeValue( "CampusFilterDisplayMode" ) == "4";
            CategoryPanelOpen = !String.IsNullOrWhiteSpace( GetAttributeValue( "FilterCategories" ) ) && GetAttributeValue( "CategoryFilterDisplayMode" ) == "3";
            CategoryPanelClosed = !String.IsNullOrWhiteSpace( GetAttributeValue( "FilterCategories" ) ) && GetAttributeValue( "CategoryFilterDisplayMode" ) == "4";

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger( upnlContent );
        }
Esempio n. 27
0
        /// <summary>
        /// Shows the item attributes.
        /// </summary>
        private void ShowItemAttributes()
        {
            var eventCalendarList = new List<int> { ( _calendarId ?? 0 ) };
            eventCalendarList.AddRange( cblCalendars.SelectedValuesAsInt );

            wpAttributes.Visible = false;
            phAttributes.Controls.Clear();

            using ( var rockContext = new RockContext() )
            {
                var eventCalendarService = new EventCalendarService( rockContext );

                foreach ( int eventCalendarId in eventCalendarList.Distinct() )
                {
                    EventCalendarItem eventCalendarItem = ItemsState.FirstOrDefault( i => i.EventCalendarId == eventCalendarId );
                    if ( eventCalendarItem == null )
                    {
                        eventCalendarItem = new EventCalendarItem();
                        eventCalendarItem.EventCalendarId = eventCalendarId;
                        ItemsState.Add( eventCalendarItem );
                    }

                    eventCalendarItem.LoadAttributes();

                    if ( eventCalendarItem.Attributes.Count > 0 )
                    {
                        wpAttributes.Visible = true;
                        phAttributes.Controls.Add( new LiteralControl( String.Format( "<h3>{0}</h3>", eventCalendarService.Get( eventCalendarId ).Name ) ) );
                        PlaceHolder phcalAttributes = new PlaceHolder();
                        Rock.Attribute.Helper.AddEditControls( eventCalendarItem, phAttributes, true, BlockValidationGroup );
                    }
                }
            }
        }
Esempio n. 28
0
 public void SetUp()
 {
     _eventsManager = new Mock <IEventsManager>();
     service        = new EventCalendarService(_eventsManager.Object);
 }
Esempio n. 29
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

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

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

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

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

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

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

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

                    PageNumber = PageNumber ?? 1;

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

            divCalendars.Attributes["class"] = GetDivClass( 1 );
            divCalendar.Attributes["class"] = GetDivClass( 2 );
            divCalendarItem.Attributes["class"] = GetDivClass( 3 );
            divEventOccurrence.Attributes["class"] = GetDivClass( 4 );
            divContentItem.Attributes["class"] = GetDivClass( 5 );
        }
Esempio n. 30
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 );
        }
Esempio n. 31
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 eventCalendar = new EventCalendarService( rockContext ).Get( hfEventCalendarId.Value.AsInteger() );

            LoadStateDetails( eventCalendar, rockContext );
            ShowEditDetails( eventCalendar, rockContext );
        }
Esempio n. 32
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="eventItemId">The eventItem identifier.</param>
        public void ShowDetail(int eventItemOccurrenceId)
        {
            pnlDetails.Visible = true;

            EventItemOccurrence eventItemOccurrence = null;

            var rockContext = new RockContext();

            bool canEdit = UserCanEdit;

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

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

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

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;

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

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

                if (!eventItemOccurrenceId.Equals(0))
                {
                    ShowReadonlyDetails(eventItemOccurrence);
                }
                else
                {
                    ShowEditDetails(eventItemOccurrence);
                }
            }
        }
Esempio n. 33
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 )
        {
            EventCalendar eventCalendar;
            using ( var rockContext = new RockContext() )
            {
                EventCalendarService eventCalendarService = new EventCalendarService( rockContext );
                EventCalendarContentChannelService eventCalendarContentChannelService = new EventCalendarContentChannelService( rockContext );
                ContentChannelService contentChannelService = new ContentChannelService( rockContext );
                AttributeService attributeService = new AttributeService( rockContext );
                AttributeQualifierService qualifierService = new AttributeQualifierService( rockContext );

                int eventCalendarId = int.Parse( hfEventCalendarId.Value );

                if ( eventCalendarId == 0 )
                {
                    eventCalendar = new EventCalendar();
                    eventCalendarService.Add( eventCalendar );
                }
                else
                {
                    eventCalendar = eventCalendarService.Get( eventCalendarId );
                }

                eventCalendar.IsActive = cbActive.Checked;
                eventCalendar.Name = tbName.Text;
                eventCalendar.Description = tbDescription.Text;
                eventCalendar.IconCssClass = tbIconCssClass.Text;

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

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

                    var dbChannelGuids = eventCalendarContentChannelService.Queryable()
                        .Where( c => c.EventCalendarId == eventCalendar.Id )
                        .Select( c => c.Guid )
                        .ToList();

                    var uiChannelGuids = ContentChannelsState.Select( c => c.Key ).ToList();

                    var toDelete = eventCalendarContentChannelService
                        .Queryable()
                        .Where( c =>
                            dbChannelGuids.Contains( c.Guid ) &&
                            !uiChannelGuids.Contains( c.Guid ));

                    eventCalendarContentChannelService.DeleteRange( toDelete );
                    contentChannelService.Queryable()
                        .Where( c =>
                            uiChannelGuids.Contains( c.Guid ) &&
                            !dbChannelGuids.Contains( c.Guid ) )
                        .ToList()
                        .ForEach( c =>
                        {
                            var eventCalendarContentChannel = new EventCalendarContentChannel();
                            eventCalendarContentChannel.EventCalendarId = eventCalendar.Id;
                            eventCalendarContentChannel.ContentChannelId = c.Id;
                            eventCalendarContentChannelService.Add( eventCalendarContentChannel );
                        } );

                    rockContext.SaveChanges();

                    /* Save Attributes */
                    string qualifierValue = eventCalendar.Id.ToString();
                    SaveAttributes( new EventCalendarItem().TypeId, "EventCalendarId", qualifierValue, AttributesState, rockContext );

                    // Reload calendar and make sure that the person who may have just added a calendar has security to view/edit/administrate the calendar
                    eventCalendar = eventCalendarService.Get( eventCalendar.Id );
                    if ( eventCalendar != null )
                    {
                        if ( !eventCalendar.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                        {
                            eventCalendar.AllowPerson( Authorization.VIEW, CurrentPerson, rockContext );
                        }
                        if ( !eventCalendar.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                        {
                            eventCalendar.AllowPerson( Authorization.EDIT, CurrentPerson, rockContext );
                        }
                        if ( !eventCalendar.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ) )
                        {
                            eventCalendar.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext );
                        }
                    }

                } );
            }

            // 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>();
            qryParams["EventCalendarId"] = eventCalendar.Id.ToString();
            NavigateToPage( RockPage.Guid, qryParams );
        }
Esempio n. 34
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            _firstDayOfWeek = GetAttributeValue( "StartofWeekDay" ).ConvertToEnum<DayOfWeek>();

            var eventCalendar = new EventCalendarService( new RockContext() ).Get( GetAttributeValue( "EventCalendar" ).AsGuid() );
            if ( eventCalendar != null )
            {
                _calendarId = eventCalendar.Id;
                _calendarName = eventCalendar.Name;
            }

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger( upnlContent );
        }
Esempio n. 35
0
        /// <summary>
        /// Gets the event calendar.
        /// </summary>
        /// <param name="eventCalendarId">The event calendar identifier.</param>
        /// <returns></returns>
        private EventCalendar GetEventCalendar( int eventCalendarId, RockContext rockContext = null )
        {
            string key = string.Format( "EventCalendar:{0}", eventCalendarId );
            EventCalendar eventCalendar = RockPage.GetSharedItem( key ) as EventCalendar;
            if ( eventCalendar == null )
            {
                rockContext = rockContext ?? new RockContext();
                eventCalendar = new EventCalendarService( rockContext ).Queryable()
                    .Where( c => c.Id == eventCalendarId )
                    .FirstOrDefault();
                RockPage.SaveSharedItem( key, eventCalendar );
            }

            return eventCalendar;
        }
Esempio n. 36
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

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

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

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

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

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

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

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

                    PageNumber = PageNumber ?? 1;

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

            divCalendars.Attributes["class"]       = GetDivClass(1);
            divCalendar.Attributes["class"]        = GetDivClass(2);
            divCalendarItem.Attributes["class"]    = GetDivClass(3);
            divEventOccurrence.Attributes["class"] = GetDivClass(4);
            divContentItem.Attributes["class"]     = GetDivClass(5);
        }
Esempio n. 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)
        {
            EventCalendar eventCalendar;

            using (var rockContext = new RockContext())
            {
                EventCalendarService eventCalendarService = new EventCalendarService(rockContext);
                EventCalendarContentChannelService eventCalendarContentChannelService = new EventCalendarContentChannelService(rockContext);
                ContentChannelService     contentChannelService = new ContentChannelService(rockContext);
                AttributeService          attributeService      = new AttributeService(rockContext);
                AttributeQualifierService qualifierService      = new AttributeQualifierService(rockContext);

                int eventCalendarId = int.Parse(hfEventCalendarId.Value);

                if (eventCalendarId == 0)
                {
                    eventCalendar = new EventCalendar();
                    eventCalendarService.Add(eventCalendar);
                }
                else
                {
                    eventCalendar = eventCalendarService.Get(eventCalendarId);
                }

                eventCalendar.IsActive     = cbActive.Checked;
                eventCalendar.Name         = tbName.Text;
                eventCalendar.Description  = tbDescription.Text;
                eventCalendar.IconCssClass = tbIconCssClass.Text;

                eventCalendar.LoadAttributes();
                Rock.Attribute.Helper.GetEditValues(phAttributes, eventCalendar);

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

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

                    var dbChannelGuids = eventCalendarContentChannelService.Queryable()
                                         .Where(c => c.EventCalendarId == eventCalendar.Id)
                                         .Select(c => c.Guid)
                                         .ToList();

                    var uiChannelGuids = ContentChannelsState.Select(c => c.Key).ToList();

                    var toDelete = eventCalendarContentChannelService
                                   .Queryable()
                                   .Where(c =>
                                          dbChannelGuids.Contains(c.Guid) &&
                                          !uiChannelGuids.Contains(c.Guid));

                    eventCalendarContentChannelService.DeleteRange(toDelete);
                    contentChannelService.Queryable()
                    .Where(c =>
                           uiChannelGuids.Contains(c.Guid) &&
                           !dbChannelGuids.Contains(c.Guid))
                    .ToList()
                    .ForEach(c =>
                    {
                        var eventCalendarContentChannel              = new EventCalendarContentChannel();
                        eventCalendarContentChannel.EventCalendarId  = eventCalendar.Id;
                        eventCalendarContentChannel.ContentChannelId = c.Id;
                        eventCalendarContentChannelService.Add(eventCalendarContentChannel);
                    });

                    rockContext.SaveChanges();

                    /* Save Event Attributes */
                    string qualifierValue = eventCalendar.Id.ToString();
                    SaveAttributes(new EventCalendarItem().TypeId, "EventCalendarId", qualifierValue, EventAttributesState, rockContext);

                    // Reload calendar and make sure that the person who may have just added a calendar has security to view/edit/administrate the calendar
                    eventCalendar = eventCalendarService.Get(eventCalendar.Id);
                    if (eventCalendar != null)
                    {
                        if (!eventCalendar.IsAuthorized(Authorization.VIEW, CurrentPerson))
                        {
                            eventCalendar.AllowPerson(Authorization.VIEW, CurrentPerson, rockContext);
                        }
                        if (!eventCalendar.IsAuthorized(Authorization.EDIT, CurrentPerson))
                        {
                            eventCalendar.AllowPerson(Authorization.EDIT, CurrentPerson, rockContext);
                        }
                        if (!eventCalendar.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                        {
                            eventCalendar.AllowPerson(Authorization.ADMINISTRATE, CurrentPerson, rockContext);
                        }
                    }
                });
            }

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

            qryParams["EventCalendarId"] = eventCalendar.Id.ToString();
            NavigateToPage(RockPage.Guid, qryParams);
        }