Пример #1
0
        /// <summary>
        /// Loads and displays the event item occurrences
        /// </summary>
        private void BindData()
        {
            var rockContext = new RockContext();
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

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

            // Add filters for approval status
            var approvalFilterSettings = GetAttributeValue("ApprovalStatusFilter").AsInteger();   // 1 = Approved, 2 = Unapproved, 3 = All

            if (approvalFilterSettings == 1)
            {
                qry = qry.Where(m => m.EventItem.IsApproved == true);
            }
            else if (approvalFilterSettings == 2)
            {
                qry = qry.Where(m => m.EventItem.IsApproved == false);
            }

            // Filter by campus
            var campusGuidList       = GetAttributeValue("Campuses").Split(',').AsGuidList();
            var campusIdList         = CampusCache.All().Where(c => campusGuidList.Contains(c.Guid)).Select(c => c.Id);
            var selectedCampusIdList = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            if (selectedCampusIdList.Any())
            {
                // No value gets them all, otherwise get the ones selected
                // Block level campus filtering has already been performed on cblCampus, so no need to do it again here
                // If CampusId is null, then the event is an 'All Campuses' event, so include those
                qry = qry.Where(c => !c.CampusId.HasValue || selectedCampusIdList.Contains(c.CampusId.Value));
            }
            else if (campusIdList.Any())
            {
                // If no campus filter is selected then check the block filtering
                // If CampusId is null, then the event is an 'All Campuses' event, so include those
                qry = qry.Where(c => !c.CampusId.HasValue || campusIdList.Contains(c.CampusId.Value));
            }

            // Filter by Category
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            if (categories.Any())
            {
                qry = qry.Where(i => i.EventItem.EventItemAudiences.Any(c => categories.Contains(c.DefinedValueId)));
            }

            // Get the beginning and end dates
            var today       = RockDateTime.Today;
            var filterStart = FilterStartDate.HasValue ? FilterStartDate.Value : today;
            var monthStart  = new DateTime(filterStart.Year, filterStart.Month, 1);
            var rangeStart  = monthStart.AddMonths(-1);
            var rangeEnd    = monthStart.AddMonths(2);
            var beginDate   = FilterStartDate.HasValue ? FilterStartDate.Value : rangeStart;
            var endDate     = FilterEndDate.HasValue ? FilterEndDate.Value : rangeEnd;

            endDate = endDate.AddDays(1).AddMilliseconds(-1);

            // Get the occurrences
            var occurrences          = qry.ToList();
            var occurrencesWithDates = occurrences
                                       .Select(o =>
            {
                var eventOccurrenceDate = new EventOccurrenceDate
                {
                    EventItemOccurrence = o
                };

                if (o.Schedule != null)
                {
                    eventOccurrenceDate.ScheduleOccurrences = o.Schedule.GetICalOccurrences(beginDate, endDate).ToList();
                }
                else
                {
                    eventOccurrenceDate.ScheduleOccurrences = new List <Occurrence>();
                }

                return(eventOccurrenceDate);
            })
                                       .Where(d => d.ScheduleOccurrences.Any())
                                       .ToList();

            CalendarEventDates = new List <DateTime>();

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;
                foreach (var scheduleOccurrence in occurrenceDates.ScheduleOccurrences)
                {
                    var datetime          = scheduleOccurrence.Period.StartTime.Value;
                    var occurrenceEndTime = scheduleOccurrence.Period.EndTime;
                    if (occurrenceEndTime != null && occurrenceEndTime.Value.Date > datetime.Date)
                    {
                        var multiDate = datetime;
                        while (multiDate <= occurrenceEndTime.Date && multiDate <= endDate)
                        {
                            CalendarEventDates.Add(multiDate.Date);
                            multiDate = multiDate.AddDays(1);
                        }
                    }
                    else
                    {
                        CalendarEventDates.Add(datetime.Date);
                    }

                    if (datetime >= beginDate && datetime < endDate)
                    {
                        eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                        {
                            EventItemOccurrence = eventItemOccurrence,
                            Name                = eventItemOccurrence.EventItem.Name,
                            DateTime            = datetime,
                            Date                = datetime.ToShortDateString(),
                            Time                = datetime.ToShortTimeString(),
                            EndDate             = occurrenceEndTime != null ? occurrenceEndTime.Value.ToShortDateString() : null,
                            EndTime             = occurrenceEndTime != null ? occurrenceEndTime.Value.ToShortTimeString() : null,
                            Campus              = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            Location            = eventItemOccurrence.Campus != null ? eventItemOccurrence.Campus.Name : "All Campuses",
                            LocationDescription = eventItemOccurrence.Location,
                            Description         = eventItemOccurrence.EventItem.Description,
                            Summary             = eventItemOccurrence.EventItem.Summary,
                            OccurrenceNote      = eventItemOccurrence.Note.SanitizeHtml(),
                            DetailPage          = string.IsNullOrWhiteSpace(eventItemOccurrence.EventItem.DetailsUrl) ? null : eventItemOccurrence.EventItem.DetailsUrl
                        });
                    }
                }
            }

            var eventSummaries = eventOccurrenceSummaries
                                 .OrderBy(e => e.DateTime)
                                 .GroupBy(e => e.Name)
                                 .Select(e => e.ToList())
                                 .ToList();

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

            var mergeFields = new Dictionary <string, object>();

            mergeFields.Add("TimeFrame", ViewMode);
            mergeFields.Add("StartDate", FilterStartDate);
            mergeFields.Add("EndDate", FilterEndDate);
            mergeFields.Add("DetailsPage", LinkedPageRoute("DetailsPage"));
            mergeFields.Add("EventItems", eventSummaries);
            mergeFields.Add("EventItemOccurrences", eventOccurrenceSummaries);
            mergeFields.Add("CurrentPerson", CurrentPerson);

            lOutput.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields, GetAttributeValue("EnabledLavaCommands"));
        }
Пример #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="GroupMemberRequirementService"/> class
 /// </summary>
 /// <param name="context">The context.</param>
 public GroupMemberRequirementService(RockContext context) : base(context)
 {
 }
Пример #3
0
        /// <summary>
        /// Sets the attendance on load.
        /// </summary>
        private void GetAttendanceByAttendanceIdAndSelectedPersonId()
        {
            using (var rockContext = new RockContext())
            {
                // Is a person selected?
                if (_selectedPerson == null)
                {
                    nbError.Visible = true;
                }
                else if (CurrentPerson != null && _selectedPerson != CurrentPerson)
                {
                    nbError.Visible             = true;
                    nbError.Title               = "Note:";
                    nbError.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Info;
                    nbError.Text = string.Format("You are setting and viewing the confirmations for {0}.", _selectedPerson.FullName);
                }

                var request      = Context.Request;
                var attendanceId = GetAttendanceIdFromParameters();
                if (attendanceId != null)
                {
                    var attendanceService = new AttendanceService(rockContext);

                    // make sure the attendance is for the currently logged in person
                    var attendance = attendanceService.Queryable().Where(a => a.Id == attendanceId.Value && a.PersonAlias.PersonId == _selectedPerson.Id).FirstOrDefault();

                    if (attendance == null)
                    {
                        ShowNotAuthorizedMessage();
                        return;
                    }

                    bool statusChanged = false;

                    bool isConfirmedParameter = this.PageParameter("IsConfirmed").AsBoolean();
                    if (isConfirmedParameter)
                    {
                        if (!attendance.IsScheduledPersonConfirmed())
                        {
                            attendanceService.ScheduledPersonConfirm(attendance.Id);
                            rockContext.SaveChanges();
                        }
                    }
                    else
                    {
                        if (!attendance.IsScheduledPersonDeclined())
                        {
                            attendanceService.ScheduledPersonDecline(attendance.Id, null);
                            rockContext.SaveChanges();
                        }
                    }

                    if (statusChanged)
                    {
                        rockContext.SaveChanges();

                        // Only send Confirm if the status has changed and change is to Yes
                        if (attendance.RSVP == RSVP.Yes)
                        {
                            DetermineRecipientAndSendResponseEmails(attendance?.Id);
                        }
                    }

                    ShowHeadingByIsConfirmed(attendance);
                }
                else
                {
                    ShowNotAuthorizedMessage();
                    return;
                }

                BindPendingConfirmations();
            }
        }
Пример #4
0
        /// <summary>
        /// Binds the pages grid.
        /// </summary>
        protected void BindPagesGrid()
        {
            pnlPages.Visible = false;
            int siteId = PageParameter("siteId").AsInteger() ?? 0;

            if (siteId == 0)
            {
                // quit if the siteId can't be determined
                return;
            }

            hfSiteId.SetValue(siteId);
            pnlPages.Visible = true;

            // Question: Is this RegisterLayouts necessary here?  Since if it's a new layout
            // there would not be any pages on them (which is our concern here).
            // It seems like it should be the concern of some other part of the puzzle.
            LayoutService.RegisterLayouts(Request.MapPath("~"), SiteCache.Read(siteId));
            //var layouts = layoutService.Queryable().Where( a => a.SiteId.Equals( siteId ) ).Select( a => a.Id ).ToList();

            // Find all the pages that are related to this site...
            // 1) pages used by one of this site's layouts and
            // 2) the site's 'special' pages used directly by the site.
            var rockContext = new RockContext();
            var siteService = new SiteService(rockContext);
            var pageService = new PageService(rockContext);

            var site = siteService.Get(siteId);

            if (site != null)
            {
                var sitePages = new List <int> {
                    site.DefaultPageId ?? -1,
                    site.LoginPageId ?? -1,
                    site.RegistrationPageId ?? -1,
                    site.PageNotFoundPageId ?? -1
                };

                var qry = pageService.Queryable()
                          .Where(t =>
                                 t.Layout.SiteId == siteId ||
                                 sitePages.Contains(t.Id));

                string layoutFilter = gPagesFilter.GetUserPreference("Layout");
                if (!string.IsNullOrWhiteSpace(layoutFilter) && layoutFilter != Rock.Constants.All.Text)
                {
                    qry = qry.Where(a => a.Layout.ToString() == layoutFilter);
                }

                SortProperty sortProperty = gPages.SortProperty;
                if (sortProperty != null)
                {
                    qry = qry.Sort(sortProperty);
                }
                else
                {
                    qry = qry
                          .OrderBy(t => t.Layout.Name)
                          .ThenBy(t => t.InternalName);
                }

                gPages.DataSource = qry.ToList();
                gPages.DataBind();
            }
        }
