public static void RemoveAttendance(Attendance attendance)
        {
            lock ( LOCK )
            {
                var lglsc = (List <GroupLocationScheduleCount>)RockCache.Get(cacheKey);
                if (lglsc == null)
                {
                    lglsc = UpdateCache();
                }

                var personId = attendance.PersonAlias.PersonId;

                var items = lglsc.Where(g =>
                                        g.LocationId == attendance.Occurrence.LocationId &&
                                        g.ScheduleId == attendance.Occurrence.ScheduleId &&
                                        g.GroupId == attendance.Occurrence.GroupId)
                            .ToList();

                foreach (var glsc in items)
                {
                    while (glsc.PersonIds.Contains(personId))
                    {
                        glsc.PersonIds.Remove(personId);
                    }
                    while (glsc.InRoomPersonIds.Contains(personId))
                    {
                        glsc.InRoomPersonIds.Remove(personId);
                    }
                    RockCache.AddOrUpdate(cacheKey, null, lglsc, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
                }
            }
        }
        private static List <GroupLocationScheduleCount> UpdateCache()
        {
            var output = new List <GroupLocationScheduleCount>();

            RockContext rockContext = new RockContext();

            AttendanceOccurrenceService attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);
            var attendances = attendanceOccurrenceService.Queryable()
                              .Where(ao => ao.OccurrenceDate == RockDateTime.Today)
                              .SelectMany(ao => ao.Attendees)
                              .Where(a => a.EndDateTime == null)
                              .GroupBy(a => new { a.Occurrence.GroupId, a.Occurrence.LocationId, a.Occurrence.ScheduleId })
                              .ToList();

            foreach (var attendance in attendances)
            {
                var glsc = new GroupLocationScheduleCount()
                {
                    GroupId         = attendance.Key.GroupId ?? 0,
                    LocationId      = attendance.Key.LocationId ?? 0,
                    ScheduleId      = attendance.Key.ScheduleId ?? 0,
                    PersonIds       = attendance.Select(a => a.PersonAlias?.PersonId ?? 0).ToList(),
                    InRoomPersonIds = attendance.Where(a => a.DidAttend == true).Select(a => a.PersonAlias?.PersonId ?? 0).ToList()
                };
                output.Add(glsc);
            }

            RockCache.AddOrUpdate(cacheKey, null, output, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            return(output);
        }
        private List <Group> GetBreakoutGroups(Person person, RockContext rockContext, WorkflowAction action)
        {
            if (!string.IsNullOrWhiteSpace(GetAttributeValue(action, "BreakoutGroupType")))
            {
                List <Group> allBreakoutGroups = RockCache.Get(cacheKey) as List <Group>;
                if (allBreakoutGroups == null || !allBreakoutGroups.Any())
                {
                    //If the cache is empty, fill it up!
                    Guid breakoutGroupTypeGuid = GetAttributeValue(action, "BreakoutGroupType").AsGuid();
                    var  breakoutGroups        = new GroupService(rockContext)
                                                 .Queryable("Members")
                                                 .AsNoTracking()
                                                 .Where(g => g.GroupType.Guid == breakoutGroupTypeGuid && g.IsActive && !g.IsArchived)
                                                 .ToList();

                    allBreakoutGroups = new List <Group>();

                    foreach (var breakoutGroup in breakoutGroups)
                    {
                        allBreakoutGroups.Add(breakoutGroup.Clone(false));
                    }

                    RockCache.AddOrUpdate(cacheKey, null, allBreakoutGroups, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
                }

                return(allBreakoutGroups.Where(g => g.Members
                                               .Where(gm => gm.PersonId == person.Id && gm.GroupMemberStatus == GroupMemberStatus.Active).Any() &&
                                               g.IsActive && !g.IsArchived)
                       .ToList());
            }
            else
            {
                return(new List <Group>());
            }
        }
Пример #4
0
        /// <summary>
        /// Gets the roles.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private static List <int> GetRoles(RockContext rockContext)
        {
            string cacheKey = "Rock.FindRelationships.Roles";

            List <int> roles = RockCache.Get(cacheKey) as List <int>;

            if (roles == null)
            {
                roles = new List <int>();

                foreach (var role in new GroupTypeRoleService(rockContext)
                         .Queryable().AsNoTracking()
                         .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS))))
                {
                    role.LoadAttributes(rockContext);
                    if (role.Attributes.ContainsKey("CanCheckin"))
                    {
                        bool canCheckIn = false;
                        if (bool.TryParse(role.GetAttributeValue("CanCheckin"), out canCheckIn) && canCheckIn)
                        {
                            roles.Add(role.Id);
                        }
                    }
                }

                RockCache.AddOrUpdate(cacheKey, null, roles, RockDateTime.Now.AddSeconds(300));
            }

            return(roles);
        }
Пример #5
0
        /// <summary>
        /// Inserts travel time from an origin to a set of destination objects.
        /// </summary>
        /// <param name="origin">The origin address</param>
        /// <param name="destinations">List of destination objects</param>
        public void LoadDurations(string origin, List <Destination> destinations)
        {
            foreach (var destination in destinations)
            {
                var destinationCache = RockCache.Get(origin + destination.Address, "org.secc.Mapping.LocationDistance") as Destination;
                if (destinationCache != null)
                {
                    destination.TravelDistance = destinationCache.TravelDistance;
                    destination.TravelDuration = destinationCache.TravelDuration;
                    destination.IsCalculated   = true;
                }
            }
            var searchList = destinations.Where(d => d.IsCalculated == false).Select(d => d.Address);

            var locationDistances = this.Queryable().Where(d => d.Origin == origin && searchList.Contains(d.Destination));

            foreach (var locationDistance in locationDistances)
            {
                var destinationItems = destinations.Where(d => d.Address == locationDistance.Destination);
                foreach (var destinationItem in destinationItems)
                {
                    destinationItem.TravelDuration = locationDistance.TravelDuration;
                    destinationItem.TravelDistance = locationDistance.TravelDistance;
                    destinationItem.IsCalculated   = true;
                    RockCache.AddOrUpdate(origin + destinationItem.Address, "org.secc.Mapping.LocationDistance", destinationItem);
                }
            }
        }
