Beispiel #1
0
        public virtual List <DateRange> GetScheduleDateRanges(Schedule schedule, DateTime beginDateTime, DateTime endDateTime)
        {
            if (schedule == null)
            {
                return(new List <DateRange>());
            }

            var result = new List <DateRange>();

            DDay.iCal.Event calEvent = schedule.GetCalenderEvent();
            if (calEvent != null && calEvent.DTStart != null)
            {
                var occurrences = ScheduleICalHelper.GetOccurrences(calEvent, beginDateTime, endDateTime);
                result = occurrences
                         .Where(a =>
                                a.Period != null &&
                                a.Period.StartTime != null &&
                                a.Period.EndTime != null)
                         .Select(a => new DateRange
                {
                    Start = DateTime.SpecifyKind(a.Period.StartTime.Value, DateTimeKind.Local).AddMinutes(-schedule.CheckInStartOffsetMinutes ?? 0),
                    End   = DateTime.SpecifyKind(a.Period.EndTime.Value, DateTimeKind.Local)
                })
                         .ToList();
                // ensure the the datetime is DateTimeKind.Local since iCal returns DateTimeKind.UTC
            }
            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// Gets the services.
        /// </summary>
        /// <returns></returns>
        private List <Schedule> GetServices(CampusCache campus = null)
        {
            var services = new List <Schedule>();

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("ScheduleCategories")))
            {
                List <Guid> categoryGuids       = GetAttributeValue("ScheduleCategories").Split(',').Select(g => g.AsGuid()).ToList();
                string      campusAttributeGuid = GetAttributeValue("CampusAttribute");

                DateTime?weekend = bddlWeekend.SelectedValue.AsDateTime();
                using (var rockContext = new RockContext())
                {
                    var attributeValueQry = new AttributeValueService(rockContext).Queryable();
                    foreach (Guid categoryGuid in categoryGuids)
                    {
                        var scheduleCategory = CategoryCache.Read(categoryGuid);
                        if (scheduleCategory != null && campus != null)
                        {
                            var schedules = new ScheduleService(rockContext)
                                            .Queryable().AsNoTracking()
                                            .Where(s => s.CategoryId == scheduleCategory.Id)
                                            .Join(
                                attributeValueQry.Where(av => av.Attribute.Guid.ToString() == campusAttributeGuid &&
                                                        av.Value.Contains(campus.Guid.ToString())),
                                p => p.Id,
                                av => av.EntityId,
                                (p, av) => new { Schedule = p, Value = av.Value });
                            // Check to see if the event was applicable the week for which we are entering data
                            foreach (var schedule in schedules)
                            {
                                var occurrences = ScheduleICalHelper.GetOccurrences(schedule.Schedule.GetCalenderEvent(), weekend.Value.Date.AddDays(-6), weekend.Value.Date.AddDays(1));
                                if (occurrences.Count > 0)
                                {
                                    services.Add(schedule.Schedule);
                                }
                            }
                        }
                        else if (scheduleCategory != null)
                        {
                            foreach (var schedule in new ScheduleService(rockContext)
                                     .Queryable().AsNoTracking()
                                     .Where(s =>
                                            s.CategoryId.HasValue &&
                                            s.CategoryId.Value == scheduleCategory.Id)
                                     .OrderBy(s => s.Name))
                            {
                                services.Add(schedule);
                            }
                        }
                    }
                }
            }
            return(services.OrderBy(s => s.NextStartDateTime.HasValue?s.NextStartDateTime.Value.Ticks : s.EffectiveEndDate.HasValue?s.EffectiveEndDate.Value.Ticks: 0).ToList());
        }
Beispiel #3
0
        public virtual DayOfWeek GetLastDayOfWeek(Schedule schedule, DateTime beginDateTime, DateTime endDateTime)
        {
            if (schedule == null)
            {
                return(DayOfWeek.Sunday);
            }

            DDay.iCal.Event calEvent = schedule.GetCalenderEvent();
            if (calEvent != null && calEvent.DTStart != null)
            {
                var occurrences = ScheduleICalHelper.GetOccurrences(calEvent, beginDateTime, endDateTime);
                return(occurrences
                       .FirstOrDefault(a =>
                                       a.Period != null &&
                                       a.Period.StartTime != null &&
                                       a.Period.EndTime != null)
                       .Period.StartTime.DayOfWeek);
                // ensure the the datetime is DateTimeKind.Local since iCal returns DateTimeKind.UTC
            }
            return(DayOfWeek.Sunday);
        }