Пример #5
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            if (HasFilterErrors())
            {
                return;
            }

            var         checkinAreaFilter = CheckinManagerHelper.GetCheckinAreaFilter(this);
            CampusCache campus            = GetCampusFromContext();

            var selectedScheduleIds = lbSchedules.SelectedValues.AsIntegerList();

            if (selectedScheduleIds.Any())
            {
                btnShowFilter.AddCssClass("criteria-exists bg-warning");
            }
            else
            {
                btnShowFilter.RemoveCssClass("criteria-exists bg-warning");
            }

            CheckinManagerHelper.SaveRoomListFilterToCookie(selectedScheduleIds.ToArray());

            var rockContext      = new RockContext();
            var groupService     = new GroupService(rockContext);
            var groupTypeService = new GroupTypeService(rockContext);
            IEnumerable <CheckinAreaPath> checkinAreaPaths;

            if (checkinAreaFilter != null)
            {
                checkinAreaPaths = groupTypeService.GetCheckinAreaDescendantsPath(checkinAreaFilter.Id);
            }
            else
            {
                checkinAreaPaths = groupTypeService.GetAllCheckinAreaPaths();
            }

            var selectedGroupTypeIds = checkinAreaPaths.Select(a => a.GroupTypeId).Distinct().ToArray();

            var groupLocationService = new GroupLocationService(rockContext);
            var groupLocationsQuery  = groupLocationService.Queryable()
                                       .Where(gl => selectedGroupTypeIds.Contains(gl.Group.GroupTypeId) && gl.Group.IsActive && (!gl.Group.IsArchived));

            var parentLocationIdParameter = PageParameter(PageParameterKey.ParentLocationId).AsIntegerOrNull();
            var locationIdParameter       = PageParameter(PageParameterKey.LocationId).AsIntegerOrNull();
            var locationGridField         = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lRoomName");

            if (locationGridField != null && !locationGridField.Visible)
            {
                locationGridField.Visible = true;
            }

            List <int> locationIds;

            if (locationIdParameter.HasValue)
            {
                // If LocationId is specified in the URL, list only items for the specified location.
                // Also, hide the Location Grid Column and set the PanelTitle as the location's name
                // This will take precedence over the selected campus+locations and/or <seealso cref="ParentLocationId"/>
                var locationService = new LocationService(rockContext);
                lPanelTitle.Text = locationService.GetSelect(locationIdParameter.Value, s => s.Name);

                locationIds = new List <int>();
                locationIds.Add(locationIdParameter.Value);

                if (locationGridField != null)
                {
                    // since a LocationId parameter was specified, the LocationGrid field doesn't need to be shown
                    locationGridField.Visible = false;
                }
            }
            else if (parentLocationIdParameter.HasValue)
            {
                // If parentLocationId is specified, show the direct (first level) child locations of the specified ParentLocationId.
                // This will take precedence over the selected campus+locations.
                var locationService = new LocationService(rockContext);
                locationIds = locationService.Queryable()
                              .Where(a => a.ParentLocationId.HasValue && a.ParentLocationId.Value == parentLocationIdParameter.Value)
                              .Select(a => a.Id).ToList();

                lPanelTitle.Text = string.Format("{0} Child Locations", locationService.GetSelect(parentLocationIdParameter.Value, s => s.Name));
            }
            else
            {
                // Limit locations (rooms) to locations within the selected campus.
                locationIds = new LocationService(rockContext).GetAllDescendentIds(campus.LocationId.Value).ToList();
                locationIds.Add(campus.LocationId.Value, true);

                lPanelTitle.Text = "Room List";
            }

            groupLocationsQuery = groupLocationsQuery.Where(a => locationIds.Contains(a.LocationId));

            if (selectedScheduleIds.Any())
            {
                groupLocationsQuery = groupLocationsQuery.Where(a => a.Schedules.Any(s => s.IsActive && s.CheckInStartOffsetMinutes.HasValue && selectedScheduleIds.Contains(s.Id)));
            }
            else
            {
                groupLocationsQuery = groupLocationsQuery.Where(a => a.Schedules.Any(s => s.IsActive && s.CheckInStartOffsetMinutes.HasValue));
            }

            var groupLocationList = groupLocationsQuery.Select(a => new GroupLocationInfo
            {
                LocationId      = a.LocationId,
                LocationName    = a.Location.Name,
                ParentGroupId   = a.Group.ParentGroupId,
                ParentGroupName = a.Group.ParentGroup.Name,
                GroupId         = a.Group.Id,
                GroupName       = a.Group.Name,
                GroupTypeId     = a.Group.GroupTypeId
            }).ToList();

            var      startDateTime = RockDateTime.Today;
            DateTime currentDateTime;

            if (campus != null)
            {
                currentDateTime = campus.CurrentDateTime;
            }
            else
            {
                currentDateTime = RockDateTime.Now;
            }

            // Get all Attendance records for the current day and location.
            var attendanceQuery = new AttendanceService(rockContext).Queryable().Where(a =>
                                                                                       a.StartDateTime >= startDateTime &&
                                                                                       a.DidAttend == true &&
                                                                                       a.StartDateTime <= currentDateTime &&
                                                                                       a.PersonAliasId.HasValue &&
                                                                                       a.Occurrence.GroupId.HasValue &&
                                                                                       a.Occurrence.LocationId.HasValue &&
                                                                                       a.Occurrence.ScheduleId.HasValue);

            // Limit attendances (rooms) to the groupLocations' LocationId and GroupIds that we'll be showing
            var groupLocationLocationIds = groupLocationList.Select(a => a.LocationId).Distinct().ToList();
            var groupLocationGroupsIds   = groupLocationList.Select(a => a.GroupId).Distinct().ToList();

            attendanceQuery = attendanceQuery.Where(a =>
                                                    groupLocationLocationIds.Contains(a.Occurrence.LocationId.Value) &&
                                                    groupLocationGroupsIds.Contains(a.Occurrence.GroupId.Value));

            attendanceQuery = attendanceQuery.Where(a => selectedGroupTypeIds.Contains(a.Occurrence.Group.GroupTypeId));

            if (selectedScheduleIds.Any())
            {
                attendanceQuery = attendanceQuery.Where(a => selectedScheduleIds.Contains(a.Occurrence.ScheduleId.Value));
            }

            var rosterAttendeeAttendanceList = RosterAttendeeAttendance.Select(attendanceQuery).ToList();

            var groupTypeIdsWithAllowCheckout = selectedGroupTypeIds
                                                .Select(a => GroupTypeCache.Get(a))
                                                .Where(a => a != null)
                                                .Where(gt => gt.GetCheckInConfigurationAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_GROUPTYPE_ALLOW_CHECKOUT).AsBoolean())
                                                .Select(a => a.Id)
                                                .Distinct().ToList();

            var groupTypeIdsWithEnablePresence = selectedGroupTypeIds
                                                 .Select(a => GroupTypeCache.Get(a))
                                                 .Where(a => a != null)
                                                 .Where(gt => gt.GetCheckInConfigurationAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_GROUPTYPE_ENABLE_PRESENCE).AsBoolean())
                                                 .Select(a => a.Id)
                                                 .Distinct();

            var scheduleIds  = rosterAttendeeAttendanceList.Select(a => a.ScheduleId.Value).Distinct().ToList();
            var scheduleList = new ScheduleService(rockContext).GetByIds(scheduleIds).ToList();
            var scheduleIdsWasScheduleOrCheckInActiveForCheckOut = new HashSet <int>(scheduleList.Where(a => a.WasScheduleOrCheckInActiveForCheckOut(currentDateTime)).Select(a => a.Id).ToList());

            rosterAttendeeAttendanceList = rosterAttendeeAttendanceList.Where(a =>
            {
                var allowCheckout = groupTypeIdsWithAllowCheckout.Contains(a.GroupTypeId);
                if (!allowCheckout)
                {
                    /*
                     *  If AllowCheckout is false, remove all Attendees whose schedules are not currently active. Per the 'WasSchedule...ActiveForCheckOut()'
                     *  method below: "Check-out can happen while check-in is active or until the event ends (start time + duration)." This will help to keep
                     *  the list of 'Present' attendees cleaned up and accurate, based on the room schedules, since the volunteers have no way to manually mark
                     *  an Attendee as 'Checked-out'.
                     *
                     *  If, on the other hand, AllowCheckout is true, it will be the volunteers' responsibility to click the [Check-out] button when an
                     *  Attendee leaves the room, in order to keep the list of 'Present' Attendees in order. This will also allow the volunteers to continue
                     *  'Checking-out' Attendees in the case that the parents are running late in picking them up.
                     */

                    return(scheduleIdsWasScheduleOrCheckInActiveForCheckOut.Contains(a.ScheduleId.Value));
                }
                else
                {
                    return(true);
                }
            }).ToList();

            var attendancesByLocationId = rosterAttendeeAttendanceList
                                          .GroupBy(a => a.LocationId.Value).ToDictionary(k => k.Key, v => v.ToList());

            _attendancesByLocationIdAndGroupId = attendancesByLocationId.ToDictionary(
                k => k.Key,
                v => v.Value.GroupBy(x => x.GroupId.Value).ToDictionary(x => x.Key, xx => xx.ToList()));

            _checkinAreaPathsLookupByGroupTypeId = checkinAreaPaths.ToDictionary(k => k.GroupTypeId, v => v);

            _showOnlyParentGroup = this.GetAttributeValue(AttributeKey.ShowOnlyParentGroup).AsBoolean();

            var roomList = new List <RoomInfo>();

            foreach (var groupLocation in groupLocationList)
            {
                AddToRoomList(roomList, groupLocation);
            }

            List <RoomInfo> sortedRoomList;

            if (_showOnlyParentGroup)
            {
                sortedRoomList = roomList.OrderBy(a => a.LocationName).ToList();
            }
            else
            {
                sortedRoomList = new List <RoomInfo>();
                sortedRoomList.AddRange(roomList.OfType <RoomInfoByGroup>().OrderBy(a => a.LocationName).ThenBy(a => a.GroupName).ToList());
            }

            var checkedInCountField  = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lCheckedInCount");
            var presentCountField    = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lPresentCount");
            var checkedOutCountField = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lCheckedOutCount");

            checkedOutCountField.Visible = groupTypeIdsWithAllowCheckout.Any();

            // Always show Present Count regardless of the 'Enable Presence' setting. (A person gets automatically marked present if 'Enable Presence' is disabled.)
            presentCountField.Visible = true;
            if (groupTypeIdsWithEnablePresence.Any())
            {
                // Presence is enabled, so records could be in the 'Checked-in' state
                // and Present column should be labeled 'Present'.
                checkedInCountField.Visible  = true;
                presentCountField.HeaderText = "Present";
            }
            else
            {
                // https://app.asana.com/0/0/1199637795718017/f
                // 'Enable Presence' is disabled, so a person automatically gets marked present.
                // So, no records will be in the 'Checked-In (but no present)' state.
                // Also, a user thinks of 'Present' as 'Checked-In' if they don't use the 'Enable Presence' feature
                checkedInCountField.Visible  = false;
                presentCountField.HeaderText = "Checked-In";
            }

            if (_showOnlyParentGroup)
            {
                gRoomList.DataKeyNames = new string[1] {
                    "LocationId"
                };
            }
            else
            {
                gRoomList.DataKeyNames = new string[2] {
                    "LocationId", "GroupId"
                };
            }

            gRoomList.DataSource = sortedRoomList;
            gRoomList.DataBind();
        }
Пример #6
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="contentChannelId">The content channel identifier.</param>
        public void ShowDetail(int contentChannelId)
        {
            ContentChannel contentChannel = null;

            cbIndexChannel.Visible = IndexContainer.IndexingEnabled;

            bool editAllowed = IsUserAuthorized(Authorization.EDIT);

            var rockContext = new RockContext();

            if (!contentChannelId.Equals(0))
            {
                contentChannel = GetContentChannel(contentChannelId);
                if (contentChannel != null)
                {
                    editAllowed = editAllowed || contentChannel.IsAuthorized(Authorization.EDIT, CurrentPerson);
                }
                pdAuditDetails.SetEntity(contentChannel, ResolveRockUrl("~"));
            }

            if (contentChannel == null)
            {
                contentChannel = new ContentChannel {
                    Id = 0
                };
                contentChannel.ChildContentChannels = new List <ContentChannel>();
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }

            if (contentChannel != null && contentChannel.IsAuthorized(Authorization.VIEW, CurrentPerson))
            {
                hfId.Value = contentChannel.Id.ToString();

                bool readOnly = false;
                nbEditModeMessage.Text = string.Empty;

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

                if (readOnly)
                {
                    lbEdit.Visible = false;
                    ShowReadonlyDetails(contentChannel);
                }
                else
                {
                    lbEdit.Visible = true;
                    if (contentChannel.Id > 0)
                    {
                        ShowReadonlyDetails(contentChannel);
                    }
                    else
                    {
                        ShowEditDetails(contentChannel);
                    }
                }

                btnSecurity.Visible  = contentChannel.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson);
                btnSecurity.Title    = contentChannel.Name;
                btnSecurity.EntityId = contentChannel.Id;

                lbSave.Visible = !readOnly;
            }
            else
            {
                nbEditModeMessage.Text      = EditModeMessage.NotAuthorizedToView(ContentChannel.FriendlyTypeName);
                pnlEditDetails.Visible      = false;
                fieldsetViewSummary.Visible = false;
            }
        }
