Beispiel #1
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            EventItem eventItem = null;

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

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

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

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

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

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

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

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

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

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

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

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

                if ( !Page.IsValid )
                {
                    return;
                }

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

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

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

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

                // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
                var qryParams = new Dictionary<string, string>();
                if ( _calendarId.HasValue )
                {
                    qryParams["EventCalendarId"] = _calendarId.Value.ToString();
                }
                qryParams["EventItemId"] = eventItem.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
Beispiel #2
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            EventItem eventItem = null;

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

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

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

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

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

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

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

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

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

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

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

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

                if (!Page.IsValid)
                {
                    return;
                }

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

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

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

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


                // Redirect back to same page so that item grid will show any attributes that were selected to show on grid
                var qryParams = new Dictionary <string, string>();
                if (_calendarId.HasValue)
                {
                    qryParams["EventCalendarId"] = _calendarId.Value.ToString();
                }
                qryParams["EventItemId"] = eventItem.Id.ToString();
                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Syncs an eSpace event into Rock.
        /// </summary>
        /// <param name="eSpaceClient">The eSpace client</param>
        /// <param name="eSpaceEvent">The eSpace event</param>
        /// <param name="occurrencesFilter">The filter to use when syncing occurrences</param>
        /// <returns>The synced Rock event</returns>
        public static async Task SyncEvent(
            Client eSpaceClient,
            ESpace.Event eSpaceEvent,
            GetEventOccurrencesOptions occurrencesFilter,
            EventCalendarCache globalCalendar,
            EventCalendarCache publicCalendar,
            EventCalendarCache privateCalendar,
            string occurrenceApprovedAttributeKey
            )
        {
            using (var rockContext = new RockContext())
            {
                // Create our services
                var eventItemService           = new EventItemService(rockContext);
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
                var eventItemAudienceService   = new EventItemAudienceService(rockContext);
                var scheduleService            = new ScheduleService(rockContext);
                var personService = new PersonService(rockContext);

                // Get or create the linked Rock event
                var rockEvent = eventItemService.GetOrCreateByForeignId(
                    "EventCalendarItems,EventItemOccurrences",
                    ForeignKey_eSpaceEventId,
                    eSpaceEvent.EventId.Value,
                    out var _
                    );

                // Track if we needed to update anything
                var changed = false;

                // Update the Name
                if (rockEvent.Name != eSpaceEvent.EventName)
                {
                    changed        = true;
                    rockEvent.Name = eSpaceEvent.EventName;
                }

                // Update the Active State
                var eSpaceEventIsActive = eSpaceEvent.Status != ESpaceStatus_Draft;
                if (rockEvent.IsActive != eSpaceEventIsActive)
                {
                    changed            = true;
                    rockEvent.IsActive = eSpaceEventIsActive;
                }

                // Update the Approval State
                var eSpaceEventIsApproved = eSpaceEvent.Status == ESpaceStatus_Approved;
                if (rockEvent.IsApproved != eSpaceEventIsApproved)
                {
                    changed = true;
                    rockEvent.IsApproved = eSpaceEventIsApproved;

                    if (eSpaceEventIsApproved)
                    {
                        rockEvent.ApprovedOnDateTime = DateTime.Now;
                    }
                    else
                    {
                        rockEvent.ApprovedOnDateTime = null;
                    }
                }

                // Update the Summary
                if (rockEvent.Summary != eSpaceEvent.Description)
                {
                    changed           = true;
                    rockEvent.Summary = eSpaceEvent.Description;
                }

                // Update the details Url
                var eSpaceEventPublicLink = eSpaceEvent.PublicLink?.ToString();
                if (rockEvent.DetailsUrl != eSpaceEventPublicLink)
                {
                    changed = true;
                    rockEvent.DetailsUrl = eSpaceEventPublicLink;
                }

                // Update the audiences
                var eSpaceCategories = MatchCategories(eSpaceEvent.Categories);


                // Check global calendar
                if (globalCalendar != null)
                {
                    rockEvent.AddToCalendar(globalCalendar, out var addedToCalendar);
                    changed = changed || addedToCalendar;
                }

                var eventCalendarItemService = new EventCalendarItemService(rockContext);

                // Check public calendar
                if (publicCalendar != null)
                {
                    if (eSpaceEvent.IsPublic ?? false)
                    {
                        rockEvent.AddToCalendar(publicCalendar, out var addedToCalendar);
                        changed = changed || addedToCalendar;
                    }
                    else
                    {
                        rockEvent.RemoveFromCalendar(eventCalendarItemService, publicCalendar, out var removedFromCalendar);
                        changed = changed || removedFromCalendar;
                    }
                }

                // Check private calendar
                if (privateCalendar != null)
                {
                    if (!(eSpaceEvent.IsPublic ?? false))
                    {
                        rockEvent.AddToCalendar(privateCalendar, out var addedToCalendar);
                        changed = changed || addedToCalendar;
                    }
                    else
                    {
                        rockEvent.RemoveFromCalendar(eventCalendarItemService, privateCalendar, out var removedFromCalendar);
                        changed = changed || removedFromCalendar;
                    }
                }

                // Fetch the occurrences for the event
                if (occurrencesFilter == null)
                {
                    occurrencesFilter = new GetEventOccurrencesOptions {
                        StartDate = DateTime.Now
                    }
                }
                ;
                occurrencesFilter.EventId = eSpaceEvent.EventId;
                var eSpaceEventOccurrences = await eSpaceClient.GetEventOccurrences(occurrencesFilter);

                // Calculate some stuff for the occurrences
                var campusLocations = MatchLocations(eSpaceEvent.IsOffSite ?? false ? eSpaceEvent.PublicLocations : eSpaceEvent.Locations);
                var contactPerson   = personService.FindPerson(eSpaceEvent.Contacts.FirstOrDefault());

                var firstESpaceOccurrence = eSpaceEventOccurrences.FirstOrDefault();
                if (firstESpaceOccurrence != null)
                {
                    // Update the Description
                    if (rockEvent.Description != firstESpaceOccurrence.PublicHtmlNotes)
                    {
                        rockEvent.Description = firstESpaceOccurrence.PublicHtmlNotes;
                        changed = true;
                    }
                }

                var syncedRockOccurrences = new List <EventItemOccurrence>();;
                var rockOccurrencesWithAttributeChanges = new List <EventItemOccurrence>();

                // Update each occurrence
                foreach (var eSpaceOccurrence in eSpaceEventOccurrences)
                {
                    foreach (var campusLocation in campusLocations)
                    {
                        var rockOccurrence = SyncOccurrence(eSpaceEvent, eSpaceOccurrence, rockEvent, campusLocation, contactPerson, occurrenceApprovedAttributeKey, out var occurrenceChanged, out var occurrenceAttributeChanged);
                        changed = changed || occurrenceChanged;
                        syncedRockOccurrences.Add(rockOccurrence);
                        if (occurrenceAttributeChanged)
                        {
                            rockOccurrencesWithAttributeChanges.Add(rockOccurrence);
                        }
                    }
                }

                // Remove any desynced occurrences
                var removedOccurrences = rockEvent.EventItemOccurrences.Except(syncedRockOccurrences).ToList();
                foreach (var occurrence in removedOccurrences)
                {
                    rockEvent.EventItemOccurrences.Remove(occurrence);
                    if (occurrence.Schedule != null)
                    {
                        scheduleService.Delete(occurrence.Schedule);
                        occurrence.Schedule = null;
                    }
                    eventItemOccurrenceService.Delete(occurrence);
                    changed = true;
                }

                // If anything was updated, save it
                if (changed)
                {
                    rockContext.SaveChanges();
                }

                // If any occurrences had attributes modified, save them
                foreach (var rockOccurrence in rockOccurrencesWithAttributeChanges)
                {
                    rockOccurrence.SaveAttributeValues();
                }
            }
        }