Пример #6
0
        private static List <Rock.Model.Group> GetBreakoutGroups(Person person, RockContext rockContext)
        {
            List <Rock.Model.Group> allBreakoutGroups = RockCache.Get(cacheKey) as List <Rock.Model.Group>;

            if (allBreakoutGroups == null || !allBreakoutGroups.Any())
            {
                //If the cache is empty, fill it up!
                Guid breakoutGroupTypeGuid = Constants.GROUP_TYPE_BREAKOUT_GROUPS.AsGuid();
                var  breakoutGroups        = new GroupService(rockContext)
                                             .Queryable("Members")
                                             .AsNoTracking()
                                             .Where(g => g.GroupType.Guid == breakoutGroupTypeGuid && g.IsActive && !g.IsArchived)
                                             .ToList();

                allBreakoutGroups = new List <Rock.Model.Group>();

                foreach (var breakoutGroup in breakoutGroups)
                {
                    allBreakoutGroups.Add(breakoutGroup.Clone(false));
                }

                RockCache.AddOrUpdate(cacheKey, null, allBreakoutGroups, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            }

            return(allBreakoutGroups.Where(g => g.Members
                                           .Where(gm => gm.PersonId == person.Id && gm.GroupMemberStatus == GroupMemberStatus.Active).Any() &&
                                           g.IsActive && !g.IsArchived)
                   .ToList());
        }
Пример #7
0
        /// <summary>
        /// This fetches a dimension's related data.
        /// </summary>
        /// <returns>List of RestrictedData objects.</returns>
        public List <RestrictedData> GetDimensionRestrictedData(IntacctModel model)
        {
            string cacheKey             = INTACCT_CACHE_PREFIX + model.GetType().Name.ToUpper() + "_" + model.Id;
            List <RestrictedData> items = RockCache.Get(cacheKey) as List <RestrictedData>;

            if (items == null)
            {
                var request = GetRequest();
                var getDimensionRestrictedData = new GetDimensionRestrictedData();
                getDimensionRestrictedData.Function.DimensionValue.Dimension = model.GetType().Name.ToUpper();
                getDimensionRestrictedData.Function.DimensionValue.Value     = model.ApiId;
                request.Operation.Content.Function = getDimensionRestrictedData;

                var restRequest = new RestRequest("", Method.POST);
                restRequest.AddHeader("Content-Type", "application/xml");
                restRequest.RequestFormat = DataFormat.Xml;
                restRequest.AddBody(request);

                var response = client.Execute <List <RestrictedData> >(restRequest);

                var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();
                var responseObj     = xmlDeserializer.Deserialize <Response>(response);
                if (responseObj?.Operation?.Result?.Status != "success" && !string.IsNullOrWhiteSpace(responseObj?.ErrorMessage?.Error?.Description))
                {
                    CheckResponse(response);
                }

                items = response.Data;

                RockCache.AddOrUpdate(cacheKey, items);
            }
            return(items);
        }
Пример #8
0
        public static T Get(string qualifiedKey, Func <T> itemFactory, Func <List <string> > keyFactory)
        {
            var item = ( T )RockCache.Get(qualifiedKey);

            if (item != null)
            {
                return(item);
            }

            item = itemFactory();
            if (item != null)
            {
                var keys = AllKeys();
                if (!keys.Any() || !keys.Contains(qualifiedKey))
                {
                    UpdateKeys(keyFactory);
                }

                RockCache.AddOrUpdate(qualifiedKey, item);
            }
            else
            {
                //This item is gone! Make sure it's not in our key list
                UpdateKeys(keyFactory);
            }

            return(item);
        }
Пример #9
0
        private static List <string> UpdateKeys(Func <List <string> > keyFactory)
        {
            var keys = keyFactory().Select(k => QualifiedKey(k)).ToList();

            RockCache.AddOrUpdate(AllKey, AllRegion, keys);

            return(keys);
        }
Пример #10
0
        private List <T> ReadByQuery <T>() where T : IntacctModel
        {
            string operation = typeof(T).Name.ToUpper();

            string   cacheKey = INTACCT_CACHE_PREFIX + operation;
            List <T> items    = RockCache.Get(cacheKey) as List <T>;

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

                var request = GetRequest();
                request.Operation.Content.Function = new ReadByQuery(operation);

                var restRequest = new RestRequest("", Method.POST);
                restRequest.AddHeader("Content-Type", "application/xml");
                restRequest.RequestFormat = DataFormat.Xml;
                restRequest.AddBody(request);

                var response = client.Execute <List <T> >(restRequest);
                CheckResponse(response);

                var    responseObj  = new RestSharp.Deserializers.XmlDeserializer().Deserialize <Response>(response);
                int?   numRemaining = responseObj?.Operation?.Result?.Data?.NumRemaining ?? 0;
                string resultId     = responseObj?.Operation?.Result?.Data?.ResultId;
                items.AddRange(response.Data);

                while (numRemaining != 0 && !string.IsNullOrWhiteSpace(resultId))
                {
                    restRequest = new RestRequest("", Method.POST);
                    restRequest.AddHeader("Content-Type", "application/xml");
                    restRequest.RequestFormat = DataFormat.Xml;

                    request.Operation.Content.Function = new ReadMore(resultId);
                    restRequest.AddBody(request);

                    response = client.Execute <List <T> >(restRequest);
                    CheckResponse(response);

                    responseObj  = new RestSharp.Deserializers.XmlDeserializer().Deserialize <Response>(response);
                    numRemaining = responseObj?.Operation?.Result?.Data?.NumRemaining ?? 0;
                    items.AddRange(response.Data);
                }


                RockCache.AddOrUpdate(cacheKey, items);
            }
            return(items);
        }
Пример #11
0
        public static void AddOrUpdate(string qualifiedKey, T item, Func <List <string> > keyFactory)
        {
            if (item == null)
            {
                return;
            }

            var keys = AllKeys();

            if (!keys.Any() || !keys.Contains(qualifiedKey))
            {
                UpdateKeys(keyFactory);
            }

            //RockCacheManager<T>.Instance.Cache.AddOrUpdate( qualifiedKey, item, v => item );
            RockCache.AddOrUpdate(qualifiedKey, item);
        }
Пример #12
0
        /// <summary>
        /// Creates a recipient token to help track conversations.
        /// </summary>
        /// <param name="rockContext">A context to use for database calls.</param>
        /// <returns>String token</returns>
        public static string GenerateResponseCode(Rock.Data.RockContext rockContext)
        {
            DateTime tokenStartDate = RockDateTime.Now.Subtract(new TimeSpan(TOKEN_REUSE_DURATION, 0, 0, 0));
            var      communicationRecipientService = new CommunicationRecipientService(rockContext);

            lock ( _responseCodesLock )
            {
                var availableResponseCodes = RockCache.Get(RESPONSE_CODE_CACHE_KEY) as List <string>;

                //
                // Try up to 1,000 times to find a code. This really should never go past the first
                // loop but we will give the benefit of the doubt in case a code is issued via SQL.
                //
                for (int attempts = 0; attempts < 1000; attempts++)
                {
                    if (availableResponseCodes == null || !availableResponseCodes.Any())
                    {
                        availableResponseCodes = GenerateAvailableResponseCodeList(rockContext);
                    }

                    var code = availableResponseCodes[0];
                    availableResponseCodes.RemoveAt(0);

                    //
                    // Verify that the code is still unused.
                    //
                    var isUsed = communicationRecipientService.Queryable()
                                 .Where(c => c.ResponseCode == code)
                                 .Where(c => c.CreatedDateTime.HasValue && c.CreatedDateTime > tokenStartDate)
                                 .Any();

                    if (!isUsed)
                    {
                        RockCache.AddOrUpdate(RESPONSE_CODE_CACHE_KEY, availableResponseCodes);
                        return(code);
                    }
                }
            }

            throw new Exception("Could not find an available response code.");
        }