Пример #7
0
        /// <summary>
        /// Maps the contact form data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        public void MapContactFormData(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext = new RockContext();

            var importedCommunicationCount = new CommunicationService(lookupContext).Queryable().Count(c => c.ForeignKey != null);
            var importedNoteCount          = new NoteService(lookupContext).Queryable().Count(n => n.ForeignKey != null);

            // Involvement Connection Type
            var connectionTypeService = new ConnectionTypeService(lookupContext);
            var defaultConnectionType = connectionTypeService.Get("DD565087-A4BE-4943-B123-BF22777E8426".AsGuid());
            var connectCardType       = connectionTypeService.Queryable().Where(t => t.Name.Equals("Connect Card", StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
            var opportunities         = new ConnectionOpportunityService(lookupContext).Queryable().ToList();
            var statuses        = new ConnectionStatusService(lookupContext).Queryable().ToList();
            var noContactStatus = statuses.FirstOrDefault(s => s.Name.Equals("No Contact", StringComparison.OrdinalIgnoreCase));

            var prayerRequestors  = new Dictionary <int, Person>();
            var communicationList = new List <Communication>();
            var connectionList    = new List <ConnectionRequest>();
            var prayerList        = new List <PrayerRequest>();
            var noteList          = new List <Note>();

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying contact items ({totalRows:N0} found, {importedNoteCount + importedCommunicationCount:N0} already exist).");

            foreach (var row in tableData.Where(r => r != null))
            {
                // ContactFormData joins to IndividualContactNotes on ContactInstItemID
                var itemForeignKey       = row["ContactInstItemID"] as int?;
                var householdId          = row["HouseholdID"] as int?;
                var itemIndividualId     = row["ContactItemIndividualID"] as int?;
                var individualId         = row["ContactIndividualID"] as int?;
                var createdDate          = row["ContactActivityDate"] as DateTime?;
                var modifiedDate         = row["ContactDatetime"] as DateTime?;
                var approvalDate         = row["ContactFormLastUpdatedDate"] as DateTime?;
                var itemType             = row["ContactFormName"] as string;
                var itemStatus           = row["ContactStatus"] as string;
                var itemCaption          = row["ContactItemName"] as string;
                var noteText1            = row["ContactNote"] as string;
                var noteText2            = row["ContactItemNote"] as string;
                var itemUserId           = row["ContactItemAssignedUserID"] as int?;
                var contactUserId        = row["ContactAssignedUserID"] as int?;
                var initialContactUserId = row["InitialContactCreatedByUserID"] as int?;
                var isConfidential       = row["IsContactItemConfidential"] as int?;
                var itemText             = !string.IsNullOrWhiteSpace(noteText1) ? $"{noteText1}<br>{noteText2}" : noteText2 ?? string.Empty;

                // look up the person this contact form is for
                var hasCaption = !string.IsNullOrWhiteSpace(itemCaption);
                var personKeys = GetPersonKeys(itemIndividualId ?? individualId, householdId);
                if (personKeys != null && (hasCaption || !string.IsNullOrWhiteSpace(itemText)))
                {
                    var assignedUserId    = itemUserId ?? contactUserId ?? initialContactUserId ?? 0;
                    var userPersonAliasId = PortalUsers.ContainsKey(assignedUserId) ? ( int? )PortalUsers[assignedUserId] : null;
                    // 99% of the Email types have no other info
                    if (itemType.Equals("Email", StringComparison.OrdinalIgnoreCase))
                    {
                        // create the recipient list for this contact
                        var recipients = new List <CommunicationRecipient> {
                            new CommunicationRecipient {
                                SendDateTime            = createdDate ?? modifiedDate,
                                Status                  = CommunicationRecipientStatus.Delivered,
                                PersonAliasId           = personKeys.PersonAliasId,
                                CreatedDateTime         = createdDate ?? modifiedDate,
                                CreatedByPersonAliasId  = userPersonAliasId,
                                ModifiedByPersonAliasId = userPersonAliasId,
                                ForeignKey              = personKeys.PersonForeignId.ToString(),
                                ForeignId               = personKeys.PersonForeignId
                            }
                        };

                        // create an email record for this contact form
                        var emailSubject  = !string.IsNullOrWhiteSpace(itemCaption) ? itemCaption.Left(100) : itemText.Left(100);
                        var communication = AddCommunication(lookupContext, EmailCommunicationMediumTypeId, emailSubject, itemText, false,
                                                             CommunicationStatus.Approved, recipients, false, createdDate ?? modifiedDate, itemForeignKey.ToString(), userPersonAliasId);

                        communicationList.Add(communication);
                    }
                    else if (itemType.EndsWith("Connection Card", StringComparison.OrdinalIgnoreCase) || itemType.Contains("Connect Card"))
                    {
                        // lookup connection opportunity
                        var opportunity = opportunities.FirstOrDefault(o => o.Name.Equals(itemType, StringComparison.OrdinalIgnoreCase) || (o.ForeignKey != null && o.ForeignKey.Equals(itemType, StringComparison.OrdinalIgnoreCase)));

                        if (opportunity == null)
                        {
                            var connectionType = connectCardType ?? defaultConnectionType;
                            opportunity = AddConnectionOpportunity(lookupContext, connectionType.Id, createdDate, itemType, string.Empty, true, itemForeignKey.ToString());
                            opportunities.Add(opportunity);
                        }

                        // create a connection request
                        var requestStatus = statuses.FirstOrDefault(s => s.Name.Equals(itemStatus, StringComparison.OrdinalIgnoreCase)) ?? noContactStatus;
                        var requestState  = itemStatus.Equals("Closed", StringComparison.OrdinalIgnoreCase) ? ConnectionState.Connected : ConnectionState.Active;

                        var request = AddConnectionRequest(opportunity, itemForeignKey.ToString(), createdDate, modifiedDate, requestStatus.Id, requestState, !string.IsNullOrWhiteSpace(itemText) ? $"{itemCaption} - {itemText}" : itemCaption ?? string.Empty, approvalDate, personKeys.PersonAliasId, userPersonAliasId);

                        connectionList.Add(request);
                    }
                    else if (hasCaption && itemCaption.EndsWith("Prayer Request", StringComparison.OrdinalIgnoreCase))
                    {
                        // create a prayer request
                        Person requestor = null;
                        prayerRequestors.TryGetValue(personKeys.PersonId, out requestor);
                        if (requestor == null)
                        {
                            requestor = lookupContext.People.FirstOrDefault(p => p.Id.Equals(personKeys.PersonId));
                            prayerRequestors.Add(personKeys.PersonId, requestor);
                        }

                        var request = AddPrayerRequest(lookupContext, null, personKeys.PersonAliasId, requestor.FirstName, requestor.LastName, requestor.Email, itemText ?? itemCaption, string.Empty,
                                                       !itemStatus.Equals("Closed", StringComparison.OrdinalIgnoreCase), false, createdDate ?? modifiedDate, approvalDate, itemForeignKey.ToString(), userPersonAliasId);
                        if (request != null)
                        {
                            prayerList.Add(request);
                        }
                    }
                    else
                    {
                        //strip campus from type
                        var campusId = GetCampusId(itemType);
                        if (campusId.HasValue)
                        {
                            itemType = StripPrefix(itemType, campusId);
                        }

                        // create a note for this contact form
                        var note = AddEntityNote(lookupContext, PersonEntityTypeId, personKeys.PersonId, itemCaption, itemText, false, false, itemType,
                                                 null, false, createdDate ?? modifiedDate, itemForeignKey.ToString(), userPersonAliasId);

                        noteList.Add(note);
                    }

                    completedItems++;
                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems:N0} contact items imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveCommunications(communicationList);
                        SaveConnectionRequests(connectionList);
                        SavePrayerRequests(prayerList);
                        SaveNotes(noteList);
                        ReportPartialProgress();

                        communicationList.Clear();
                        connectionList.Clear();
                        prayerList.Clear();
                        noteList.Clear();
                    }
                }
            }

            if (communicationList.Any() || connectionList.Any() || noteList.Any())
            {
                SaveCommunications(communicationList);
                SaveConnectionRequests(connectionList);
                SavePrayerRequests(prayerList);
                SaveNotes(noteList);
            }

            ReportProgress(100, $"Finished contact item import: {completedItems:N0} items imported.");
        }
Пример #8
0
        /// <summary>
        /// Handles the Click event of the btnAddBlock 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 btnAddBlock_Click(object sender, EventArgs e)
        {
            tbNewBlockName.Text = string.Empty;

            // Load the block types
            using (var rockContext = new RockContext())
            {
                try
                {
                    BlockTypeService.RegisterBlockTypes(Request.MapPath("~"), Page);
                }
                catch
                {
                    // ignore
                }


                Rock.Model.BlockTypeService blockTypeService = new Rock.Model.BlockTypeService(rockContext);
                var blockTypes = blockTypeService.Queryable().AsNoTracking()
                                 .Select(b => new { b.Id, b.Name, b.Category, b.Description })
                                 .ToList();

                ddlBlockType.Items.Clear();

                // Add the categorized block types
                foreach (var blockType in blockTypes
                         .Where(b => b.Category != string.Empty)
                         .OrderBy(b => b.Category)
                         .ThenBy(b => b.Name))
                {
                    var li = new ListItem(blockType.Name, blockType.Id.ToString());
                    li.Attributes.Add("optiongroup", blockType.Category);
                    li.Attributes.Add("title", blockType.Description);
                    ddlBlockType.Items.Add(li);
                }

                // Add the uncategorized block types
                foreach (var blockType in blockTypes
                         .Where(b => b.Category == null || b.Category == string.Empty)
                         .OrderBy(b => b.Name))
                {
                    var li = new ListItem(blockType.Name, blockType.Id.ToString());
                    li.Attributes.Add("optiongroup", "Other (not categorized)");
                    li.Attributes.Add("title", blockType.Description);
                    ddlBlockType.Items.Add(li);
                }
            }

            var htmlContentBlockType = BlockTypeCache.Read(Rock.SystemGuid.BlockType.HTML_CONTENT.AsGuid());

            ddlBlockType.SetValue(htmlContentBlockType.Id);

            rblAddBlockLocation.Items.Clear();

            var page = PageCache.Read(hfPageId.Value.AsInteger());

            var listItemPage = new ListItem();

            listItemPage.Text     = string.Format("Page ({0})", page.ToString());
            listItemPage.Value    = "Page";
            listItemPage.Selected = true;

            var listItemLayout = new ListItem();

            listItemLayout.Text     = string.Format("Layout ({0})", page.Layout);
            listItemLayout.Value    = "Layout";
            listItemLayout.Selected = false;

            var listItemSite = new ListItem();

            listItemSite.Text     = string.Format("Site ({0})", page.Layout.Site);
            listItemSite.Value    = "Site";
            listItemSite.Selected = false;

            rblAddBlockLocation.Items.Add(listItemPage);
            rblAddBlockLocation.Items.Add(listItemLayout);
            rblAddBlockLocation.Items.Add(listItemSite);
            mdAddBlock.Title = "Add Block to " + ddlZones.SelectedValue + " Zone";
            mdAddBlock.Show();
        }
Пример #9
0
        /// <summary>
        /// Maps the individual contact notes.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        public void MapIndividualContactNotes(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext = new RockContext();

            var activityTypeService   = new ConnectionActivityTypeService(lookupContext);
            var connectedActivityType = activityTypeService.Get(Rock.SystemGuid.ConnectionActivityType.CONNECTED.AsGuid());
            var assignedActivityType  = activityTypeService.Get(Rock.SystemGuid.ConnectionActivityType.ASSIGNED.AsGuid());

            var importedNotes = new NoteService(lookupContext).Queryable().Where(n => n.ForeignId != null)
                                .ToDictionary(n => n.ForeignId, n => n.Id);
            var importedConnectionRequests = new ConnectionRequestService(lookupContext).Queryable().Where(r => r.ForeignId != null)
                                             .ToDictionary(r => r.ForeignId, r => new { Id = r.Id, OpportunityId = r.ConnectionOpportunityId, ConnectorId = r.ConnectorPersonAliasId, State = r.ConnectionState });
            var importedPrayerRequests = new PrayerRequestService(lookupContext).Queryable().Where(r => r.ForeignId != null)
                                         .ToDictionary(r => r.ForeignId, r => r.Id);

            int?confidentialNoteTypeId = null;
            var noteList     = new List <Note>();
            var activityList = new List <ConnectionRequestActivity>();

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying contact notes ({totalRows:N0} found, {importedNotes.Count:N0} already exist).");

            foreach (var row in tableData.Where(r => r != null))
            {
                var userId            = row["UserID"] as int?;
                var individualId      = row["IndividualID"] as int?;
                var relatedForeignKey = row["ContactInstItemID"] as int?;
                var itemForeignKey    = row["IndividualContactID"] as int?;
                var createdDate       = row["IndividualContactDatetime"] as DateTime?;
                var noteText          = row["IndividualContactNote"] as string;
                var confidentialText  = row["ConfidentialNote"] as string;

                var personKeys     = GetPersonKeys(individualId, null);
                int?creatorAliasId = null;
                if (userId.HasValue && PortalUsers.ContainsKey(( int )userId))
                {
                    creatorAliasId = PortalUsers[( int )userId];
                }

                if (personKeys != null && (!string.IsNullOrWhiteSpace(noteText) || !string.IsNullOrWhiteSpace(confidentialText)))
                {
                    // this is a connection request comment
                    if (importedConnectionRequests.ContainsKey(relatedForeignKey))
                    {
                        var parentRequest = importedConnectionRequests[relatedForeignKey];
                        var activityType  = parentRequest.State == ConnectionState.Active ? assignedActivityType : connectedActivityType;
                        if (parentRequest != null && activityType != null)
                        {
                            var requestActivity = AddConnectionActivity(parentRequest.OpportunityId, noteText, createdDate, creatorAliasId ?? parentRequest.ConnectorId, activityType.Id, relatedForeignKey.ToString());
                            requestActivity.ConnectionRequestId = parentRequest.Id;
                            activityList.Add(requestActivity);
                        }
                    }
                    else // this is a new note or prayer request comment
                    {
                        var noteId           = 0;
                        var noteEntityId     = personKeys.PersonId;
                        var noteEntityTypeId = PersonEntityTypeId;
                        var noteTypeId       = PersonalNoteTypeId;

                        // add a confidential note
                        if (!string.IsNullOrWhiteSpace(confidentialText))
                        {
                            var confidential = AddEntityNote(lookupContext, noteEntityTypeId, noteEntityId, string.Empty, confidentialText, false, false,
                                                             "Confidential Note", confidentialNoteTypeId, false, createdDate, relatedForeignKey.ToString());
                            confidentialNoteTypeId = confidential.NoteTypeId;

                            noteList.Add(confidential);
                        }

                        // this is new or an update to timeline note
                        if (importedNotes.ContainsKey(relatedForeignKey))
                        {
                            noteId = importedNotes[relatedForeignKey];
                        }
                        // this is a prayer request comment
                        else if (importedPrayerRequests.ContainsKey(relatedForeignKey))
                        {
                            noteEntityTypeId = PrayerRequestTypeId;
                            noteEntityId     = importedPrayerRequests[relatedForeignKey];
                            noteTypeId       = PrayerNoteTypeId;
                        }

                        // add the note text
                        if (!string.IsNullOrWhiteSpace(noteText))
                        {
                            var note = AddEntityNote(lookupContext, noteEntityTypeId, noteEntityId, string.Empty, noteText, false, false,
                                                     null, noteTypeId, false, createdDate, itemForeignKey.ToString());
                            note.Id = noteId;

                            noteList.Add(note);
                        }
                    }

                    completedItems++;
                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems:N0} notes imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveNotes(noteList);
                        SaveActivities(activityList);
                        ReportPartialProgress();
                        noteList.Clear();
                        activityList.Clear();
                    }
                }
            }

            if (noteList.Any() || activityList.Any())
            {
                SaveNotes(noteList);
                SaveActivities(activityList);
            }

            ReportProgress(100, $"Finished contact note import: {completedItems:N0} notes imported.");
        }