Beispiel #4
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            EventItemOccurrence eventItemOccurrence = null;

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

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

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

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

                eventItemOccurrence.Location = tbLocation.Text;

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

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

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

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

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

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

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

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

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

                if (!Page.IsValid)
                {
                    return;
                }

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

                rockContext.SaveChanges();

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

                if (newItem)
                {
                    NavigateToParentPage(qryParams);
                }
                else
                {
                    qryParams.Add("EventItemOccurrenceId", eventItemOccurrence.Id.ToString());
                    NavigateToPage(RockPage.Guid, qryParams);
                }
            }
        }
Beispiel #5
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)
        {
            bool wasSecurityRole = false;
            bool triggersUpdated = false;

            RockContext rockContext = new RockContext();

            GroupService    groupService    = new GroupService(rockContext);
            ScheduleService scheduleService = new ScheduleService(rockContext);

            var roleGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid());
            int roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : int.MinValue;

            int?parentGroupId = hfParentGroupId.Value.AsIntegerOrNull();

            if (parentGroupId != null)
            {
                var allowedGroupIds = LineQuery.GetCellGroupIdsInLine(CurrentPerson, rockContext);
                if (!allowedGroupIds.Contains(parentGroupId.Value))
                {
                    nbMessage.Text         = "You are not allowed to add a group to this parent group.";
                    nbMessage.Visible      = true;
                    pnlEditDetails.Visible = false;
                    btnSave.Enabled        = false;
                    return;
                }
                var parentGroup = groupService.Get(parentGroupId.Value);
                if (parentGroup != null)
                {
                    CurrentGroupTypeId = parentGroup.GroupTypeId;

                    if (!lppLeader.PersonId.HasValue)
                    {
                        nbMessage.Text    = "A Leader is required.";
                        nbMessage.Visible = true;
                        return;
                    }

                    if (!GroupLocationsState.Any())
                    {
                        nbMessage.Text    = "A location is required.";
                        nbMessage.Visible = true;
                        return;
                    }

                    if (CurrentGroupTypeId == 0)
                    {
                        return;
                    }

                    Group group = new Group();
                    group.IsSystem = false;
                    group.Name     = string.Empty;



                    // add/update any group locations that were added or changed in the UI (we already removed the ones that were removed above)
                    foreach (var groupLocationState in GroupLocationsState)
                    {
                        GroupLocation groupLocation = group.GroupLocations.Where(l => l.Guid == groupLocationState.Guid).FirstOrDefault();
                        if (groupLocation == null)
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add(groupLocation);
                        }
                        else
                        {
                            groupLocationState.Id   = groupLocation.Id;
                            groupLocationState.Guid = groupLocation.Guid;

                            var selectedSchedules = groupLocationState.Schedules.Select(s => s.Guid).ToList();
                            foreach (var schedule in groupLocation.Schedules.Where(s => !selectedSchedules.Contains(s.Guid)).ToList())
                            {
                                groupLocation.Schedules.Remove(schedule);
                            }
                        }

                        groupLocation.CopyPropertiesFrom(groupLocationState);

                        var existingSchedules = groupLocation.Schedules.Select(s => s.Guid).ToList();
                        foreach (var scheduleState in groupLocationState.Schedules.Where(s => !existingSchedules.Contains(s.Guid)).ToList())
                        {
                            var schedule = scheduleService.Get(scheduleState.Guid);
                            if (schedule != null)
                            {
                                groupLocation.Schedules.Add(schedule);
                            }
                        }
                    }

                    GroupMember leader = new GroupMember();
                    leader.GroupMemberStatus = GroupMemberStatus.Active;
                    leader.PersonId          = lppLeader.PersonId.Value;
                    leader.Person            = new PersonService(rockContext).Get(lppLeader.PersonId.Value);
                    leader.GroupRole         = parentGroup.GroupType.Roles.Where(r => r.IsLeader).FirstOrDefault() ?? parentGroup.GroupType.DefaultGroupRole;

                    group.Name           = String.Format("{0}, {1}", leader.Person.NickName, leader.Person.LastName);
                    group.Description    = tbDescription.Text;
                    group.CampusId       = parentGroup.CampusId;
                    group.GroupTypeId    = CurrentGroupTypeId;
                    group.ParentGroupId  = parentGroupId;
                    group.IsSecurityRole = false;
                    group.IsActive       = true;
                    group.IsPublic       = true;

                    if (dpStartDate.SelectedDate.HasValue)
                    {
                        group.CreatedDateTime = dpStartDate.SelectedDate.Value;
                    }

                    group.Members.Add(leader);

                    string iCalendarContent = string.Empty;

                    // If unique schedule option was selected, but a schedule was not defined, set option to 'None'
                    var scheduleType = rblScheduleSelect.SelectedValueAsEnum <ScheduleType>(ScheduleType.None);
                    if (scheduleType == ScheduleType.Custom)
                    {
                        iCalendarContent = sbSchedule.iCalendarContent;
                        var calEvent = ScheduleICalHelper.GetCalenderEvent(iCalendarContent);
                        if (calEvent == null || calEvent.DTStart == null)
                        {
                            scheduleType = ScheduleType.None;
                        }
                    }

                    if (scheduleType == ScheduleType.Weekly)
                    {
                        if (!dowWeekly.SelectedDayOfWeek.HasValue)
                        {
                            scheduleType = ScheduleType.None;
                        }
                    }

                    int?oldScheduleId = hfUniqueScheduleId.Value.AsIntegerOrNull();
                    if (scheduleType == ScheduleType.Custom || scheduleType == ScheduleType.Weekly)
                    {
                        if (!oldScheduleId.HasValue || group.Schedule == null)
                        {
                            group.Schedule = new Schedule();
                        }

                        if (scheduleType == ScheduleType.Custom)
                        {
                            group.Schedule.iCalendarContent = iCalendarContent;
                            group.Schedule.WeeklyDayOfWeek  = null;
                            group.Schedule.WeeklyTimeOfDay  = null;
                        }
                        else
                        {
                            group.Schedule.iCalendarContent = null;
                            group.Schedule.WeeklyDayOfWeek  = dowWeekly.SelectedDayOfWeek;
                            group.Schedule.WeeklyTimeOfDay  = timeWeekly.SelectedTime;
                        }
                    }
                    else
                    {
                        // If group did have a unique schedule, delete that schedule
                        if (oldScheduleId.HasValue)
                        {
                            var schedule = scheduleService.Get(oldScheduleId.Value);
                            if (schedule != null && string.IsNullOrEmpty(schedule.Name))
                            {
                                scheduleService.Delete(schedule);
                            }
                        }

                        if (scheduleType == ScheduleType.Named)
                        {
                            group.ScheduleId = spSchedule.SelectedValueAsId();
                        }
                        else
                        {
                            group.ScheduleId = null;
                        }
                    }

                    group.LoadAttributes();
                    Rock.Attribute.Helper.GetEditValues(phGroupAttributes, group);

                    group.GroupType = new GroupTypeService(rockContext).Get(group.GroupTypeId);
                    if (group.ParentGroupId.HasValue)
                    {
                        group.ParentGroup = groupService.Get(group.ParentGroupId.Value);
                    }

                    if (!Page.IsValid)
                    {
                        return;
                    }

                    // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass.
                    // So, make sure a message is displayed in the validation summary
                    cvGroup.IsValid = group.IsValid;

                    if (!cvGroup.IsValid)
                    {
                        cvGroup.ErrorMessage = group.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                        return;
                    }

                    // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                    rockContext.WrapTransaction(() =>
                    {
                        var adding = group.Id.Equals(0);
                        if (adding)
                        {
                            groupService.Add(group);
                        }

                        rockContext.SaveChanges();

                        if (adding)
                        {
                            // add ADMINISTRATE to the person who added the group
                            Rock.Security.Authorization.AllowPerson(group, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext);
                        }

                        group.SaveAttributeValues(rockContext);
                    });

                    bool isNowSecurityRole = group.IsActive && (group.GroupTypeId == roleGroupTypeId);


                    if (isNowSecurityRole)
                    {
                        // new security role, flush
                        Rock.Security.Authorization.Flush();
                    }

                    AttributeCache.FlushEntityAttributes();

                    pnlDetails.Visible = false;
                    pnlSuccess.Visible = true;
                    nbSuccess.Text     = string.Format("Your group ({0}) has been created", group.Name);
                    string linkedPage            = LinkedPageRoute("RedirectPage");
                    int    secondsBeforeRedirect = GetAttributeValue("SecondsBeforeRedirect").AsInteger() * 1000;
                    ScriptManager.RegisterClientScriptBlock(upnlGroupDetail, typeof(UpdatePanel), "Redirect", string.Format("console.log('{0}'); setTimeout(function() {{ window.location.replace('{0}?GroupId={2}') }}, {1});", linkedPage, secondsBeforeRedirect, group.Id), true);
                }
            }
        }