Пример #13
0
        protected void StartApiSession()
        {
            string     cacheKey   = "org.secc.Purchasing.Intacct.ApiSession";
            ApiSession apiSession = RockCache.Get(cacheKey) as ApiSession;

            if (apiSession == null)
            {
                var request = GetRequest(false);
                request.Operation.Content.Function = new GetAPISession();

                // Set the login information in the request
                Login login = new Login();
                login.CompanyId = CompanyId;
                login.UserId    = UserId;
                login.Password  = Password;
                request.Operation.Authentication.Login = login;

                var restRequest = new RestRequest("", Method.POST);
                restRequest.AddHeader("Content-Type", "application/xml");
                restRequest.RequestFormat = DataFormat.Xml;
                restRequest.AddBody(request);


                var response = client.Execute <ApiSession>(restRequest);
                CheckResponse(response);

                apiSession = response.Data;

                // Fetch the expiration date too (expire cache 30 minutes before the session ends)
                var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();
                var auth            = xmlDeserializer.Deserialize <Authentication>(response);

                CacheTimeout = DateTime.Now.AddHours(2);

                RockCache.AddOrUpdate(cacheKey, null, apiSession, CacheTimeout, INTACCT_CACHE_TAG);
                ;
            }
            Session = apiSession.SessionId;
        }
        public static void AddAttendance(Attendance attendance)
        {
            lock ( LOCK )
            {
                var lglsc = (List <GroupLocationScheduleCount>)RockCache.Get(cacheKey);
                if (lglsc == null)
                {
                    lglsc = UpdateCache();
                }
                GroupLocationScheduleCount glsc = lglsc.FirstOrDefault(g =>
                                                                       g.LocationId == (attendance.Occurrence.LocationId ?? 0) &&
                                                                       g.ScheduleId == (attendance.Occurrence.ScheduleId ?? 0) &&
                                                                       g.GroupId == (attendance.Occurrence.GroupId ?? 0));
                if (glsc == null)
                {
                    glsc = new GroupLocationScheduleCount()
                    {
                        LocationId      = attendance.Occurrence.LocationId ?? 0,
                        ScheduleId      = attendance.Occurrence.ScheduleId ?? 0,
                        GroupId         = attendance.Occurrence.GroupId ?? 0,
                        PersonIds       = new List <int>(),
                        InRoomPersonIds = new List <int>()
                    };
                    lglsc.Add(glsc);
                }


                if (!glsc.PersonIds.Contains(attendance.PersonAlias?.PersonId ?? 0))
                {
                    glsc.PersonIds.Add(attendance.PersonAlias.PersonId);
                }

                if (attendance.DidAttend == true && !glsc.InRoomPersonIds.Contains(attendance.PersonAlias?.PersonId ?? 0))
                {
                    glsc.InRoomPersonIds.Add(attendance.PersonAlias.PersonId);
                }
                RockCache.AddOrUpdate(cacheKey, null, lglsc, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            }
        }
Пример #15
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            RockPage page = HttpContext.Current.Handler as RockPage;

            var parms = ParseMarkup(_markup, context);

            using (TextWriter twStylesheet = new StringWriter())
            {
                base.Render(context, twStylesheet);

                var stylesheet = twStylesheet.ToString();

                if (parms.ContainsKey("compile"))
                {
                    if (parms["compile"] == "less")
                    {
                        DotlessConfiguration dotLessConfiguration = new DotlessConfiguration();
                        dotLessConfiguration.MinifyOutput = true;

                        if (parms.ContainsKey("import"))
                        {
                            // import statements should go at the end to allow for default variable assignment in the beginning
                            // to help reduce the number of Less errors we automatically add the bootstrap and core rock variables files
                            var importStatements = string.Empty;

                            var importSource = "~/Styles/Bootstrap/variables.less,~/Styles/_rock-variables.less," + parms["import"];

                            var importFiles = importSource.Split(',');
                            foreach (var importFile in importFiles)
                            {
                                var filePath = string.Empty;
                                if (!importFile.StartsWith("~"))
                                {
                                    filePath = $"~~/Styles/{importFile}";
                                }
                                else
                                {
                                    filePath = importFile;
                                }

                                filePath = page.ResolveRockUrl(filePath);

                                var fullPath = page.MapPath("~/") + filePath;

                                if (File.Exists(fullPath))
                                {
                                    importStatements = $"{importStatements}{Environment.NewLine}@import \"{fullPath}\";";
                                }
                            }

                            stylesheet = $"{stylesheet}{Environment.NewLine}{importStatements}";
                        }

                        // ok we have our less stylesheet let's see if it's been cached (less can take ~100ms to compile so let's try not to do that if necessary)
                        if (parms.ContainsKey("cacheduration"))
                        {
                            var cacheKey         = stylesheet.GetHashCode().ToString();
                            var cachedStylesheet = RockCache.Get(cacheKey) as string;

                            if (cachedStylesheet.IsNotNullOrWhiteSpace())
                            {
                                stylesheet = cachedStylesheet;
                            }
                            else
                            {
                                stylesheet = LessWeb.Parse(stylesheet, dotLessConfiguration);

                                // check if we should cache this
                                if (parms.ContainsKey("cacheduration") && stylesheet.IsNotNullOrWhiteSpace())
                                {
                                    int cacheDuration = 0;
                                    Int32.TryParse(parms["cacheduration"], out cacheDuration);

                                    if (cacheDuration > 0)
                                    {
                                        RockCache.AddOrUpdate(cacheKey, null, stylesheet, RockDateTime.Now.AddSeconds(cacheDuration));
                                    }
                                }
                            }
                        }
                        else
                        {
                            stylesheet = LessWeb.Parse(stylesheet, dotLessConfiguration);
                        }
                    }

                    if (stylesheet == string.Empty)
                    {
                        if (parms.ContainsKey("id"))
                        {
                            result.Write($"An error occurred compiling the Less for this stylesheet (id: {parms["id"]}).");
                        }
                        else
                        {
                            result.Write("An error occurred compiling the Less for this stylesheet.");
                        }
                        return;
                    }
                }

                if (parms.ContainsKey("id"))
                {
                    var identifier = parms["id"];
                    if (identifier.IsNotNullOrWhiteSpace())
                    {
                        var controlId = "css-" + identifier;

                        var cssControl = page.Header.FindControl(controlId);
                        if (cssControl == null)
                        {
                            cssControl    = new System.Web.UI.LiteralControl($"{Environment.NewLine}<style>{stylesheet}</style>{Environment.NewLine}");
                            cssControl.ID = controlId;
                            page.Header.Controls.Add(cssControl);
                        }
                    }
                }
                else
                {
                    page.Header.Controls.Add(new System.Web.UI.LiteralControl($"{Environment.NewLine}<style>{stylesheet}</style>{Environment.NewLine}"));
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Loads and displays the event item occurrences
        /// </summary>
        private void BindData()
        {
            List <int> campusIds  = cblCampus.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();
            List <int> categories = cblCategory.Items.OfType <ListItem>().Where(l => l.Selected).Select(a => a.Value.AsInteger()).ToList();

            var cacheKey = string.Format("{0}^{1}^{2}CalendarLava",
                                         string.Join("-", campusIds),
                                         string.Join("-", categories),
                                         BlockCache.Id.ToString());
            var content = RockCache.Get(cacheKey, System.Globalization.CultureInfo.CurrentCulture.ToString());

            if (content != null && !string.IsNullOrWhiteSpace(( string )content))
            {
                lOutput.Text = ( string )content;
                return;
            }

            var rockContext = new RockContext();
            var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);
            var attributeService           = new AttributeService(rockContext);
            var attributeValueService      = new AttributeValueService(rockContext);

            int calendarItemEntityTypeId        = EntityTypeCache.GetId(typeof(EventCalendarItem)).Value;
            int eventItemOccurrenceEntityTypeId = EntityTypeCache.GetId(typeof(EventItemOccurrence)).Value;

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

            var qry = firstQry
                      .GroupJoin(
                attributeValueService.Queryable().Where(av => av.Attribute.EntityTypeId == ( int? )calendarItemEntityTypeId || av.Attribute.EntityTypeId == ( int? )eventItemOccurrenceEntityTypeId),
                obj => obj.EventItem.EventCalendarItems.Where(i => i.EventCalendarId == _calendarId).Select(i => i.Id).FirstOrDefault(),
                av => av.EntityId,
                (obj, av) => new
            {
                EventItemOccurrence = obj,
                EventCalendarItemAttributeValues = av,
            })
                      .GroupJoin(
                attributeValueService.Queryable().Where(av => av.Attribute.EntityTypeId == ( int? )eventItemOccurrenceEntityTypeId),
                obj => obj.EventItemOccurrence.Id,
                av => av.EntityId,
                (obj, av) => new
            {
                EventItemOccurrence = obj.EventItemOccurrence,
                EventCalendarItemAttributeValues   = obj.EventCalendarItemAttributeValues,
                EventItemOccurrenceAttributeValues = av
            }
                );


            // Filter by campus
            if (campusIds.Any())
            {
                qry = qry
                      .Where(c =>
                             !c.EventItemOccurrence.CampusId.HasValue || // All
                             campusIds.Contains(c.EventItemOccurrence.CampusId.Value));
            }

            // Filter by Category
            if (categories.Any())
            {
                qry = qry
                      .Where(i => i.EventItemOccurrence.EventItem.EventItemAudiences
                             .Any(c => categories.Contains(c.DefinedValueId)));
            }

            // Get the beginning and end dates
            var today       = RockDateTime.Now;
            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);

            var scheduleEntityType = EntityTypeCache.Get(Rock.SystemGuid.EntityType.SCHEDULE).Id;
            var attributeId        = attributeService.Queryable()
                                     .Where(a => a.EntityTypeId == scheduleEntityType && a.Key == "NextStartDate")
                                     .FirstOrDefault()
                                     .Id;

            // Get the occurrences
            var occurrences = qry
                              .Where(o => o.EventItemOccurrence.Schedule != null)
                              .ToList();

            var eventSchedules = occurrences.Select(o => o.EventItemOccurrence.Schedule.Id).ToList();

            var schedules = attributeValueService.Queryable()
                            .Where(av => av.AttributeId == attributeId)
                            .Where(av => eventSchedules.Contains(av.EntityId ?? 0))
                            .ToDictionary(av => av.EntityId, av => av.Value);

            var occurrencesWithDates = occurrences
                                       .Select(o => new EventOccurrenceDate
            {
                EventItemOccurrence = o.EventItemOccurrence,
                EventCalendarItemAttributeValues   = o.EventCalendarItemAttributeValues,
                EventItemOccurrenceAttributeValues = o.EventItemOccurrenceAttributeValues,
                Date = schedules.ContainsKey(o.EventItemOccurrence.Schedule.Id) ? schedules[o.EventItemOccurrence.Schedule.Id].AsDateTime() ?? new DateTime() : new DateTime()
            })
                                       .Where(d => d.Date >= RockDateTime.Today)
                                       .ToList();

            var priorityAttributeKey = GetAttributeValue("PriorityAttributeKey");

            var eventOccurrenceSummaries = new List <EventOccurrenceSummary>();

            foreach (var occurrenceDates in occurrencesWithDates)
            {
                var eventItemOccurrence = occurrenceDates.EventItemOccurrence;

                if (occurrenceDates.Date >= beginDate && occurrenceDates.Date < endDate)
                {
                    var primaryMinistry          = DefinedValueCache.Get(occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "PrimaryMinistry").Select(av => av.Value).FirstOrDefault());
                    var primaryMinistryImageGuid = "";
                    var primaryMinistryName      = "";
                    if (primaryMinistry != null)
                    {
                        primaryMinistryName      = primaryMinistry.Value;
                        primaryMinistryImageGuid = primaryMinistry.GetAttributeValue("CalendarImage");
                    }

                    eventOccurrenceSummaries.Add(new EventOccurrenceSummary
                    {
                        EventItemOccurrence = eventItemOccurrence,
                        EventItem           = eventItemOccurrence.EventItem,
                        EventItemPhotoId    = eventItemOccurrence.EventItem.PhotoId ?? 0,
                        ICalendarContent    = eventItemOccurrence.Schedule.iCalendarContent,
                        Name                     = eventItemOccurrence.EventItem.Name,
                        DateTime                 = occurrenceDates.Date,
                        Date                     = occurrenceDates.Date.ToShortDateString(),
                        Time                     = occurrenceDates.Date.ToShortTimeString(),
                        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,
                        PrimaryMinistryImageGuid = primaryMinistryImageGuid,
                        PrimaryMinstryTitle      = primaryMinistryName,
                        URLSlugs                 = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "URLSlugs").Select(av => av.Value).FirstOrDefault(),
                        Priority                 = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == priorityAttributeKey).Select(av => av.Value).FirstOrDefault().AsIntegerOrNull() ?? int.MaxValue,
                        ImageHeaderText          = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "ImageHeaderText").Select(av => av.Value).FirstOrDefault(),
                        ImageHeaderTextSmall     = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "ImageHeaderTextSmall").Select(av => av.Value).FirstOrDefault(),
                        EventDatesHide           = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "EventDatesHide").Select(av => av.Value).FirstOrDefault(),
                        AttChildcareAvailable    = occurrenceDates.EventItemOccurrenceAttributeValues.Where(av => av.AttributeKey == "ChildcareAvailable").Select(av => av.Value).FirstOrDefault(),
                        AttScheduleText          = occurrenceDates.EventItemOccurrenceAttributeValues.Where(av => av.AttributeKey == "ScheduleText").Select(av => av.Value).FirstOrDefault(),
                        AttUseOnlyScheduleText   = occurrenceDates.EventItemOccurrenceAttributeValues.Where(av => av.AttributeKey == "UseOnlyScheduleText").Select(av => av.Value).FirstOrDefault(),
                        CustomDateText           = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "CustomDateText").Select(av => av.Value).FirstOrDefault(),
                        CustomLocationText       = occurrenceDates.EventCalendarItemAttributeValues.Where(av => av.AttributeKey == "CustomLocationText").Select(av => av.Value).FirstOrDefault(),
                    });
                }
            }

            var eventSummaries = eventOccurrenceSummaries
                                 .OrderBy(e => e.DateTime)
                                 .GroupBy(e => e.Name)
                                 .OrderBy(e => e.First().Priority)
                                 .Select(e => e.ToList())
                                 .Take(GetAttributeValue("Limit").AsInteger())
                                 .ToList();

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

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

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

            var text     = GetAttributeValue("LavaTemplate");
            var commands = GetAttributeValue("EnabledLavaCommands");

            lOutput.Text = text.ResolveMergeFields(mergeFields, commands);

            var minutes = GetAttributeValue("CacheDuration").AsInteger();

            if (minutes > 0)
            {
                string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;
                RockCache.AddOrUpdate(cacheKey,
                                      System.Globalization.CultureInfo.CurrentCulture.ToString(),
                                      lOutput.Text, RockDateTime.Now.AddMinutes(minutes),
                                      cacheTags);
            }
        }