Пример #10
0
        /// <summary>
        /// Maps the notes.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        public void MapNotes(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext = new RockContext();

            var importedUsers = new UserLoginService(lookupContext).Queryable().AsNoTracking()
                                .Where(u => u.ForeignId != null)
                                .ToDictionary(t => t.ForeignId, t => t.PersonId);

            var noteList = new List <Note>();

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying note import ({totalRows:N0} found).");
            foreach (var row in tableData.Where(r => r != null))
            {
                var noteType         = row["Note_Type_Name"] as string;
                var text             = row["Note_Text"] as string;
                var individualId     = row["Individual_ID"] as int?;
                var householdId      = row["Household_ID"] as int?;
                var noteTypeActive   = row["NoteTypeActive"] as bool?;
                var noteArchived     = row["NoteArchived"] as bool?;
                var noteTextArchived = row["NoteTextArchived"] as bool?;
                var dateCreated      = row["NoteCreated"] as DateTime?;

                // see if pre-import helper fix is present
                var noteArchivedFlag     = row["NoteArchived"] as int?;
                var noteTextArchivedFlag = row["NoteTextArchived"] as int?;
                noteArchived     = noteArchived.HasValue ? noteArchived : noteArchivedFlag > 0;
                noteTextArchived = noteTextArchived.HasValue ? noteTextArchived : noteTextArchivedFlag > 0;

                var noteExcluded = noteArchived == true || noteTextArchived == true;
                var personKeys   = GetPersonKeys(individualId, householdId);
                if (personKeys != null && !string.IsNullOrWhiteSpace(text) && noteTypeActive == true && !noteExcluded)
                {
                    int?creatorAliasId = null;
                    var userId         = row["NoteCreatedByUserID"] as int?;

                    if (userId.HasValue && PortalUsers.ContainsKey(( int )userId))
                    {
                        creatorAliasId = PortalUsers[( int )userId];
                    }

                    var noteTypeId = noteType.StartsWith("General", StringComparison.OrdinalIgnoreCase) ? ( int? )PersonalNoteTypeId : null;
                    var note       = AddEntityNote(lookupContext, PersonEntityTypeId, personKeys.PersonId, string.Empty, text, false, false, noteType, noteTypeId, false, dateCreated,
                                                   $"Note imported {ImportDateTime}", creatorAliasId);

                    noteList.Add(note);
                    completedItems++;

                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems:N0} notes imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveNotes(noteList);
                        ReportPartialProgress();
                        noteList.Clear();
                    }
                }
            }

            if (noteList.Any())
            {
                SaveNotes(noteList);
            }

            ReportProgress(100, $"Finished note import: {completedItems:N0} notes imported.");
        }
Пример #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConnectionRequestActivityService"/> class
 /// </summary>
 /// <param name="context">The context.</param>
 public ConnectionRequestActivityService(RockContext context) : base(context)
 {
 }
        /// <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)
        {
            var rockContext = new RockContext();

            MarketingCampaign marketingCampaign;

            MarketingCampaignService marketingCampaignService = new MarketingCampaignService(rockContext);

            int marketingCampaignId = int.Parse(hfMarketingCampaignId.Value);

            if (marketingCampaignId == 0)
            {
                marketingCampaign = new MarketingCampaign();
                marketingCampaignService.Add(marketingCampaign);
            }
            else
            {
                marketingCampaign = marketingCampaignService.Get(marketingCampaignId);
            }

            marketingCampaign.Title = tbTitle.Text;
            if (ppContactPerson.SelectedValue.Equals(None.Id.ToString()))
            {
                marketingCampaign.ContactPersonId = null;
            }
            else
            {
                marketingCampaign.ContactPersonId = ppContactPerson.PersonId;
            }

            marketingCampaign.ContactEmail       = tbContactEmail.Text;
            marketingCampaign.ContactPhoneNumber = tbContactPhoneNumber.Text;
            marketingCampaign.ContactFullName    = tbContactFullName.Text;

            if (ddlEventGroup.SelectedValue.Equals(None.Id.ToString()))
            {
                marketingCampaign.EventGroupId = null;
            }
            else
            {
                marketingCampaign.EventGroupId = int.Parse(ddlEventGroup.SelectedValue);
            }

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

            RockTransactionScope.WrapTransaction(() =>
            {
                /* Save MarketingCampaignAudiences to db */
                if (marketingCampaign.MarketingCampaignAudiences == null)
                {
                    marketingCampaign.MarketingCampaignAudiences = new List <MarketingCampaignAudience>();
                }

                // delete Audiences that aren't assigned in the UI anymore
                MarketingCampaignAudienceService marketingCampaignAudienceService = new MarketingCampaignAudienceService(rockContext);
                var deletedAudiences = from audienceInDB in marketingCampaign.MarketingCampaignAudiences.AsQueryable()
                                       where !(from audienceStateItem in MarketingCampaignAudiencesState
                                               select audienceStateItem.AudienceTypeValueId).Contains(audienceInDB.AudienceTypeValueId)
                                       select audienceInDB;
                deletedAudiences.ToList().ForEach(a =>
                {
                    var aud = marketingCampaignAudienceService.Get(a.Guid);
                    marketingCampaignAudienceService.Delete(aud);
                });

                rockContext.SaveChanges();

                // add or update the Audiences that are assigned in the UI
                foreach (var item in MarketingCampaignAudiencesState)
                {
                    MarketingCampaignAudience marketingCampaignAudience = marketingCampaign.MarketingCampaignAudiences.FirstOrDefault(a => a.AudienceTypeValueId.Equals(item.AudienceTypeValueId));
                    if (marketingCampaignAudience == null)
                    {
                        marketingCampaignAudience = new MarketingCampaignAudience();
                        marketingCampaign.MarketingCampaignAudiences.Add(marketingCampaignAudience);
                    }

                    marketingCampaignAudience.AudienceTypeValueId = item.AudienceTypeValueId;
                    marketingCampaignAudience.IsPrimary           = item.IsPrimary;
                }

                /* Save MarketingCampaignCampuses to db */

                // Update MarketingCampaignCampuses with UI values
                if (marketingCampaign.MarketingCampaignCampuses == null)
                {
                    marketingCampaign.MarketingCampaignCampuses = new List <MarketingCampaignCampus>();
                }

                // take care of deleted Campuses
                MarketingCampaignCampusService marketingCampaignCampusService = new MarketingCampaignCampusService(rockContext);
                var deletedCampuses = from mcc in marketingCampaign.MarketingCampaignCampuses.AsQueryable()
                                      where !cpCampuses.SelectedCampusIds.Contains(mcc.CampusId)
                                      select mcc;

                deletedCampuses.ToList().ForEach(a =>
                {
                    var c = marketingCampaignCampusService.Get(a.Guid);
                    marketingCampaignCampusService.Delete(c);
                });

                rockContext.SaveChanges();

                // add or update the Campuses that are assigned in the UI
                foreach (int campusId in cpCampuses.SelectedCampusIds)
                {
                    MarketingCampaignCampus marketingCampaignCampus = marketingCampaign.MarketingCampaignCampuses.FirstOrDefault(a => a.CampusId.Equals(campusId));
                    if (marketingCampaignCampus == null)
                    {
                        marketingCampaignCampus = new MarketingCampaignCampus();
                        marketingCampaign.MarketingCampaignCampuses.Add(marketingCampaignCampus);
                    }

                    marketingCampaignCampus.CampusId = campusId;
                }

                rockContext.SaveChanges();
            });


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

            qryParams["marketingCampaignId"] = marketingCampaign.Id.ToString();
            NavigateToPage(RockPage.Guid, qryParams);
        }
Пример #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentChannelItemService"/> class
 /// </summary>
 /// <param name="context">The context.</param>
 public ContentChannelItemService(RockContext context) : base(context)
 {
 }
Пример #14
0
        /// <summary>
        /// Gets the name of the Google user.
        /// </summary>
        /// <param name="googleUser">The Google user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetGoogleUser(GoogleUser googleUser, string accessToken = "")
        {
            // accessToken is required
            if (accessToken.IsNullOrWhiteSpace())
            {
                return(null);
            }

            string username   = string.Empty;
            string googleId   = googleUser.id;
            string googleLink = googleUser.link;

            string    userName = "******" + googleId;
            UserLogin user     = null;

            using (var rockContext = new RockContext())
            {
                // Query for an existing user
                var userLoginService = new UserLoginService(rockContext);
                user = userLoginService.GetByUserName(userName);

                // If no user was found, see if we can find a match in the person table
                if (user == null)
                {
                    // Get name/email from Google login
                    string lastName  = googleUser.family_name.ToString();
                    string firstName = googleUser.given_name.ToString();
                    string email     = string.Empty;
                    try { email = googleUser.email.ToString(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if (!string.IsNullOrWhiteSpace(email))
                    {
                        var personService = new PersonService(rockContext);
                        person = personService.FindPerson(firstName, lastName, email, true);
                    }

                    var personRecordTypeId  = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    var personStatusPending = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;

                    rockContext.WrapTransaction(() =>
                    {
                        if (person == null)
                        {
                            person                     = new Person();
                            person.IsSystem            = false;
                            person.RecordTypeValueId   = personRecordTypeId;
                            person.RecordStatusValueId = personStatusPending;
                            person.FirstName           = firstName;
                            person.LastName            = lastName;
                            person.Email               = email;
                            person.IsEmailActive       = true;
                            person.EmailPreference     = EmailPreference.EmailAllowed;
                            try
                            {
                                if (googleUser.gender.ToString() == "male")
                                {
                                    person.Gender = Gender.Male;
                                }
                                else if (googleUser.gender.ToString() == "female")
                                {
                                    person.Gender = Gender.Female;
                                }
                                else
                                {
                                    person.Gender = Gender.Unknown;
                                }
                            }
                            catch { }

                            if (person != null)
                            {
                                PersonService.SaveNewPerson(person, rockContext, null, false);
                            }
                        }

                        if (person != null)
                        {
                            int typeId = EntityTypeCache.Get(typeof(Google)).Id;
                            user       = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "goog", true);
                        }
                    });
                }
                if (user != null)
                {
                    username = user.UserName;

                    if (user.PersonId.HasValue)
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService(rockContext);
                        var person        = personService.Get(user.PersonId.Value);
                    }
                }

                return(username);
            }
        }
Пример #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WorkflowActionFormAttributeService"/> class
 /// </summary>
 /// <param name="context">The context.</param>
 public WorkflowActionFormAttributeService(RockContext context) : base(context)
 {
 }
Пример #16
0
        private void SortPanelWidgets(string eventParam, string[] values)
        {
            string      panelWidgetClientId = values[0];
            int         newIndex            = int.Parse(values[1]);
            Panel       pnlWidget           = pnlDetails.ControlsOfTypeRecursive <Panel>().FirstOrDefault(a => a.ClientID == panelWidgetClientId);
            HiddenField hfSiteBlockId       = pnlWidget.FindControl("hfSiteBlockId") as HiddenField;
            HiddenField hfLayoutBlockId     = pnlWidget.FindControl("hfLayoutBlockId") as HiddenField;
            HiddenField hfPageBlockId       = pnlWidget.FindControl("hfPageBlockId") as HiddenField;

            int?blockId = null;

            if (hfSiteBlockId != null)
            {
                blockId = hfSiteBlockId.Value.AsIntegerOrNull();
            }
            else if (hfLayoutBlockId != null)
            {
                blockId = hfLayoutBlockId.Value.AsIntegerOrNull();
            }
            else if (hfPageBlockId != null)
            {
                blockId = hfPageBlockId.Value.AsIntegerOrNull();
            }

            if (blockId.HasValue)
            {
                var rockContext  = new RockContext();
                var blockService = new BlockService(rockContext);
                var block        = blockService.Get(blockId.Value);
                var page         = Rock.Web.Cache.PageCache.Read(hfPageId.Value.AsInteger());
                if (block != null && page != null)
                {
                    List <Block> zoneBlocks = null;
                    switch (block.BlockLocation)
                    {
                    case BlockLocation.Page:
                        zoneBlocks = blockService.GetByPageAndZone(block.PageId.Value, block.Zone).ToList();
                        break;

                    case BlockLocation.Layout:
                        zoneBlocks = blockService.GetByLayoutAndZone(block.LayoutId.Value, block.Zone).ToList();
                        break;

                    case BlockLocation.Site:
                        zoneBlocks = blockService.GetBySiteAndZone(block.SiteId.Value, block.Zone).ToList();
                        break;
                    }

                    if (zoneBlocks != null)
                    {
                        var oldIndex = zoneBlocks.IndexOf(block);
                        blockService.Reorder(zoneBlocks, oldIndex, newIndex);

                        rockContext.SaveChanges();
                    }

                    foreach (var zoneBlock in zoneBlocks)
                    {
                        // make sure the BlockCache for all the re-ordered blocks get flushed so the new Order is updated
                        BlockCache.Flush(zoneBlock.Id);
                    }

                    page.FlushBlocks();
                    if (block.LayoutId.HasValue)
                    {
                        Rock.Web.Cache.PageCache.FlushLayoutBlocks(block.LayoutId.Value);
                    }

                    if (block.SiteId.HasValue)
                    {
                        Rock.Web.Cache.PageCache.FlushSiteBlocks(block.SiteId.Value);
                    }

                    ShowDetailForZone(ddlZones.SelectedValue);
                }
            }
        }