Пример #17
0
        /// <summary>
        /// Adds the cached HTML for a specific blockId or, if specified, a specific entityValue (Entity Context)
        /// </summary>
        /// <param name="blockId">The block identifier.</param>
        /// <param name="entityValue">The entity value.</param>
        /// <param name="html">The HTML.</param>
        /// <param name="cacheDuration">Duration of the cache.</param>
        /// <param name="cacheTags">The cache tags.</param>
        public static void AddCachedContent(int blockId, string entityValue, string html, int cacheDuration, string cacheTags)
        {
            var expiration = RockDateTime.Now.AddSeconds(cacheDuration);

            RockCache.AddOrUpdate(HtmlContentCacheKey(blockId, entityValue), string.Empty, html, expiration, cacheTags);
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Rock.Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState == null)
            {
                errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null.");
                return(false);
            }
            var dataViewAttributeKey  = string.Empty;
            var dataViewAttributeGuid = GetAttributeValue(action, "DataViewGroupAttribute").AsGuid();

            if (dataViewAttributeGuid != Guid.Empty)
            {
                dataViewAttributeKey = AttributeCache.Get(dataViewAttributeGuid).Key;
            }

            var dataViewService = new DataViewService(new RockContext());

            var family = checkInState.CheckIn.CurrentFamily;

            if (family != null)
            {
                var remove = GetAttributeValue(action, "Remove").AsBoolean();

                foreach (var person in family.People)
                {
                    foreach (var groupType in person.GroupTypes.ToList())
                    {
                        foreach (var group in groupType.Groups.ToList())
                        {
                            if (group.ExcludedByFilter == true)
                            {
                                continue;
                            }

                            var approvedPeopleGuid = group.Group.GetAttributeValue(dataViewAttributeKey);
                            if (string.IsNullOrWhiteSpace(approvedPeopleGuid))
                            {
                                continue;
                            }

                            //Get approved people dataview from cache or from db
                            var approvedPeopleList = RockCache.Get(approvedPeopleGuid) as List <int>;

                            if (approvedPeopleList == null)
                            {
                                DataView approvedPeople = dataViewService.Get(approvedPeopleGuid.AsGuid());

                                if (approvedPeople == null)
                                {
                                    continue;
                                }

                                var errors            = new List <string>();
                                var dbContext         = approvedPeople.GetDbContext();
                                var approvedPeopleQry = (IQueryable <Person>)approvedPeople.GetQuery(null, dbContext, 30, out errors).AsNoTracking();
                                if (approvedPeopleQry != null)
                                {
                                    try
                                    {
                                        approvedPeopleQry  = approvedPeopleQry.Skip(0).Take(5000);
                                        approvedPeopleList = approvedPeopleQry.Select(e => e.Id).ToList();
                                        RockCache.AddOrUpdate(approvedPeopleGuid, null, approvedPeopleList, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
                                    }
                                    catch (Exception ex)
                                    {
                                        if (remove)
                                        {
                                            groupType.Groups.Remove(group);
                                        }
                                        else
                                        {
                                            group.ExcludedByFilter = true;
                                        }
                                        ExceptionLogService.LogException(ex);
                                    }
                                }
                            }

                            if (approvedPeopleList != null && !approvedPeopleList.Contains(person.Person.Id))
                            {
                                if (remove)
                                {
                                    groupType.Groups.Remove(group);
                                }
                                else
                                {
                                    group.ExcludedByFilter = true;
                                }
                            }
                        }
                    }
                }
            }
            return(true);
        }
Пример #19
0
    /// <summary>
    /// Gets a <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the contents of the syndicated feed.
    /// </summary>
    /// <param name="feedUrl">A <see cref="System.String"/> representing the URL of the feed.</param>
    /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page. </param>
    /// <param name="cacheDuration">A <see cref="System.Int32"/> representing the length of time that the content of the RSS feed will be saved to cache.</param>
    /// <param name="message">A <see cref="System.Collections.Generic.Dictionary{string,object}"/> that will contain any error or alert messages that are returned.</param>
    /// <param name="isError">A <see cref="System.Boolean"/> that is <c>true</c> if an error has occurred, otherwise <c>false</c>.</param>
    /// <returns></returns>
    public static Dictionary <string, object> GetFeed(string feedUrl, string detailPage, int cacheDuration, ref Dictionary <string, string> message, ref bool isError)
    {
        Dictionary <string, object> feedDictionary = new Dictionary <string, object>();

        if (message == null)
        {
            message = new Dictionary <string, string>();
        }

        if (String.IsNullOrEmpty(feedUrl))
        {
            message.Add("Feed URL not provided.", "The RSS Feed URL has not been provided. Please update the \"RSS Feed URL\" attribute in the block settings.");
            return(feedDictionary);
        }
        if (!System.Text.RegularExpressions.Regex.IsMatch(feedUrl, @"^(http://|https://|)([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"))
        {
            message.Add("Feed URL not valid.", "The Feed URL is not formatted properly. Please verify the \"RSS Feed URL\" attribute in block settings.");
            isError = false;
            return(feedDictionary);
        }

        string cacheKey = GetFeedCacheKey(feedUrl);

        feedDictionary = RockCache.Get(cacheKey) as Dictionary <string, object>;

        if (feedDictionary == null)
        {
            XDocument feed = null;

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(feedUrl);

            using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
            {
                if (resp.StatusCode == HttpStatusCode.OK)
                {
                    XmlReader feedReader = XmlReader.Create(resp.GetResponseStream());
                    feed = XDocument.Load(feedReader);

                    feedReader.Close();
                }
                else
                {
                    message.Add("Error loading feed.", string.Format("An error has occurred while loading the feed.  Status Code: {0} - {1}", (int)resp.StatusCode, resp.StatusDescription));
                    isError = true;
                }
            }

            if (feed != null)
            {
                string detailPageBaseUrl = string.Empty;
                int    detailPageID      = 0;

                if (!String.IsNullOrEmpty(detailPage))
                {
                    detailPageID = new Rock.Model.PageService(new Rock.Data.RockContext()).Get(new Guid(detailPage)).Id;

                    detailPageBaseUrl = new PageReference(detailPageID).BuildUrl();
                }

                if (detailPageID > 0)
                {
                    detailPageBaseUrl = new PageReference(detailPageID).BuildUrl();
                }

                Dictionary <string, XNamespace> namespaces = feed.Root.Attributes()
                                                             .Where(a => a.IsNamespaceDeclaration)
                                                             .GroupBy(a => a.Name.Namespace == XNamespace.None ? String.Empty : a.Name.LocalName,
                                                                      a => XNamespace.Get(a.Value))
                                                             .ToDictionary(g => g.Key, g => g.First());


                feedDictionary = BuildElementDictionary(feed.Elements().First(), namespaces);

                if (feedDictionary.Count == 1 && feedDictionary.First().Value.GetType() == typeof(Dictionary <string, object>))
                {
                    feedDictionary = (Dictionary <string, object>)feedDictionary.First().Value;
                }

                if (feedDictionary.ContainsKey("lastBuildDate"))
                {
                    feedDictionary["lastBuildDate"] = DateTimeOffset.Parse(feedDictionary["lastBuildDate"].ToString()).LocalDateTime;
                }

                if (feedDictionary.ContainsKey("updated"))
                {
                    feedDictionary["updated"] = DateTimeOffset.Parse(feedDictionary["updated"].ToString()).LocalDateTime;
                }

                if (feedDictionary.ContainsKey("item") || feedDictionary.ContainsKey("entry"))
                {
                    List <Dictionary <string, object> > articles = (List <Dictionary <string, object> >)feedDictionary.Where(x => x.Key == "item" || x.Key == "entry").FirstOrDefault().Value;

                    foreach (var article in articles)
                    {
                        string idEntry       = String.Empty;
                        string idEntryHashed = string.Empty;
                        if (article.ContainsKey("id"))
                        {
                            idEntry = article["id"].ToString();
                        }

                        if (article.ContainsKey("guid"))
                        {
                            if (article["guid"].GetType() == typeof(Dictionary <string, object>))
                            {
                                idEntry = ((Dictionary <string, object>)article["guid"])["value"].ToString();
                            }
                            else
                            {
                                idEntry = article["guid"].ToString();
                            }
                        }

                        if (!String.IsNullOrWhiteSpace(idEntry))
                        {
                            System.Security.Cryptography.HashAlgorithm hashAlgorithm = System.Security.Cryptography.SHA1.Create();
                            System.Text.StringBuilder sb = new System.Text.StringBuilder();
                            foreach (byte b in hashAlgorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(idEntry)))
                            {
                                sb.Append(b.ToString("X2"));
                            }

                            idEntryHashed = sb.ToString();

                            Dictionary <string, string> queryString = new Dictionary <string, string>();
                            queryString.Add("FeedItemId", idEntryHashed);

                            if (detailPageID > 0)
                            {
                                article.Add("detailPageUrl", new PageReference(detailPageID, 0, queryString).BuildUrl());
                            }

                            article.Add("articleHash", idEntryHashed);
                        }

                        if (article.ContainsKey("pubDate"))
                        {
                            article["pubDate"] = DateTimeOffset.Parse(article["pubDate"].ToString()).LocalDateTime;
                        }

                        if (article.ContainsKey("updated"))
                        {
                            article["updated"] = DateTimeOffset.Parse(article["updated"].ToString()).LocalDateTime;
                        }
                    }
                }

                if (!String.IsNullOrEmpty(detailPageBaseUrl))
                {
                    feedDictionary.Add("DetailPageBaseUrl", detailPageBaseUrl);
                }
            }

            if (feedDictionary != null)
            {
                var expiration = Rock.RockDateTime.Now.AddMinutes(cacheDuration);
                RockCache.AddOrUpdate(cacheKey, null, feedDictionary, expiration);
            }
        }

        return(feedDictionary);
    }
Пример #20
0
        private void ShowView()
        {
            var rockContext = new RockContext();

            var missingConfiguration = new List <string>();

            var contentChannelGuid = GetAttributeValue("ContentChannel").AsGuidOrNull();

            if (!contentChannelGuid.HasValue)
            {
                missingConfiguration.Add("The content channel has not yet been configured.");
            }

            var blockTitleTemplate = GetAttributeValue("BlockTitleTemplate");

            if (blockTitleTemplate.IsNullOrWhiteSpace())
            {
                missingConfiguration.Add("The block title template appears to be blank.");
            }

            var bodyTemplate = GetAttributeValue("BodyTemplate");

            if (bodyTemplate.IsNullOrWhiteSpace())
            {
                missingConfiguration.Add("The body template appears to be blank.");
            }

            if (missingConfiguration.Count > 0)
            {
                StringBuilder message = new StringBuilder();
                message.Append("Currently, there are some missing configuration items. These items are summarized below: <ul>");

                foreach (var configurationItem in missingConfiguration)
                {
                    message.Append(string.Format("<li>{0}</li>", configurationItem));
                }

                message.Append("</ul>");

                nbMessages.Text = message.ToString();
                nbMessages.NotificationBoxType = NotificationBoxType.Validation;
                return;
            }

            var    enabledLavaCommands    = GetAttributeValue("EnabledLavaCommands");
            var    blockTitleIconCssClass = GetAttributeValue("BlockTitleIconCssClass");
            var    metricValueCount       = GetAttributeValue("MetricValueCount").AsInteger();
            var    cacheDuration          = GetAttributeValue("CacheDuration").AsInteger();
            string cacheTags = GetAttributeValue("CacheTags") ?? string.Empty;

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

            var cacheKey = "internal-commmunication-view-" + this.BlockId.ToString();

            ContentChannelItem  contentChannelItem = null;
            List <MetricResult> metrics            = null;
            var showPrev = false;

            CachedBlockData cachedItem = null;

            if (cacheDuration > 0 && _currentPage == 0)
            {
                var serializedCachedItem = RockCache.Get(cacheKey, true);
                if (serializedCachedItem != null &&
                    serializedCachedItem is string &&
                    !string.IsNullOrWhiteSpace(( string )serializedCachedItem))
                {
                    cachedItem = (( string )serializedCachedItem).FromJsonOrNull <CachedBlockData>();
                }
            }

            if (cachedItem != null)
            {
                contentChannelItem = cachedItem.ContentChannelItem;
                metrics            = cachedItem.Metrics;
                showPrev           = cachedItem.ShowPrev;
            }
            else
            {
                var channel = ContentChannelCache.Get(contentChannelGuid.Value);

                // Get latest content channel items, get two so we know if a previous one exists for paging
                var contentChannelItemsQry = new ContentChannelItemService(rockContext)
                                             .Queryable()
                                             .AsNoTracking()
                                             .Where(i => i.ContentChannel.Guid == contentChannelGuid &&
                                                    i.Status == ContentChannelItemStatus.Approved &&
                                                    i.StartDateTime <= RockDateTime.Now);

                if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
                {
                    if (channel.ContentChannelType.IncludeTime)
                    {
                        contentChannelItemsQry = contentChannelItemsQry.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime >= RockDateTime.Now);
                    }
                    else
                    {
                        contentChannelItemsQry = contentChannelItemsQry.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime > RockDateTime.Today);
                    }
                }

                var contentChannelItems = contentChannelItemsQry.OrderByDescending(i => i.StartDateTime)
                                          .Take(2)
                                          .Skip(_currentPage)
                                          .ToList();

                if (contentChannelItems.IsNull() || contentChannelItems.Count == 0)
                {
                    nbMessages.Text = "It appears that there are no active communications to display for this content channel.";
                    nbMessages.NotificationBoxType = NotificationBoxType.Info;
                    return;
                }

                contentChannelItem = contentChannelItems.First();
                showPrev           = (contentChannelItems.Count > 1);

                // Get metrics
                var metricCategories = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs(GetAttributeValue("Metrics"));

                var metricGuids = metricCategories.Select(a => a.MetricGuid).ToList();
                metrics = new MetricService(rockContext).GetByGuids(metricGuids)
                          .Select(m => new MetricResult
                {
                    Id              = m.Id,
                    Title           = m.Title,
                    Description     = m.Description,
                    IconCssClass    = m.IconCssClass,
                    UnitsLabel      = m.YAxisLabel,
                    LastRunDateTime = m.MetricValues.OrderByDescending(v => v.MetricValueDateTime).Select(v => v.MetricValueDateTime).FirstOrDefault(),
                    LastValue       = m.MetricValues.OrderByDescending(v => v.MetricValueDateTime).Select(v => v.YValue).FirstOrDefault()
                }).ToList();

                // Get metric values for each metric if requested
                if (metricValueCount > 0)
                {
                    foreach (var metric in metrics)
                    {
                        metric.MetricValues = new MetricValueService(rockContext).Queryable()
                                              .Where(v => v.MetricId == metric.Id)
                                              .OrderByDescending(v => v.MetricValueDateTime)
                                              .Select(v => new MetricValue
                        {
                            DateTime = v.MetricValueDateTime,
                            Value    = v.YValue,
                            Note     = v.Note
                        })
                                              .Take(metricValueCount)
                                              .ToList();
                    }
                }

                // Set Cache
                if (cacheDuration > 0 && _currentPage == 0)
                {
                    var cachedData = new CachedBlockData();
                    cachedData.ContentChannelItem = contentChannelItem.Clone(false);
                    cachedData.ShowPrev           = showPrev;
                    cachedData.Metrics            = metrics;

                    var expiration = RockDateTime.Now.AddSeconds(cacheDuration);
                    RockCache.AddOrUpdate(cacheKey, string.Empty, cachedData.ToJson(), expiration, cacheTags);
                }
            }

            mergeFields.Add("Item", contentChannelItem);
            mergeFields.Add("Metrics", metrics);

            lBlockTitleIcon.Text = string.Format("<i class='{0}'></i>", blockTitleIconCssClass);
            lBlockTitle.Text     = blockTitleTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands);

            lBlockBody.Text = bodyTemplate.ResolveMergeFields(mergeFields, enabledLavaCommands);

            // Determine if we can page backwards
            btnPrevious.Visible = showPrev;

            // Determine if we can page forwards
            btnNext.Visible = (_currentPage > 0);

            // Set the current page hidden field
            hfCurrentPage.Value = _currentPage.ToString();
        }