Пример #17
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            var rockContext = new RockContext();

            int sessionCount = GetAttributeValue("SessionCount").AsInteger();

            int skipCount = pageNumber * sessionCount;

            var person = new PersonService(rockContext).GetByUrlEncodedKey(PageParameter("Person"));

            if (person != null)
            {
                lPersonName.Text = person.FullName;

                PageViewService pageviewService = new PageViewService(rockContext);

                var pageViews = pageviewService.Queryable();

                var sessionInfo = pageviewService.Queryable()
                                  .Where(s => s.PersonAlias.PersonId == person.Id);

                if (startDate != DateTime.MinValue)
                {
                    sessionInfo = sessionInfo.Where(s => s.DateTimeViewed > drpDateFilter.LowerValue);
                }

                if (endDate != DateTime.MaxValue)
                {
                    sessionInfo = sessionInfo.Where(s => s.DateTimeViewed < drpDateFilter.UpperValue);
                }

                if (siteId != -1)
                {
                    sessionInfo = sessionInfo.Where(p => p.SiteId == siteId);
                }

                var pageviewInfo = sessionInfo.GroupBy(s => new
                {
                    s.PageViewSession,
                    s.SiteId,
                    SiteName = s.Site.Name
                })
                                   .Select(s => new WebSession
                {
                    PageViewSession = s.Key.PageViewSession,
                    StartDateTime   = s.Min(x => x.DateTimeViewed),
                    EndDateTime     = s.Max(x => x.DateTimeViewed),
                    SiteId          = s.Key.SiteId,
                    Site            = s.Key.SiteName,
                    PageViews       = pageViews.Where(p => p.PageViewSessionId == s.Key.PageViewSession.Id && p.SiteId == s.Key.SiteId).ToList()
                });

                pageviewInfo = pageviewInfo.OrderByDescending(p => p.StartDateTime)
                               .Skip(skipCount)
                               .Take(sessionCount + 1);

                rptSessions.DataSource = pageviewInfo.ToList().Take(sessionCount);
                rptSessions.DataBind();

                // set next button
                if (pageviewInfo.Count() > sessionCount)
                {
                    hlNext.Visible = hlNext.Enabled = true;
                    Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                    queryStringNext.Add("Page", (pageNumber + 1).ToString());
                    queryStringNext.Add("Person", person.UrlEncodedKey);
                    if (siteId != -1)
                    {
                        queryStringNext.Add("SiteId", siteId.ToString());
                    }

                    if (startDate != DateTime.MinValue)
                    {
                        queryStringNext.Add("StartDate", startDate.ToShortDateString());
                    }

                    if (endDate != DateTime.MaxValue)
                    {
                        queryStringNext.Add("EndDate", endDate.ToShortDateString());
                    }

                    var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                    hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                }
                else
                {
                    hlNext.Visible = hlNext.Enabled = false;
                }

                // set prev button
                if (pageNumber == 0)
                {
                    hlPrev.Visible = hlPrev.Enabled = false;
                }
                else
                {
                    hlPrev.Visible = hlPrev.Enabled = true;
                    Dictionary <string, string> queryStringPrev = new Dictionary <string, string>();
                    queryStringPrev.Add("Page", (pageNumber - 1).ToString());
                    queryStringPrev.Add("Person", person.UrlEncodedKey);
                    if (siteId != -1)
                    {
                        queryStringPrev.Add("SiteId", siteId.ToString());
                    }

                    if (startDate != DateTime.MinValue)
                    {
                        queryStringPrev.Add("StartDate", startDate.ToShortDateString());
                    }

                    if (endDate != DateTime.MaxValue)
                    {
                        queryStringPrev.Add("EndDate", endDate.ToShortDateString());
                    }

                    var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                    hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>";
            }
        }
Пример #18
0
        private List <StatisticRow> GetDataForDateRange(DateTime startDate, DateTime endDate)
        {
            var entityTypeGroupGuid        = Rock.SystemGuid.EntityType.GROUP.AsGuid();
            var groupEntityType            = EntityTypeCache.Read(entityTypeGroupGuid);
            int entityTypeScheduleEntityId = EntityTypeCache.Read(Rock.SystemGuid.EntityType.SCHEDULE.AsGuid()).Id;

            var rockContext = new RockContext();

            rockContext.Database.CommandTimeout = 2600;
            var metricService         = new MetricService(rockContext);
            var metricValueService    = new MetricValueService(rockContext);
            var scheduleService       = new ScheduleService(rockContext);
            var groupService          = new GroupService(rockContext);
            var attendanceService     = new AttendanceService(rockContext);
            var attributeService      = new AttributeService(rockContext);
            var attributeValueService = new AttributeValueService(rockContext);

            var metricCategoryGuidList          = GetAttributeValue("Metrics").SplitDelimitedValues().AsGuidList();
            var attendanceGroupGuidList         = GetAttributeValue("AttendanceGroups").SplitDelimitedValues().AsGuidList();
            var parentMetricVolunteerGroupGuids = GetAttributeValue("ServiceVolunteerGroups").SplitDelimitedValues().AsGuidList();


            var attendanceGroups            = groupService.GetByGuids(attendanceGroupGuidList);
            var parentMetricVolunteerGroups = groupService.GetByGuids(parentMetricVolunteerGroupGuids);
            var metrics = metricService.GetByGuids(metricCategoryGuidList).Distinct().ToList();

            var datasource = new List <StatisticRow>();

            var metricVolunteerGroups = new List <Group>();

            foreach (var parentMetricVolunteerGroup in parentMetricVolunteerGroups)
            {
                metricVolunteerGroups.Add(parentMetricVolunteerGroup);
                metricVolunteerGroups.AddRange(groupService.GetAllDescendents(parentMetricVolunteerGroup.Id));
            }

            var metricVolunteerGroupIds = metricVolunteerGroups.Select(g => g.Id).ToList();

            var metricVolunteerAttendanceData = attendanceService.Queryable().Where(a =>
                                                                                    a.GroupId.HasValue &&
                                                                                    metricVolunteerGroupIds.Contains(a.GroupId.Value) && a.StartDateTime >= startDate && a.StartDateTime <= endDate);

            foreach (var metric in metrics)
            {
                var metricData = metricValueService.Queryable("MetricValuePartitions").Where(mv =>
                                                                                             mv.MetricValueDateTime >= startDate &&
                                                                                             mv.MetricValueDateTime <= endDate &&
                                                                                             mv.MetricId == metric.Id &&
                                                                                             mv.MetricValuePartitions.FirstOrDefault(
                                                                                                 mvp =>
                                                                                                 mvp.MetricPartition.EntityTypeId ==
                                                                                                 entityTypeScheduleEntityId).EntityId.HasValue
                                                                                             )
                                 .GroupBy(
                    mv =>
                    mv.MetricValuePartitions.FirstOrDefault(
                        mvp =>
                        mvp.MetricPartition.EntityTypeId ==
                        entityTypeScheduleEntityId).EntityId.Value)
                                 .ToList()
                                 .Select(mv =>
                {
                    var service = scheduleService.Get(mv.Key);
                    return(new StatisticRow
                    {
                        ScheduleDateRanges =
                            GetScheduleDateRanges(service,
                                                  startDate, endDate),
                        RowId = metric.Id + "-" + mv.Key,
                        SortValue = 0,
                        IsTotal = false,
                        Area = metric.Title,
                        Subarea = "Head Count",
                        StartTime = service.WeeklyTimeOfDay ?? service.StartTimeOfDay,
                        DayOfWeek = service.WeeklyDayOfWeek ?? GetLastDayOfWeek(service, startDate, endDate),
                        Service = service.Name,
                        Count =
                            mv.Sum(a => a.YValue).HasValue
                                                                    ? decimal.ToInt32(mv.Sum(a => a.YValue).Value)
                                                                    : 0,
                        MetricNote = mv.Max(a => a.Note),
                        Value = mv
                    });
                })
                                 .ToList();

                foreach (var row in metricData)
                {
                    int volunteers = 0;
                    int total      = row.Value.Sum(a => a.YValue).HasValue ? decimal.ToInt32(row.Value.Sum(a => a.YValue).Value) : 0;

                    if (metricVolunteerAttendanceData.Any())
                    {
                        volunteers    += row.ScheduleDateRanges.Sum(dateRange => metricVolunteerAttendanceData.Count(a => (a.DidAttend == null || a.DidAttend.Value) && a.StartDateTime >= dateRange.Start && a.StartDateTime <= dateRange.End));
                        row.Total      = total + volunteers;
                        row.Volunteers = volunteers;
                    }
                }


                datasource.AddRange(metricData);

                if (metricData.Count > 1)
                {
                    var subTotalRow = new StatisticRow
                    {
                        RowId      = metric.Id.ToString(),
                        SortValue  = 0,
                        IsTotal    = true,
                        Area       = metric.Title,
                        Subarea    = "Head Count",
                        Service    = "Sub-Total",
                        Count      = metricData.Sum(mv => mv.Count),
                        Volunteers = metricData.Sum(mv => mv.Volunteers),
                        Total      = metricData.Sum(mv => mv.Total)
                    };

                    datasource.Add(subTotalRow);
                }
            }

            var totalRow = new StatisticRow
            {
                RowId      = "HeadcountTotal",
                SortValue  = 1,
                IsTotal    = true,
                Area       = "Head Count Total",
                Subarea    = "Head Count",
                Service    = "Total",
                Count      = datasource.Where(row => !row.IsTotal).Sum(row => row.Count),
                Volunteers = datasource.Where(row => !row.IsTotal).Sum(mv => mv.Volunteers),
                Total      = datasource.Where(row => !row.IsTotal).Sum(mv => mv.Total)
            };

            datasource.Add(totalRow);

            string attributeKeyString            = GetAttributeValue("VolunteerGroupAttributeKey");
            var    volunteerGroupAttributeIdList = attributeService.Queryable()
                                                   .Where(a => a.Key == attributeKeyString && a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeId == groupEntityType.Id).Select(a => a.Id);

            if (volunteerGroupAttributeIdList.Any())
            {
                // Find the groups that attribute values that have the maaping between group (the entityId) and the place they should be grouped with attending (value)
                var volunteerGroupMappingList = attributeValueService.Queryable().Where(av => volunteerGroupAttributeIdList.Contains(av.AttributeId) && av.Value != null)
                                                .ToList()
                                                .Select(av => new
                {
                    VolunteerAttendanceGroupGuid = av.Value.AsGuid(),
                    VolunteerGroupId             = av.EntityId
                }).ToList();

                foreach (var attendanceGroup in attendanceGroups)
                {
                    foreach (var attendanceChildGroup in attendanceGroup.Groups)
                    {
                        var attendanceChildDescendantGroups = groupService.GetAllDescendents(attendanceChildGroup.Id).ToList();
                        // Include child group in for cases where attendance needs to be mapped to an area not a specific group (production team isn't for a specific children's group -- it's associated with TC kids as a whole)
                        attendanceChildDescendantGroups.Add(attendanceChildGroup);
                        var attendanceChildDescendantGroupIds = attendanceChildDescendantGroups.Select(g => g.Id);

                        var volunteerGroupIds = volunteerGroupMappingList
                                                .Where(vgm => attendanceChildDescendantGroups.Any(g => g.Guid == vgm.VolunteerAttendanceGroupGuid))
                                                .Select(vgm => vgm.VolunteerGroupId).ToList();
                        var volunteerGroupAttendance = attendanceService.Queryable()
                                                       .Where(a => volunteerGroupIds.Any(id => id != null && id == a.Group.Id) && a.StartDateTime >= startDate && a.StartDateTime <= endDate)
                                                       .ToList();

                        var acg = attendanceChildGroup;
                        var childGroupAttendance = attendanceService.Queryable().Where(a =>
                                                                                       a.GroupId != null &&
                                                                                       a.StartDateTime >= startDate &&
                                                                                       a.StartDateTime <= endDate &&
                                                                                       (a.GroupId == acg.Id ||
                                                                                        attendanceChildDescendantGroupIds.Any(id => id == a.GroupId)) &&
                                                                                       (a.DidAttend == null || a.DidAttend.Value))
                                                   .GroupBy(a => a.ScheduleId)
                                                   .ToList();

                        // ag is created to prevent a warn "Access to foreach variable in closure."
                        var ag            = attendanceGroup;
                        var statisticRows = childGroupAttendance.Select(a =>
                        {
                            var attendance         = a.FirstOrDefault();
                            var scheduleDateRanges = GetScheduleDateRanges(attendance.Schedule, startDate,
                                                                           endDate);
                            var row        = new StatisticRow();
                            row.RowId      = acg.Id + "-" + a.Key;
                            row.SortValue  = 2;
                            row.IsTotal    = false;
                            row.Area       = ag.Name;
                            row.Subarea    = acg.Name;
                            row.Service    = attendance.Schedule.Name;
                            row.StartTime  = attendance.Schedule.WeeklyTimeOfDay ?? attendance.Schedule.StartTimeOfDay;
                            row.DayOfWeek  = attendance.Schedule.WeeklyDayOfWeek ?? GetLastDayOfWeek(attendance.Schedule, startDate, endDate);
                            row.Count      = a.Count();
                            row.Volunteers = volunteerGroupAttendance.Count(b => scheduleDateRanges.Any(s => b.StartDateTime >= s.Start && b.StartDateTime <= s.End));
                            row.Total      = a.Count() + volunteerGroupAttendance.Count(b => scheduleDateRanges.Any(s => b.StartDateTime >= s.Start && b.StartDateTime <= s.End));
                            return(row);
                        }).ToList();

                        datasource.AddRange(statisticRows);

                        if (statisticRows.Count > 1)
                        {
                            var subTotalRow = new StatisticRow
                            {
                                RowId      = attendanceChildGroup.Id.ToString(),
                                SortValue  = 2,
                                IsTotal    = true,
                                Area       = attendanceGroup.Name,
                                Subarea    = attendanceChildGroup.Name,
                                Service    = "Sub-Total",
                                Count      = statisticRows.Sum(cg => cg.Count),
                                Volunteers = statisticRows.Sum(cg => cg.Volunteers),
                                Total      = statisticRows.Sum(cg => cg.Total)
                            };

                            datasource.Add(subTotalRow);
                        }
                    }
                }
            }

            datasource.Add(new StatisticRow
            {
                RowId      = "Total",
                SortValue  = 3,
                IsTotal    = true,
                Area       = "Grand Total",
                Subarea    = "Total",
                Service    = "Total",
                Count      = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Count),
                Volunteers = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Volunteers),
                Total      = datasource.Where(ds => ds.IsTotal).Sum(cg => cg.Total)
            });

            return(datasource);
        }