Пример #21
0
        public IHttpActionResult GetSpeakerSeries(string slug = "", string speaker = "", int offset = 0)
        {
            var cacheKey = string.Format("api/sermonfeed/{0}/{1}/{2}", slug, speaker, offset);
            var output   = RockCache.Get(cacheKey) as List <SermonSeries>;

            if (output != null)
            {
                return(Json(output));
            }


            string      imageLocation = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash() + "GetImage.ashx?Guid=";
            string      audioLocation = GlobalAttributesCache.Get().GetValue("PublicApplicationRoot").EnsureTrailingForwardslash() + "GetFile.ashx?Guid=";
            RockContext rockContext   = new RockContext();

            var speakerQry = new AttributeValueService(rockContext).Queryable().Where(av => av.AttributeId == SPEAKER_ATTRIBUTE && av.Value == speaker);
            ContentChannelItemService contentChannelItemService = new ContentChannelItemService(rockContext);
            var sermonSeriesQry = contentChannelItemService.Queryable()
                                  .Where(i => i.ContentChannelId == CONTENT_CHANNEL);

            if (!string.IsNullOrWhiteSpace(slug))
            {
                sermonSeriesQry = sermonSeriesQry.Where(i => i.ContentChannelItemSlugs.Where(s => s.ContentChannelItemId == i.Id && s.Slug == slug).Any());
            }
            var sermonSeriesList = sermonSeriesQry.SelectMany(i => i.ChildItems)
                                   .Select(i => i.ChildContentChannelItem)
                                   .Join(
                speakerQry,
                i => i.Id,
                a => a.EntityId,
                (i, a) => i
                )
                                   .Select(i => i.ParentItems.FirstOrDefault().ContentChannelItem)
                                   .DistinctBy(i => i.Id)
                                   .OrderByDescending(i => i.StartDateTime)
                                   .Skip(offset)
                                   .Take(12)
                                   .ToList();

            output = new List <SermonSeries>();

            foreach (var seriesItem in sermonSeriesList)
            {
                seriesItem.LoadAttributes();
                var sermonSeries = new SermonSeries
                {
                    id           = seriesItem.Id,
                    title        = seriesItem.Title,
                    description  = seriesItem.Content,
                    slug         = seriesItem.PrimarySlug,
                    image        = imageLocation + seriesItem.GetAttributeValue("Image"),
                    image_url    = imageLocation + seriesItem.GetAttributeValue("Image"),
                    last_updated = ConvertTime(seriesItem.StartDateTime),
                    sermons      = new List <Sermon>()
                };
                if (string.IsNullOrWhiteSpace(seriesItem.GetAttributeValue("Image")))
                {
                    var childItem = seriesItem.ChildItems.FirstOrDefault().ChildContentChannelItem;
                    childItem.LoadAttributes();
                    sermonSeries.image_url = imageLocation + childItem.GetAttributeValue("Image");
                    sermonSeries.image     = imageLocation + childItem.GetAttributeValue("Image");
                }

                output.Add(sermonSeries);

                //add sermons to series
                foreach (var sermonItem in seriesItem.ChildItems.Select(s => s.ChildContentChannelItem))
                {
                    sermonItem.LoadAttributes();
                    if (sermonItem.GetAttributeValue("Speaker").ToLower() != speaker.ToLower())
                    {
                        continue;
                    }

                    sermonSeries.sermons.Add(
                        new Sermon
                    {
                        id          = sermonItem.Id,
                        title       = sermonItem.Title,
                        description = sermonItem.Content,
                        slug        = sermonItem.PrimarySlug,
                        audio_link  = audioLocation + sermonItem.GetAttributeValue("Audio"),
                        date        = ConvertTime(sermonItem.StartDateTime),
                        duration    = sermonItem.GetAttributeValue("Duration").AsInteger(),
                        image       = imageLocation + sermonItem.GetAttributeValue("Image"),
                        image_url   = imageLocation + sermonItem.GetAttributeValue("Image"),
                        speaker     = sermonItem.GetAttributeValue("Speaker"),
                        vimeo_id    = sermonItem.GetAttributeValue("VimeoId").AsInteger()
                    });
                }
            }
            RockCache.AddOrUpdate(cacheKey, null, output, RockDateTime.Now.AddHours(1));

            return(Json(output));
        }
Пример #22
0
        /// <summary>
        /// Writes the <see cref="T:System.Web.UI.WebControls.CompositeControl" /> content to the specified <see cref="T:System.Web.UI.HtmlTextWriter" /> object, for display on the client.
        /// </summary>
        /// <param name="writer">An <see cref="T:System.Web.UI.HtmlTextWriter" /> that represents the output stream to render HTML content on the client.</param>
        protected override void Render(HtmlTextWriter writer)
        {
            var blockCache = _rockBlock.BlockCache;

            string preHtml   = string.Empty;
            string postHtml  = string.Empty;
            string appRoot   = _rockBlock.ResolveRockUrl("~/");
            string themeRoot = _rockBlock.ResolveRockUrl("~~/");

            if (_rockBlock.Visible)
            {
                if (!string.IsNullOrWhiteSpace(blockCache.PreHtml))
                {
                    preHtml = blockCache.PreHtml.Replace("~~/", themeRoot).Replace("~/", appRoot);
                }

                if (!string.IsNullOrWhiteSpace(blockCache.PostHtml))
                {
                    postHtml = blockCache.PostHtml.Replace("~~/", themeRoot).Replace("~/", appRoot);
                }

                if (preHtml.HasMergeFields() || postHtml.HasMergeFields())
                {
                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(_rockBlock.RockPage);
                    preHtml  = preHtml.ResolveMergeFields(mergeFields, "All");
                    postHtml = postHtml.ResolveMergeFields(mergeFields, "All");
                }
            }

            StringBuilder  sbOutput = null;
            StringWriter   swOutput = null;
            HtmlTextWriter twOutput = null;

            if (_rockBlock.BlockCache.OutputCacheDuration > 0)
            {
                sbOutput = new StringBuilder();
                swOutput = new StringWriter(sbOutput);
                twOutput = new HtmlTextWriter(swOutput);
            }

            // Create block wrapper
            string blockTypeCss = blockCache.BlockType != null ? blockCache.BlockType.Name : "";
            var    parts        = blockTypeCss.Split(new char[] { '>' });

            if (parts.Length > 1)
            {
                blockTypeCss = parts[parts.Length - 1].Trim();
            }
            blockTypeCss = blockTypeCss.Replace(' ', '-').ToLower();
            string blockInstanceCss = "block-instance js-block-instance " +
                                      blockTypeCss +
                                      (string.IsNullOrWhiteSpace(blockCache.CssClass) ? "" : " " + blockCache.CssClass.Trim()) +
                                      (_rockBlock.UserCanEdit || _rockBlock.UserCanAdministrate ? " can-configure " : "");

            writer.Write(preHtml);
            writer.AddAttribute(HtmlTextWriterAttribute.Id, string.Format("bid_{0}", blockCache.Id));
            writer.AddAttribute("data-zone-location", blockCache.BlockLocation.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Class, blockInstanceCss);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-content");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            if (blockCache.OutputCacheDuration > 0)
            {
                twOutput.Write(preHtml);
                twOutput.AddAttribute(HtmlTextWriterAttribute.Id, string.Format("bid_{0}", blockCache.Id));
                twOutput.AddAttribute("data-zone-location", blockCache.BlockLocation.ToString());
                twOutput.AddAttribute(HtmlTextWriterAttribute.Class, blockInstanceCss);
                twOutput.RenderBeginTag(HtmlTextWriterTag.Div);

                twOutput.AddAttribute(HtmlTextWriterAttribute.Class, "block-content");
                twOutput.RenderBeginTag(HtmlTextWriterTag.Div);
            }

            if (_rockBlock.PageCache.IncludeAdminFooter && _adminControls.Any())
            {
                // Add the config buttons
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-configuration config-bar");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, "#");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "fa fa-arrow-circle-right");
                writer.RenderBeginTag(HtmlTextWriterTag.I);
                writer.RenderEndTag();
                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "block-configuration-bar");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(string.IsNullOrWhiteSpace(blockCache.Name) ? blockCache.BlockType.Name : blockCache.Name);
                writer.RenderEndTag();

                foreach (Control configControl in _adminControls)
                {
                    configControl.RenderControl(writer);
                }

                writer.RenderEndTag();  // block-configuration-bar
                writer.RenderEndTag();  // config-bar
            }

            _rockBlock.RenderControl(writer);

            writer.RenderEndTag();  // block-content
            writer.RenderEndTag();  // block-instance
            writer.Write(postHtml);

            if (blockCache.OutputCacheDuration > 0)
            {
                base.Render(twOutput);

                twOutput.RenderEndTag();  // block-content
                twOutput.RenderEndTag();  // block-instance
                twOutput.Write(postHtml);

                var    expiration     = RockDateTime.Now.AddSeconds(blockCache.OutputCacheDuration);
                string _blockCacheKey = string.Format("Rock:BlockOutput:{0}", blockCache.Id);
                RockCache.AddOrUpdate(_blockCacheKey, sbOutput.ToString(), expiration);
            }
        }