Пример #19
0
        /// <summary>Saves the specified publish group status.</summary>
        /// <param name="publishGroupStatus">The publish group status.</param>
        private void Save(PublishGroupStatus publishGroupStatus)
        {
            RockContext         rockContext         = new RockContext();
            PublishGroupService publishGroupService = new PublishGroupService(rockContext);
            PublishGroup        publishGroup        = GetPublishGroup(rockContext, publishGroupService);

            var slug = tbSlug.Text.ToLower().RemoveAllNonAlphaNumericCharacters();

            tbSlug.Text = slug;

            //Test for already taken Slugs
            var isDuplicateSlug = publishGroupService.Queryable()
                                  .Where(pg => pg.Slug == slug && pg.Id != publishGroup.Id && pg.GroupId != publishGroup.Group.Id)
                                  .Any();

            if (isDuplicateSlug)
            {
                nbSlug.Visible = true;
                return;
            }
            else
            {
                nbSlug.Visible    = false;
                publishGroup.Slug = slug;
            }


            bool isApprover = false;

            if (IsUserAuthorized(Rock.Security.Authorization.EDIT))
            {
                isApprover = true;
            }

            if (isApprover)
            {
                publishGroupStatus = ddlStatus.SelectedValueAsEnum <PublishGroupStatus>();
            }
            else if (publishGroupStatus != PublishGroupStatus.Draft)
            {
                if (ddlRegistration.SelectedValue == "4" ||
                    (ddlChildcareOptions.SelectedValue == "2" && ddlChildcareNeedRegistration.SelectedValue == "2"))     //Childcare required && Registration needed.
                {
                    publishGroupStatus = PublishGroupStatus.PendingIT;
                }
            }

            if (publishGroup.PublishGroupStatus == PublishGroupStatus.Approved)
            {
                var tempGroup = publishGroup.Group;
                publishGroup       = ( PublishGroup )publishGroup.Clone();
                publishGroup.Guid  = Guid.NewGuid();
                publishGroup.Id    = 0;
                publishGroup.Group = tempGroup;
                publishGroupService.Add(publishGroup);
            }

            publishGroup.Name                             = tbName.Text;
            publishGroup.ImageId                          = iGroupImage.BinaryFileId;
            publishGroup.PublishGroupStatus               = publishGroupStatus;
            publishGroup.Description                      = tbDescription.Text;
            publishGroup.EndDateTime                      = drPublishDates.UpperValue.Value;
            publishGroup.StartDateTime                    = drPublishDates.LowerValue.Value;
            publishGroup.WeeklyDayOfWeek                  = ddlDayOfWeek.SelectedValueAsEnumOrNull <DayOfWeek>();
            publishGroup.WeeklyTimeOfDay                  = tTimeOfDay.SelectedTime;
            publishGroup.CustomSchedule                   = tbCustomSchedule.Text;
            publishGroup.StartDate                        = dpStartDate.SelectedDate;
            publishGroup.MeetingLocation                  = tbLocationName.Text;
            publishGroup.IsHidden                         = cbIsHidden.Checked;
            publishGroup.RegistrationRequirement          = ( RegistrationRequirement )ddlRegistration.SelectedValue.AsInteger();
            publishGroup.RequiresRegistration             = ddlRegistration.SelectedValue.AsInteger() > 0; //This is obsolete but left in for backward compatability
            publishGroup.RegistrationLink                 = publishGroup.RegistrationRequirement == RegistrationRequirement.CustomRegistration ? tbRegistrationLink.Text : "";
            publishGroup.RegistrationDescription          = tbRegistrationDetails.Text;
            publishGroup.ChildcareRegistrationDescription = ddlChildcareNeedRegistration.SelectedValue == "2" ? tbChildcareRegistrationDetails.Text : "";
            publishGroup.AllowSpouseRegistration          = cbAllowSpouseRegistration.Checked;
            publishGroup.ChildcareOptions                 = ( ChildcareOptions )ddlChildcareOptions.SelectedValue.AsInteger();
            publishGroup.ChildcareAvailable               = ddlChildcareOptions.SelectedValue.AsInteger() > 0;
            publishGroup.ChildcareRegistrationLink        = publishGroup.ChildcareAvailable ? tbChildcareRegistrationLink.Text : "";
            publishGroup.AudienceValues                   = GetSelectedAudiences(rockContext);
            publishGroup.ContactPersonAliasId             = pContactPerson.PersonAliasId.Value;
            publishGroup.RequestorAliasId                 = CurrentPersonAliasId.Value;
            publishGroup.ContactEmail                     = tbContactEmail.Text;
            publishGroup.ContactPhoneNumber               = tbContactPhoneNumber.Text;
            publishGroup.ConfirmationFromName             = tbConfirmationFromName.Text;
            publishGroup.ConfirmationEmail                = tbConfirmationFromEmail.Text;
            publishGroup.ConfirmationSubject              = tbConfirmationSubject.Text;
            publishGroup.ConfirmationBody                 = ceConfirmationBody.Text;

            if (publishGroup.Id == 0)
            {
                publishGroupService.Add(publishGroup);
            }

            if (isApprover && publishGroupStatus == PublishGroupStatus.Approved)
            {
                publishGroup.Group.IsActive = true;
                publishGroup.Group.IsPublic = true;
                //remove all other publish groups for this computer
                publishGroupService.DeleteRange(publishGroupService.Queryable().Where(pg => pg.GroupId == publishGroup.GroupId && pg.Id != publishGroup.Id));
            }
            ;

            //Set the binary file to not be temporary
            if (publishGroup.ImageId.HasValue)
            {
                BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                var binaryFile = binaryFileService.Get(publishGroup.ImageId.Value);
                if (binaryFile != null)
                {
                    binaryFile.IsTemporary = false;
                }
            }

            rockContext.SaveChanges();

            publishGroup.LoadAttributes(rockContext);

            if (publishGroup.Attributes.Any())
            {
                Rock.Attribute.Helper.GetEditValues(phAttributeEdits, publishGroup);
                publishGroup.SaveAttributeValues(rockContext);
            }

            if (publishGroup.PublishGroupStatus != PublishGroupStatus.Draft)
            {
                publishGroup.LaunchWorkflow(GetAttributeValue(AttributeKeys.Workflow).AsGuidOrNull());
            }

            NavigateToParentPage(new Dictionary <string, string> {
                { "GroupId", publishGroup.GroupId.ToString() }
            });
        }
Пример #20
0
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            var            rockContext = new RockContext();
            ContentChannel contentChannel;

            ContentChannelService contentChannelService = new ContentChannelService(rockContext);

            int contentChannelId = hfId.Value.AsInteger();

            if (contentChannelId == 0)
            {
                contentChannel = new ContentChannel {
                    Id = 0
                };
                contentChannelService.Add(contentChannel);
            }
            else
            {
                contentChannel = contentChannelService.Get(contentChannelId);
            }

            if (contentChannel != null)
            {
                contentChannel.Name                 = tbName.Text;
                contentChannel.Description          = tbDescription.Text;
                contentChannel.ContentChannelTypeId = ddlChannelType.SelectedValueAsInt() ?? 0;
                contentChannel.ContentControlType   = ddlContentControlType.SelectedValueAsEnum <ContentControlType>();
                contentChannel.RootImageDirectory   = tbRootImageDirectory.Visible ? tbRootImageDirectory.Text : string.Empty;
                contentChannel.IconCssClass         = tbIconCssClass.Text;

                // the cbRequireApproval will be hidden if contentChannelType.DisableStatus == True
                contentChannel.RequiresApproval          = cbRequireApproval.Visible && cbRequireApproval.Checked;
                contentChannel.IsIndexEnabled            = cbIndexChannel.Checked;
                contentChannel.ItemsManuallyOrdered      = cbItemsManuallyOrdered.Checked;
                contentChannel.ChildItemsManuallyOrdered = cbChildItemsManuallyOrdered.Checked;
                contentChannel.EnableRss         = cbEnableRss.Checked;
                contentChannel.ChannelUrl        = tbChannelUrl.Text;
                contentChannel.ItemUrl           = tbItemUrl.Text;
                contentChannel.TimeToLive        = nbTimetoLive.Text.AsIntegerOrNull();
                contentChannel.ItemUrl           = tbContentChannelItemPublishingPoint.Text;
                contentChannel.IsTaggingEnabled  = cbEnableTag.Checked;
                contentChannel.ItemTagCategoryId = cbEnableTag.Checked ? cpCategory.SelectedValueAsInt() : (int?)null;

                contentChannel.ChildContentChannels = new List <ContentChannel>();
                contentChannel.ChildContentChannels.Clear();
                foreach (var item in ChildContentChannelsList)
                {
                    var childContentChannel = contentChannelService.Get(item);
                    if (childContentChannel != null)
                    {
                        contentChannel.ChildContentChannels.Add(childContentChannel);
                    }
                }

                contentChannel.LoadAttributes(rockContext);
                Rock.Attribute.Helper.GetEditValues(phAttributes, contentChannel);

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

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    contentChannel.SaveAttributeValues(rockContext);

                    foreach (var item in new ContentChannelItemService(rockContext)
                             .Queryable()
                             .Where(i =>
                                    i.ContentChannelId == contentChannel.Id &&
                                    i.ContentChannelTypeId != contentChannel.ContentChannelTypeId
                                    ))
                    {
                        item.ContentChannelTypeId = contentChannel.ContentChannelTypeId;
                    }

                    rockContext.SaveChanges();

                    // Save the Item Attributes
                    int entityTypeId = EntityTypeCache.Get(typeof(ContentChannelItem)).Id;
                    SaveAttributes(contentChannel.Id, entityTypeId, ItemAttributesState, rockContext);
                });

                var pageReference = RockPage.PageReference;
                pageReference.Parameters.AddOrReplace("contentChannelId", contentChannel.Id.ToString());
                Response.Redirect(pageReference.BuildUrl(), false);
            }
        }
Пример #21
0
        /// <summary>
        /// Handles the Click event of the lbSave 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 lbSave_Click(object sender, EventArgs e)
        {
            if (_group != null && _occurrence != null)
            {
                var rockContext        = new RockContext();
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                DateTime startDate = _occurrence.Date;
                DateTime endDate   = _occurrence.Date.AddDays(1);

                var existingAttendees = attendanceService
                                        .Queryable("PersonAlias")
                                        .Where(a =>
                                               a.GroupId == _group.Id &&
                                               a.LocationId == _occurrence.LocationId &&
                                               a.ScheduleId == _occurrence.ScheduleId &&
                                               a.StartDateTime >= startDate &&
                                               a.StartDateTime < endDate);

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location)
                // then just delete all the attendance records instead of tracking a 'did not meet' value
                if (cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue)
                {
                    foreach (var attendance in existingAttendees)
                    {
                        attendanceService.Delete(attendance);
                    }
                }
                else
                {
                    if (cbDidNotMeet.Checked)
                    {
                        // If the occurrence is based on a schedule, set the did not meet flags
                        foreach (var attendance in existingAttendees)
                        {
                            attendance.DidAttend   = null;
                            attendance.DidNotOccur = true;
                        }
                    }

                    foreach (var attendee in _attendees)
                    {
                        var attendance = existingAttendees
                                         .Where(a => a.PersonAlias.PersonId == attendee.PersonId)
                                         .FirstOrDefault();

                        if (attendance == null)
                        {
                            int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonId);
                            if (personAliasId.HasValue)
                            {
                                attendance               = new Attendance();
                                attendance.GroupId       = _group.Id;
                                attendance.ScheduleId    = _group.ScheduleId;
                                attendance.PersonAliasId = personAliasId;
                                attendance.StartDateTime = _occurrence.Date;
                                attendance.LocationId    = _occurrence.LocationId;
                                attendance.CampusId      = locationService.GetCampusIdForLocation(_occurrence.LocationId);
                                attendance.ScheduleId    = _occurrence.ScheduleId;
                                attendanceService.Add(attendance);
                            }
                        }

                        if (attendance != null)
                        {
                            if (cbDidNotMeet.Checked)
                            {
                                attendance.DidAttend   = null;
                                attendance.DidNotOccur = true;
                            }
                            else
                            {
                                attendance.DidAttend   = attendee.Attended;
                                attendance.DidNotOccur = null;
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                WorkflowType workflowType     = null;
                Guid?        workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowTypeService = new WorkflowTypeService(rockContext);
                    workflowType = workflowTypeService.Get(workflowTypeGuid.Value);
                    if (workflowType != null)
                    {
                        try
                        {
                            var workflow = Workflow.Activate(workflowType, _group.Name);

                            workflow.SetAttributeValue("StartDateTime", _occurrence.Date.ToString("o"));
                            workflow.SetAttributeValue("Schedule", _group.Schedule.Guid.ToString());

                            List <string> workflowErrors;
                            new WorkflowService(rockContext).Process(workflow, _group, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }

                NavigateToParentPage(new Dictionary <string, string> {
                    { "GroupId", _group.Id.ToString() }
                });
            }
        }
Пример #22
0
        /// <summary>
        /// Saves the attributes.
        /// </summary>
        /// <param name="channelId">The channel identifier.</param>
        /// <param name="entityTypeId">The entity type identifier.</param>
        /// <param name="attributes">The attributes.</param>
        /// <param name="rockContext">The rock context.</param>
        private void SaveAttributes(int channelId, int entityTypeId, List <Attribute> attributes, RockContext rockContext)
        {
            string qualifierColumn = "ContentChannelId";
            string qualifierValue  = channelId.ToString();

            AttributeService attributeService = new AttributeService(rockContext);

            // Get the existing attributes for this entity type and qualifier value
            var existingAttributes = attributeService.GetByEntityTypeQualifier(entityTypeId, qualifierColumn, qualifierValue, true);

            // Delete any of those attributes that were removed in the UI
            var selectedAttributeGuids = attributes.Select(a => a.Guid);

            foreach (var attr in existingAttributes.Where(a => !selectedAttributeGuids.Contains(a.Guid)))
            {
                attributeService.Delete(attr);
            }

            rockContext.SaveChanges();

            int newOrder = 1000;

            // Update the Attributes that were assigned in the UI
            foreach (var attr in attributes.OrderBy(a => a.Order))
            {
                // Artificially exaggerate the order so that all channel specific attributes are displayed after the content-type specific attributes (unless categorized)
                attr.Order = newOrder++;
                Rock.Attribute.Helper.SaveAttributeEdits(attr, entityTypeId, qualifierColumn, qualifierValue, rockContext);
            }
        }
Пример #23
0
        /// <summary>
        /// Maps the specified folder.
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="personImageType">Type of the person image file.</param>
        /// <param name="storageProvider">The storage provider.</param>
        public void Map(ZipArchive folder, BinaryFileType personImageType, ProviderComponent storageProvider)
        {
            // check for existing images
            var lookupContext     = new RockContext();
            var existingImageList = new PersonService(lookupContext).Queryable().AsNoTracking()
                                    .Where(p => p.Photo != null)
                                    .ToDictionary(p => p.Id, p => p.Photo.CreatedDateTime);

            var emptyJsonObject = "{}";
            var newFileList     = new Dictionary <int, Rock.Model.BinaryFile>();

            int completed  = 0;
            int totalRows  = folder.Entries.Count;
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying files import ({0:N0} found.", totalRows));

            foreach (var file in folder.Entries)
            {
                var fileExtension = Path.GetExtension(file.Name);
                if (BinaryFileComponent.FileTypeBlackList.Contains(fileExtension))
                {
                    LogException("Binary File Import", string.Format("{0} filetype not allowed ({1})", fileExtension, file.Name));
                    continue;
                }

                var personForeignId = Path.GetFileNameWithoutExtension(file.Name).AsType <int?>();
                var personKeys      = BinaryFileComponent.ImportedPeople.FirstOrDefault(p => p.IndividualId == personForeignId);
                if (personKeys != null)
                {
                    // only import the most recent profile photo
                    if (!existingImageList.ContainsKey(personKeys.PersonId) || existingImageList[personKeys.PersonId].Value < file.LastWriteTime.DateTime)
                    {
                        var rockFile = new Rock.Model.BinaryFile();
                        rockFile.IsSystem         = false;
                        rockFile.IsTemporary      = false;
                        rockFile.FileName         = file.Name;
                        rockFile.BinaryFileTypeId = personImageType.Id;
                        rockFile.MimeType         = Extensions.GetMIMEType(file.Name);
                        rockFile.CreatedDateTime  = file.LastWriteTime.DateTime;
                        rockFile.ModifiedDateTime = ImportDateTime;
                        rockFile.Description      = string.Format("Imported as {0}", file.Name);
                        rockFile.SetStorageEntityTypeId(personImageType.StorageEntityTypeId);
                        rockFile.StorageEntitySettings = emptyJsonObject;

                        if (personImageType.AttributeValues.Any())
                        {
                            rockFile.StorageEntitySettings = personImageType.AttributeValues
                                                             .ToDictionary(a => a.Key, v => v.Value.Value).ToJson();
                        }

                        // use base stream instead of file stream to keep the byte[]
                        // NOTE: if byte[] converts to a string it will corrupt the stream
                        using (var fileContent = new StreamReader(file.Open()))
                        {
                            rockFile.ContentStream = new MemoryStream(fileContent.BaseStream.ReadBytesToEnd());
                        }

                        newFileList.Add(personKeys.PersonId, rockFile);
                    }

                    completed++;
                    if (completed % percentage < 1)
                    {
                        int percentComplete = completed / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} files imported ({1}% complete).", completed, percentComplete));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveFiles(newFileList, storageProvider);

                        // add image keys to master list
                        foreach (var newFile in newFileList)
                        {
                            existingImageList.AddOrReplace(newFile.Key, newFile.Value.CreatedDateTime);
                        }

                        // Reset batch list
                        newFileList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            if (newFileList.Any())
            {
                SaveFiles(newFileList, storageProvider);
            }

            ReportProgress(100, string.Format("Finished files import: {0:N0} addresses imported.", completed));
        }
Пример #24
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Determine which group to add the person to
            Group group       = null;
            int?  groupRoleId = null;

            var groupAndRoleValues = (GetAttributeValue(action, "GroupAndRole") ?? string.Empty).Split('|');

            if (groupAndRoleValues.Count() > 1)
            {
                var groupGuid = groupAndRoleValues[1].AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (groupAndRoleValues.Count() > 2)
                    {
                        var groupTypeRoleGuid = groupAndRoleValues[2].AsGuidOrNull();
                        if (groupTypeRoleGuid.HasValue)
                        {
                            var groupRole = new GroupTypeRoleService(rockContext).Get(groupTypeRoleGuid.Value);
                            if (groupRole != null)
                            {
                                groupRoleId = groupRole.Id;
                            }
                        }
                    }

                    if (!groupRoleId.HasValue && group != null)
                    {
                        // use the group's grouptype's default group role if a group role wasn't specified
                        groupRoleId = group.GroupType.DefaultGroupRoleId;
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("No group role was provided and group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = new GroupMember();
                groupMember.PersonId          = person.Id;
                groupMember.GroupId           = group.Id;
                groupMember.GroupRoleId       = groupRoleId.Value;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if (groupMember.IsValid)
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Пример #25
0
        protected void CreateActionMenu()
        {
            StringBuilder sbActions = new StringBuilder();

            // First list the actions manually entered as html in the block settting
            var actions = GetAttributeValue(AttributeKey.AdditionalCustomActions);

            if (!string.IsNullOrWhiteSpace(actions))
            {
                string appRoot   = ResolveRockUrl("~/");
                string themeRoot = ResolveRockUrl("~~/");
                actions = actions.Replace("~~/", themeRoot).Replace("~/", appRoot);

                if (actions.Contains("{0}"))
                {
                    actions = string.Format(actions, Person.Id);
                }

                sbActions.Append("<li role=\"separator\" class=\"divider\"></li>");
                sbActions.Append(actions);
            }

            // Next list the workflow actions selected in the picker
            var workflowActions = GetAttributeValue(AttributeKey.WorkflowActions);

            if (!string.IsNullOrWhiteSpace(workflowActions))
            {
                List <WorkflowType> workflowTypes = new List <WorkflowType>();

                using (var rockContext = new RockContext())
                {
                    var workflowTypeService = new WorkflowTypeService(rockContext);
                    foreach (string guidValue in workflowActions.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        Guid?guid = guidValue.AsGuidOrNull();
                        if (guid.HasValue)
                        {
                            var workflowType = workflowTypeService.Get(guid.Value);
                            if (workflowType != null && (workflowType.IsActive ?? true) && workflowType.IsAuthorized(Authorization.VIEW, CurrentPerson))
                            {
                                workflowTypes.Add(workflowType);
                            }
                        }
                    }
                }

                workflowTypes = workflowTypes.OrderBy(w => w.Name).ToList();

                if (workflowTypes.Count() > 0)
                {
                    sbActions.Append("<li role=\"separator\" class=\"divider\"></li>");
                }

                foreach (var workflowType in workflowTypes)
                {
                    string url = string.Format("~/WorkflowEntry/{0}?PersonId={1}", workflowType.Id, Person.Id);
                    sbActions.AppendFormat(
                        "<li><a href='{0}'><i class='fa-fw {1}'></i> {2}</a></li>",
                        ResolveRockUrl(url),
                        workflowType.IconCssClass,
                        workflowType.Name);
                    sbActions.AppendLine();
                }
            }

            lActions.Text = sbActions.ToString();
        }
Пример #26
0
 /// <summary>
 /// If action on the current entity is private, removes security that made it private.
 /// </summary>
 /// <param name="action">The action.</param>
 /// <param name="person">The person.</param>
 /// <param name="rockContext">The rock context.</param>
 public void MakeUnPrivate(string action, Model.Person person, RockContext rockContext = null)
 {
     Security.Authorization.MakeUnPrivate(this, action, person, rockContext);
 }
Пример #27
0
        /// <summary>
        /// Sets the name of the person.
        /// </summary>
        private void SetPersonName()
        {
            // Check if this record represents a Business.
            bool isBusiness = false;

            if (Person.RecordTypeValueId.HasValue)
            {
                int recordTypeValueIdBusiness = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

                isBusiness = (Person.RecordTypeValueId.Value == recordTypeValueIdBusiness);
            }

            // Get the Display Name.
            string nameText;

            if (isBusiness)
            {
                nameText = Person.LastName;
            }
            else
            {
                if (GetAttributeValue(AttributeKey.DisplayMiddleName).AsBoolean() && !String.IsNullOrWhiteSpace(Person.MiddleName))
                {
                    nameText = string.Format("<span class='first-word nickname'>{0}</span> <span class='middlename'>{1}</span> <span class='lastname'>{2}</span>", Person.NickName, Person.MiddleName, Person.LastName);
                }
                else
                {
                    nameText = string.Format("<span class='first-word nickname'>{0}</span> <span class='lastname'>{1}</span>", Person.NickName, Person.LastName);
                }

                // Prefix with Title if they have a Title with IsFormal=True
                if (Person.TitleValueId.HasValue)
                {
                    var personTitleValue = DefinedValueCache.Get(Person.TitleValueId.Value);
                    if (personTitleValue != null && personTitleValue.GetAttributeValue("IsFormal").AsBoolean())
                    {
                        nameText = string.Format("<span class='title'>{0}</span> ", personTitleValue.Value) + nameText;
                    }
                }

                // Add First Name if different from NickName.
                if (Person.NickName != Person.FirstName)
                {
                    if (!string.IsNullOrWhiteSpace(Person.FirstName))
                    {
                        nameText += string.Format(" <span class='firstname'>({0})</span>", Person.FirstName);
                    }
                }

                // Add Suffix.
                if (Person.SuffixValueId.HasValue)
                {
                    var suffix = DefinedValueCache.Get(Person.SuffixValueId.Value);
                    if (suffix != null)
                    {
                        nameText += " " + suffix.Value;
                    }
                }

                // Add Previous Names.
                using (var rockContext = new RockContext())
                {
                    var previousNames = Person.GetPreviousNames(rockContext).Select(a => a.LastName);

                    if (previousNames.Any())
                    {
                        nameText += string.Format(Environment.NewLine + "<span class='previous-names'>(Previous Names: {0})</span>", previousNames.ToList().AsDelimited(", "));
                    }
                }
            }

            lName.Text = nameText;
        }
Пример #28
0
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            try
            {
                int notificationsSent   = 0;
                int errorsEncountered   = 0;
                int pendingMembersCount = 0;

                // get groups set to sync
                RockContext rockContext = new RockContext();

                Guid?groupTypeGuid       = dataMap.GetString("GroupType").AsGuidOrNull();
                Guid?systemEmailGuid     = dataMap.GetString("NotificationEmail").AsGuidOrNull();
                Guid?groupRoleFilterGuid = dataMap.GetString("GroupRoleFilter").AsGuidOrNull();
                int? pendingAge          = dataMap.GetString("PendingAge").AsIntegerOrNull();


                bool includePreviouslyNotificed = dataMap.GetString("IncludePreviouslyNotified").AsBoolean();

                // get system email
                SystemEmailService emailService = new SystemEmailService(rockContext);

                SystemEmail systemEmail = null;
                if (!systemEmailGuid.HasValue || systemEmailGuid == Guid.Empty)
                {
                    context.Result = "Job failed. Unable to find System Email";
                    throw new Exception("No system email found.");
                }

                systemEmail = emailService.Get(systemEmailGuid.Value);

                // get group members
                if (!groupTypeGuid.HasValue || groupTypeGuid == Guid.Empty)
                {
                    context.Result = "Job failed. Unable to find group type";
                    throw new Exception("No group type found");
                }

                var qry = new GroupMemberService(rockContext).Queryable("Person, Group, Group.Members.GroupRole")
                          .Where(m => m.Group.GroupType.Guid == groupTypeGuid.Value &&
                                 m.GroupMemberStatus == GroupMemberStatus.Pending);

                if (!includePreviouslyNotificed)
                {
                    qry = qry.Where(m => m.IsNotified == false);
                }

                if (groupRoleFilterGuid.HasValue)
                {
                    qry = qry.Where(m => m.GroupRole.Guid == groupRoleFilterGuid.Value);
                }

                if (pendingAge.HasValue && pendingAge.Value > 0)
                {
                    var ageDate = RockDateTime.Now.AddDays(pendingAge.Value * -1);
                    qry = qry.Where(m => m.ModifiedDateTime > ageDate);
                }

                var pendingGroupMembers = qry.ToList();

                var groups = pendingGroupMembers.GroupBy(m => m.Group);

                var errorList = new List <string>();
                foreach (var groupKey in groups)
                {
                    var group = groupKey.Key;

                    // get list of pending people
                    var qryPendingIndividuals = group.Members.Where(m => m.GroupMemberStatus == GroupMemberStatus.Pending);

                    if (!includePreviouslyNotificed)
                    {
                        qryPendingIndividuals = qryPendingIndividuals.Where(m => m.IsNotified == false);
                    }

                    if (groupRoleFilterGuid.HasValue)
                    {
                        qryPendingIndividuals = qryPendingIndividuals.Where(m => m.GroupRole.Guid == groupRoleFilterGuid.Value);
                    }

                    var pendingIndividuals = qryPendingIndividuals.Select(m => m.Person).ToList();

                    if (!pendingIndividuals.Any())
                    {
                        continue;
                    }

                    // get list of leaders
                    var groupLeaders = group.Members.Where(m => m.GroupRole.IsLeader == true && m.Person != null && m.Person.Email != null && m.Person.Email != string.Empty);

                    if (!groupLeaders.Any())
                    {
                        errorList.Add("Unable to send emails to members in group " + group.Name + " because there is no group leader");
                        continue;
                    }

                    var recipients = new List <RockEmailMessageRecipient>();
                    foreach (var leader in groupLeaders)
                    {
                        // create merge object
                        var mergeFields = new Dictionary <string, object>();
                        mergeFields.Add("PendingIndividuals", pendingIndividuals);
                        mergeFields.Add("Group", group);
                        mergeFields.Add("ParentGroup", group.ParentGroup);
                        mergeFields.Add("Person", leader.Person);
                        recipients.Add(new RockEmailMessageRecipient(leader.Person, mergeFields));
                    }


                    var errorMessages = new List <string>();
                    var emailMessage  = new RockEmailMessage(systemEmail.Guid);
                    emailMessage.SetRecipients(recipients);
                    var sendSuccess = emailMessage.Send(out errorMessages);

                    errorsEncountered += errorMessages.Count;
                    errorList.AddRange(errorMessages);

                    // be conservative: only mark as notified if we are sure the email didn't fail
                    if (sendSuccess == false)
                    {
                        continue;
                    }

                    notificationsSent += recipients.Count();
                    // mark pending members as notified as we go in case the job fails
                    var notifiedPersonIds = pendingIndividuals.Select(p => p.Id);
                    foreach (var pendingGroupMember in pendingGroupMembers.Where(m => m.IsNotified == false && m.GroupId == group.Id && notifiedPersonIds.Contains(m.PersonId)))
                    {
                        pendingGroupMember.IsNotified = true;
                    }

                    rockContext.SaveChanges();
                }

                context.Result = string.Format("Sent {0} emails to leaders for {1} pending individuals. {2} errors encountered.", notificationsSent, pendingMembersCount, errorsEncountered);
                if (errorList.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append("Errors in GroupLeaderPendingNotificationJob: ");
                    errorList.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errors = sb.ToString();
                    context.Result += errors;
                    throw new Exception(errors);
                }
            }
            catch (Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
Пример #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RestControllerService"/> class
 /// </summary>
 /// <param name="context">The context.</param>
 public RestControllerService(RockContext context) : base(context)
 {
 }
        /// <summary>
        /// Operations to be performed during the upgrade process.
        /// </summary>
        public override void Up()
        {
            var rockContext = new RockContext();

            var discWorkflowGuid = new Guid( "885CBA61-44EA-4B4A-B6E1-289041B6A195" );
            var discWorkflowNotEdited = new WorkflowTypeService( rockContext ).Queryable()
                                                .Where( w => w.Guid == discWorkflowGuid && w.ModifiedDateTime == null )
                                                .Any();

            if ( discWorkflowNotEdited )
            {
                // add person attribute to store last DISC request date
                RockMigrationHelper.UpdatePersonAttribute( Rock.SystemGuid.FieldType.DATE, "0B187C81-2106-4875-82B6-FBF1277AE23B", "Last DISC Request Date", "LastDiscRequestDate", "fa fa-bar-chart", "The date the last DISC request was sent.", 9, string.Empty, "41B73365-A984-879E-4749-7DB4FC720138" );

                RockMigrationHelper.UpdateWorkflowTypeAttribute( "885CBA61-44EA-4B4A-B6E1-289041B6A195", "9C204CD0-1233-41C5-818A-C5DA439445AA", "No Email Warning", "NoEmailWarning", "Warning message when the person does not have an email address.", 5, @"", "BB2B3CF8-7C81-4EBD-9589-A961E341F70C" ); // DISC Request:No Email Warning}

                RockMigrationHelper.UpdateWorkflowActionType( "4A8E2E61-FE0D-4AB3-BA48-9419A20E4541", "Set No Email Warning", 5, "A41216D6-6FB0-4019-B222-2C29B4519CF4", true, false, "", "", 1, "", "940E88E7-1294-4DD7-A626-E1345A41A2D1" ); // DISC Request:Launch From Person Profile:Set No Email Warning
                RockMigrationHelper.AddActionTypeAttributeValue( "940E88E7-1294-4DD7-A626-E1345A41A2D1", "FA7C685D-8636-41EF-9998-90FFF3998F76", @"" ); // DISC Request:Launch From Person Profile:Set No Email Warning:Order
                RockMigrationHelper.AddActionTypeAttributeValue( "940E88E7-1294-4DD7-A626-E1345A41A2D1", "F3B9908B-096F-460B-8320-122CF046D1F9", @"DECLARE @PersonAliasGuid uniqueidentifier = '{{ Workflow.Person_unformatted }}'

            SELECT  CASE
            WHEN EXISTS ( SELECT 1
            FROM [Person] P
            INNER JOIN [PersonAlias] PA ON PA.[Guid] = @PersonAliasGuid AND P.[Id] = PA.[PersonId]
            WHERE P.[IsEmailActive] <> 0 AND P.[Email] IS NOT NULL AND P.[Email] != '' )
            THEN 'True'
            ELSE 'False'
            END" ); // DISC Request:Launch From Person Profile:Set No Email Warning:SQLQuery
                RockMigrationHelper.AddActionTypeAttributeValue( "940E88E7-1294-4DD7-A626-E1345A41A2D1", "A18C3143-0586-4565-9F36-E603BC674B4E", @"False" ); // DISC Request:Launch From Person Profile:Set No Email Warning:Active
                RockMigrationHelper.AddActionTypeAttributeValue( "940E88E7-1294-4DD7-A626-E1345A41A2D1", "56997192-2545-4EA1-B5B2-313B04588984", @"bb2b3cf8-7c81-4ebd-9589-a961e341f70c" ); // DISC Request:Launch From Person Profile:Set No Email Warning:Result Attribute

                RockMigrationHelper.UpdateWorkflowActionType( "4A8E2E61-FE0D-4AB3-BA48-9419A20E4541", "Set No Email Warning Message", 6, "C789E457-0783-44B3-9D8F-2EBAB5F11110", true, false, "", "BB2B3CF8-7C81-4EBD-9589-A961E341F70C", 1, "False", "3FAC4206-D572-4BB7-84A8-9FF817C96302" ); // DISC Request:Launch From Person Profile:Set No Email Warning Message
                RockMigrationHelper.AddActionTypeAttributeValue( "3FAC4206-D572-4BB7-84A8-9FF817C96302", "57093B41-50ED-48E5-B72B-8829E62704C8", @"" ); // DISC Request:Launch From Person Profile:Set No Email Warning Message:Order
                RockMigrationHelper.AddActionTypeAttributeValue( "3FAC4206-D572-4BB7-84A8-9FF817C96302", "D7EAA859-F500-4521-9523-488B12EAA7D2", @"False" ); // DISC Request:Launch From Person Profile:Set No Email Warning Message:Active
                RockMigrationHelper.AddActionTypeAttributeValue( "3FAC4206-D572-4BB7-84A8-9FF817C96302", "44A0B977-4730-4519-8FF6-B0A01A95B212", @"bb2b3cf8-7c81-4ebd-9589-a961e341f70c" ); // DISC Request:Launch From Person Profile:Set No Email Warning Message:Attribute
                RockMigrationHelper.AddActionTypeAttributeValue( "3FAC4206-D572-4BB7-84A8-9FF817C96302", "E5272B11-A2B8-49DC-860D-8D574E2BC15C", @"<div class=""alert alert-warning margin-t-sm"">{{ Workflow.Person }} does not have an active email address. Please add an address to their record.</div>" ); // DISC Request:Launch From Person Profile:Set No Email Warning Message:Text Value|Attribute Value

                RockMigrationHelper.UpdateWorkflowActionType( "4A8E2E61-FE0D-4AB3-BA48-9419A20E4541", "Update Request Person Attribute", 9, "320622DA-52E0-41AE-AF90-2BF78B488552", true, false, "", "", 1, "", "42401767-F313-4AAE-BE46-AD557F970847" ); // DISC Request:Launch From Person Profile:Update Request Person Attribute
                RockMigrationHelper.AddActionTypeAttributeValue( "42401767-F313-4AAE-BE46-AD557F970847", "E5BAC4A6-FF7F-4016-BA9C-72D16CB60184", @"False" ); // DISC Request:Launch From Person Profile:Update Request Person Attribute:Active
                RockMigrationHelper.AddActionTypeAttributeValue( "42401767-F313-4AAE-BE46-AD557F970847", "E456FB6F-05DB-4826-A612-5B704BC4EA13", @"c0bc984c-84c3-494b-a861-49840e452f68" ); // DISC Request:Launch From Person Profile:Update Request Person Attribute:Person
                RockMigrationHelper.AddActionTypeAttributeValue( "42401767-F313-4AAE-BE46-AD557F970847", "3F3BF3E6-AD53-491E-A40F-441F2AFCBB5B", @"" ); // DISC Request:Launch From Person Profile:Update Request Person Attribute:Order
                RockMigrationHelper.AddActionTypeAttributeValue( "42401767-F313-4AAE-BE46-AD557F970847", "8F4BB00F-7FA2-41AD-8E90-81F4DFE2C762", @"41b73365-a984-879e-4749-7db4fc720138" ); // DISC Request:Launch From Person Profile:Update Request Person Attribute:Person Attribute
                RockMigrationHelper.AddActionTypeAttributeValue( "42401767-F313-4AAE-BE46-AD557F970847", "94689BDE-493E-4869-A614-2D54822D747C", @"{{ 'Now' | Date:'M/d/yyyy' }}" ); // DISC Request:Launch From Person Profile:Update Request Person Attribute:Value|Attribute Value

                // reorder actions
                Sql( @"
            -- set no email warning flag
              UPDATE  [WorkflowActionType]
            SET [Order] = 6
            WHERE [Guid] = '940E88E7-1294-4DD7-A626-E1345A41A2D1'

              -- set no email warning message
              UPDATE  [WorkflowActionType]
            SET [Order] = 7
            WHERE [Guid] = '3FAC4206-D572-4BB7-84A8-9FF817C96302'

              -- custom messgae
              UPDATE  [WorkflowActionType]
            SET [Order] = 8
            WHERE [Guid] = '1A08A4EC-B2C6-43B5-926F-2F86CFA35102'

              -- persist workflow
              UPDATE  [WorkflowActionType]
            SET [Order] = 9
            WHERE [Guid] = '555A729C-5EC4-4C83-B35F-036234E5EFCC'

            -- send email
            UPDATE  [WorkflowActionType]
            SET [Order] = 10
            WHERE [Guid] = '666FC137-BC95-49BE-A976-0BFF2417F44C'

            -- update person attribute
            UPDATE  [WorkflowActionType]
            SET [Order] = 11
            WHERE [Guid] = '42401767-F313-4AAE-BE46-AD557F970847'

            -- workflow complete
            UPDATE  [WorkflowActionType]
            SET [Order] = 12
            WHERE [Guid] = 'EA4FF8DD-0E66-4C98-84FC-845DEAB76A61'" );

                // update form header with new warning message
                Sql( @"  UPDATE [WorkflowActionForm]
              SET [Header] = 'Hi &#123;&#123; Person.NickName &#125;&#125;!

            {{ Workflow.WarningMessage }}
            {{ Workflow.NoEmailWarning }}'
              WHERE [Guid] = '4AFAB342-D584-4B79-B038-A99C0C469D74'" );

            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ContentChannelTypeService"/> class
 /// </summary>
 /// <param name="context">The context.</param>
 public ContentChannelTypeService(RockContext context) : base(context)
 {
 }