Пример #23
0
        public void ProcessRequest(HttpContext context)
        {
            request  = context.Request;
            response = context.Response;

            string cacheKey      = "Rock:GetChannelFeed:" + request.RawUrl;
            var    contentCache  = RockCache.Get(cacheKey);
            var    mimeTypeCache = RockCache.Get(cacheKey + ":MimeType");

            if (mimeTypeCache != null && contentCache != null)
            {
                response.ContentType = ( string )mimeTypeCache;
                response.Write(( string )contentCache);
                response.StatusCode = 200;
                return;
            }

            RockContext rockContext = new RockContext();

            if (request.HttpMethod != "GET" && request.HttpMethod != "HEAD")
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 405;
                response.Headers.Add("Allow", "GET");
                response.Write("Invalid request method.");
                return;
            }

            if (request.QueryString["ChannelId"] == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("A ChannelId is required.");
                return;
            }

            int?channelId = request.QueryString["ChannelId"].AsIntegerOrNull();

            if (channelId == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid channel id.");
                return;
            }

            ContentChannel channel = new ContentChannelService(rockContext).Queryable("ContentChannelType").FirstOrDefault(c => c.Id == channelId.Value);

            if (channel == null)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 404;
                response.Write("Channel does not exist.");
                return;
            }

            if (!channel.EnableRss)
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 403;
                response.Write("RSS is not enabled for this channel.");
                return;
            }

            DefinedValueCache dvRssTemplate = null;

            if (request.QueryString["TemplateId"] != null)
            {
                int?templateDefinedValueId = request.QueryString["TemplateId"].AsIntegerOrNull();

                if (templateDefinedValueId == null)
                {
                    response.TrySkipIisCustomErrors = true;
                    response.StatusCode             = 400;
                    response.Write("Invalid template id.");
                    return;
                }

                dvRssTemplate = DefinedValueCache.Get(templateDefinedValueId.Value);
            }

            if (dvRssTemplate == null)
            {
                dvRssTemplate = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.DEFAULT_RSS_CHANNEL);
            }

            if (dvRssTemplate.DefinedType.Guid != new Guid(Rock.SystemGuid.DefinedType.LAVA_TEMPLATES))
            {
                response.TrySkipIisCustomErrors = true;
                response.StatusCode             = 400;
                response.Write("Invalid template id.");
                return;
            }

            string rssTemplate = dvRssTemplate.GetAttributeValue("Template");

            if (string.IsNullOrWhiteSpace(dvRssTemplate.GetAttributeValue("MimeType")))
            {
                response.ContentType = "application/rss+xml";
            }
            else
            {
                response.ContentType = dvRssTemplate.GetAttributeValue("MimeType");
            }

            if (request.HttpMethod == "HEAD")
            {
                response.StatusCode = 200;
                return;
            }

            // load merge fields
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            mergeFields.Add("Channel", channel);

            Dictionary <string, object> requestObjects = new Dictionary <string, object>();

            requestObjects.Add("Scheme", request.Url.Scheme);
            requestObjects.Add("Host", WebRequestHelper.GetHostNameFromRequest(context));
            requestObjects.Add("Authority", request.Url.Authority);
            requestObjects.Add("LocalPath", request.Url.LocalPath);
            requestObjects.Add("AbsoluteUri", request.Url.AbsoluteUri);
            requestObjects.Add("AbsolutePath", request.Url.AbsolutePath);
            requestObjects.Add("Port", request.Url.Port);
            requestObjects.Add("Query", request.Url.Query);
            requestObjects.Add("OriginalString", request.Url.OriginalString);

            mergeFields.Add("Request", requestObjects);

            // check for new rss item limit
            if (request.QueryString["Count"] != null)
            {
                int.TryParse(request.QueryString["Count"], out rssItemLimit);
            }

            // get channel items
            ContentChannelItemService contentService = new ContentChannelItemService(rockContext);

            var content = contentService.Queryable("ContentChannelType")
                          .Where(c =>
                                 c.ContentChannelId == channel.Id &&
                                 (c.Status == ContentChannelItemStatus.Approved || c.ContentChannel.ContentChannelType.DisableStatus || c.ContentChannel.RequiresApproval == false) &&
                                 c.StartDateTime <= RockDateTime.Now);

            if (channel.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange)
            {
                if (channel.ContentChannelType.IncludeTime)
                {
                    content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime >= RockDateTime.Now);
                }
                else
                {
                    content = content.Where(c => !c.ExpireDateTime.HasValue || c.ExpireDateTime > RockDateTime.Today);
                }
            }

            if (channel.ItemsManuallyOrdered)
            {
                content = content.OrderBy(c => c.Order);
            }
            else
            {
                content = content.OrderByDescending(c => c.StartDateTime);
            }

            content = content.Take(rssItemLimit);

            foreach (var item in content)
            {
                item.Content = item.Content.ResolveMergeFields(mergeFields);

                // resolve any relative links
                var    globalAttributes = GlobalAttributesCache.Get();
                string publicAppRoot    = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
                item.Content = item.Content.Replace(@" src=""/", @" src=""" + publicAppRoot);
                item.Content = item.Content.Replace(@" href=""/", @" href=""" + publicAppRoot);

                // get item attributes and add them as elements to the feed
                item.LoadAttributes(rockContext);
                foreach (var attributeValue in item.AttributeValues)
                {
                    attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields(mergeFields);
                }
            }

            mergeFields.Add("Items", content);

            mergeFields.Add("RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber());

            var outputContent = rssTemplate.ResolveMergeFields(mergeFields);

            response.Write(outputContent);

            var cacheDuration = dvRssTemplate.GetAttributeValue("CacheDuration").AsInteger();

            if (cacheDuration > 0)
            {
                var expiration = RockDateTime.Now.AddMinutes(cacheDuration);
                if (expiration > RockDateTime.Now)
                {
                    RockCache.AddOrUpdate(cacheKey + ":MimeType", null, response.ContentType, expiration);
                    RockCache.AddOrUpdate(cacheKey, null, outputContent, expiration);
                }
                ;
            }
        }
Пример #24
0
 private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
 {
     context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
     RockCache.AddOrUpdate(context.Token, context.SerializeTicket());
 }
Пример #25
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                var output = RockCache.Get("TimedContentChannel_" + this.BlockId.ToString());
                if (output != null)
                {
                    ltOutput.Text = output as string;
                    return;
                }

                RockContext           rockContext           = new RockContext();
                ContentChannelService contentChannelService = new ContentChannelService(rockContext);
                ScheduleService       scheduleService       = new ScheduleService(rockContext);

                var cacheLength = GetAttributeValue("MaximumCache").AsDouble();

                var contentChannelGuid = GetAttributeValue("ContentChannel").AsGuid();
                var contentChannel     = contentChannelService.Get(contentChannelGuid);
                if (contentChannel == null)
                {
                    return;
                }
                var contentChannelItems = contentChannel.Items.OrderBy(i => i.Order).ToList();
                List <ContentChannelItem> mergeItems = new List <ContentChannelItem>();
                var scheduleKey = GetAttributeValue("TimerAttributeKey");
                foreach (var item in contentChannelItems)
                {
                    item.LoadAttributes();
                    var scheduleValue = item.GetAttributeValue(scheduleKey);
                    if (scheduleValue.IsNotNullOrWhiteSpace())
                    {
                        var schedule = scheduleService.Get(scheduleValue.AsGuid());
                        if (schedule == null)
                        {
                            continue;
                        }

                        if (schedule.WasScheduleActive(Rock.RockDateTime.Now))
                        {
                            mergeItems.Add(item);
                            var end        = schedule.GetCalendarEvent().DTEnd.TimeOfDay;
                            var endMinutes = (end - Rock.RockDateTime.Now.TimeOfDay).TotalSeconds;
                            cacheLength = Math.Min(cacheLength, endMinutes);
                        }
                        else
                        {
                            var nextTime = schedule.GetNextStartDateTime(Rock.RockDateTime.Now);
                            if (nextTime.HasValue)
                            {
                                var time    = nextTime.Value - Rock.RockDateTime.Now;
                                var minutes = time.TotalSeconds;
                                cacheLength = Math.Min(cacheLength, minutes);
                            }
                        }
                    }
                    else
                    {
                        mergeItems.Add(item);
                    }
                }
                var lava        = GetAttributeValue("Lava");
                var mergefields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson);
                mergefields.Add("ContentChannelItems", mergeItems);
                lava          = lava.ResolveMergeFields(mergefields, CurrentPerson, GetAttributeValue("EnabledLavaCommands"));
                ltOutput.Text = lava;
                if (cacheLength > 5)   //the time could be low enough to throw an error
                {
                    RockCache.AddOrUpdate("TimedContentChannel_" + this.BlockId.ToString(), "", lava, Rock.RockDateTime.Now.AddSeconds(cacheLength));
                }
            }
        }
Пример #26
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            string cacheKey = "Rock.FindRelationships.Roles";

            List <int> roles = RockCache.Get(cacheKey) as List <int>;

            if (roles == null)
            {
                roles = new List <int>();

                foreach (var role in new GroupTypeRoleService(rockContext)
                         .Queryable().AsNoTracking()
                         .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS))))
                {
                    role.LoadAttributes(rockContext);
                    if (role.Attributes.ContainsKey("CanCheckin"))
                    {
                        bool canCheckIn = false;
                        if (bool.TryParse(role.GetAttributeValue("CanCheckin"), out canCheckIn) && canCheckIn)
                        {
                            roles.Add(role.Id);
                        }
                    }
                }

                RockCache.AddOrUpdate(cacheKey, null, roles, RockDateTime.Now.AddSeconds(300));
            }

            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                if (!roles.Any())
                {
                    return(true);
                }

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    bool preventInactive = (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeople);
                    var  dvInactive      = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid());

                    var groupMemberService = new GroupMemberService(rockContext);

                    var familyMemberIds = family.People.Select(p => p.Person.Id).ToList();

                    var knownRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                    if (knownRelationshipGroupType != null)
                    {
                        var ownerRole = knownRelationshipGroupType.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid());
                        if (ownerRole != null)
                        {
                            // Get the Known Relationship group id's for each person in the family
                            var relationshipGroupIds = groupMemberService
                                                       .Queryable().AsNoTracking()
                                                       .Where(g =>
                                                              g.GroupRoleId == ownerRole.Id &&
                                                              familyMemberIds.Contains(g.PersonId))
                                                       .Select(g => g.GroupId);

                            // Get anyone in any of those groups that has a role with the canCheckIn attribute set
                            var personIds = groupMemberService
                                            .Queryable().AsNoTracking()
                                            .Where(g =>
                                                   relationshipGroupIds.Contains(g.GroupId) &&
                                                   roles.Contains(g.GroupRoleId))
                                            .Select(g => g.PersonId)
                                            .ToList();

                            foreach (var person in new PersonService(rockContext)
                                     .Queryable().AsNoTracking()
                                     .Where(p => personIds.Contains(p.Id))
                                     .ToList())
                            {
                                if (!family.People.Any(p => p.Person.Id == person.Id))
                                {
                                    if (!preventInactive || dvInactive == null || person.RecordStatusValueId != dvInactive.Id)
                                    {
                                        var relatedPerson = new CheckInPerson();
                                        relatedPerson.Person       = person.Clone(false);
                                        relatedPerson.FamilyMember = false;
                                        family.People.Add(relatedPerson);
                                    }
                                }
                            }
                        }
                    }

                    return(true);
                }
                else
                {
                    errorMessages.Add("There is not a family that is selected");
                }

                return(false);
            }

            return(false);
        }
Пример #27
0
        /// <summary>
        /// Renders the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="result">The result.</param>
        public override void Render(Context context, TextWriter result)
        {
            // First ensure that cached commands are allowed in the context
            if (!this.IsAuthorized(context))
            {
                result.Write(string.Format(RockLavaBlockBase.NotAuthorizedMessage, this.Name));
                base.Render(context, result);
                return;
            }

            var parms = ParseMarkup(_markup, context);

            var twoPassEnabled = parms["twopass"].AsBoolean();

            var cacheKey = "lavacache-" + parms["key"];

            if (cacheKey == string.Empty)
            {
                result.Write("* No cache key provided. *");
                base.Render(context, result);
                return;
            }

            // Get content from cache
            var cachedResult = RockCache.Get(cacheKey, true) as CacheLavaTag;

            // Check that the cached value is current
            if (cachedResult != null)
            {
                var currentHash = CalculateContentHash(_blockMarkup.ToString());
                if (currentHash != cachedResult.Hash)
                {
                    cachedResult = null;
                }
            }

            // Use the cached value
            if (cachedResult != null)
            {
                if (twoPassEnabled)
                {
                    result.Write(MergeLava(cachedResult.Content, context));
                }
                else
                {
                    result.Write(cachedResult.Content);
                }

                base.Render(context, result);
                return;
            }

            // Cached value not available so render the template and cache it
            var lavaResults = MergeLava(_blockMarkup.ToString(), context);

            var cacheDuration = parms["duration"].AsInteger();

            if (cacheDuration > 0)
            {
                // Don't cache if it's too large
                var maxCacheSize = parms["maxcachesize"].AsInteger();

                if (lavaResults.Length < maxCacheSize)
                {
                    var expiration = RockDateTime.Now.AddSeconds(cacheDuration);
                    var cachedHash = CalculateContentHash(_blockMarkup.ToString());
                    RockCache.AddOrUpdate(cacheKey, string.Empty, new CacheLavaTag {
                        Hash = cachedHash, Content = lavaResults
                    }, expiration, parms["tags"]);
                }
            }

            // If twopass is enabled run the lava again
            if (twoPassEnabled)
            {
                lavaResults = MergeLava(lavaResults, context);
            }

            result.Write(lavaResults);



            base.Render(context, result);
        }
Пример #28
0
        private static List <BreakoutGroupItem> GetBreakoutGroupItems(Person person)
        {
            List <BreakoutGroupItem> allBreakoutGroupItems = RockCache.Get(cacheKey) as List <BreakoutGroupItem>;

            if (allBreakoutGroupItems == null || !allBreakoutGroupItems.Any())
            {
                allBreakoutGroupItems = new List <BreakoutGroupItem>();
                RockContext rockContext = new RockContext();

                var attributeService      = new AttributeService(rockContext);
                var attributeValueService = new AttributeValueService(rockContext);

                var groupEntityTypeId        = EntityTypeCache.GetId(typeof(Rock.Model.Group));
                var breakoutGroupGroupTypeId = GroupTypeCache.GetId(Constants.GROUP_TYPE_BREAKOUT_GROUPS.AsGuid());

                if (groupEntityTypeId == null || breakoutGroupGroupTypeId == null)
                {
                    ExceptionLogService.LogException(new Exception("Could not load breakout groups due to missing breakoutgroup type"));
                    return(new List <BreakoutGroupItem>());
                }

                var letterAttribute = attributeService.GetByEntityTypeQualifier(groupEntityTypeId, "GroupTypeId", breakoutGroupGroupTypeId.Value.ToString(), false)
                                      .Where(a => a.Key == Constants.GROUP_ATTRIBUTE_KEY_LETTER)
                                      .FirstOrDefault();

                if (letterAttribute == null)
                {
                    ExceptionLogService.LogException(new Exception("Could not load breakout group letter attribute."));
                    return(new List <BreakoutGroupItem>());
                }

                var attributeQueryable = attributeValueService.Queryable().AsNoTracking()
                                         .Where(av => letterAttribute.Id == av.AttributeId);

                //Get all the data in one go
                var breakoutData = new GroupService(rockContext)
                                   .Queryable()
                                   .AsNoTracking()
                                   .Where(g => g.GroupTypeId == breakoutGroupGroupTypeId && g.IsActive && !g.IsArchived)
                                   .Join(attributeQueryable,
                                         g => g.Id,
                                         av => av.EntityId,
                                         (g, av) => new
                {
                    ScheduleId = g.ScheduleId ?? 0,
                    PersonIds  = g.Members.Where(gm => gm.IsArchived == false && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.PersonId),
                    Letter     = av.Value
                })
                                   .ToList();

                foreach (var item in breakoutData)
                {
                    foreach (var personId in item.PersonIds)
                    {
                        allBreakoutGroupItems.Add(new BreakoutGroupItem
                        {
                            Letter     = item.Letter,
                            PersonId   = personId,
                            ScheduleId = item.ScheduleId
                        });
                    }
                }

                RockCache.AddOrUpdate(cacheKey, null, allBreakoutGroupItems, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            }

            return(allBreakoutGroupItems.Where(i => i.PersonId == person.Id).ToList());
        }