/// <summary>
        /// Use Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">A comma-delimited list of the lava commands that are enabled for this template.</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        public static string RenderLava(this string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands)
        {
            try
            {
                // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
                if (enabledLavaCommands == null)
                {
                    enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
                }

                var context = LavaService.NewRenderContext();

                context.SetEnabledCommands(enabledLavaCommands, ",");

                context.SetMergeField("CurrentPerson", currentPersonOverride);
                context.SetMergeFields(mergeObjects);

                var result = LavaService.RenderTemplate(content, LavaRenderParameters.WithContext(context));

                if (result.HasErrors)
                {
                    throw result.GetLavaException();
                }

                return(result.Text);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                return("Error resolving Lava merge fields: " + ex.Message);
            }
        }
Exemple #2
0
        /// <summary>
        /// Use Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <param name="enabledLavaCommands">A comma-delimited list of the lava commands that are enabled for this template.</param>
        /// <param name="encodeStringOutput">if set to <c>true</c> [encode string output].</param>
        /// <returns>If lava present returns merged string, if no lava returns original string, if null returns empty string</returns>
        private static LavaRenderResult ResolveMergeFieldsWithCurrentLavaEngine(string content, IDictionary <string, object> mergeObjects, Person currentPersonOverride, string enabledLavaCommands, bool encodeStringOutput)
        {
            // If there have not been any EnabledLavaCommands explicitly set, then use the global defaults.
            if (enabledLavaCommands == null)
            {
                enabledLavaCommands = GlobalAttributesCache.Value("DefaultEnabledLavaCommands");
            }

            var context = LavaService.NewRenderContext();

            context.SetEnabledCommands(enabledLavaCommands, ",");

            if (currentPersonOverride != null)
            {
                context.SetMergeField("CurrentPerson", currentPersonOverride);
            }

            context.SetMergeFields(mergeObjects);

            var parameters = LavaRenderParameters.WithContext(context);

            parameters.ShouldEncodeStringsAsXml = encodeStringOutput;

            var result = LavaService.RenderTemplate(content, parameters);

            if (result.HasErrors &&
                LavaService.ExceptionHandlingStrategy == ExceptionHandlingStrategySpecifier.RenderToOutput)
            {
                // If the result is an error, encode the error message to prevent any part of it from appearing as rendered content, and then add markup for line breaks.
                result.Text = result.Text.EncodeHtml().ConvertCrLfToHtmlBr();
            }

            return(result);
        }
        private void Render()
        {
            string content = null;

            try
            {
                PageCache currentPage = PageCache.Get(RockPage.PageId);
                PageCache rootPage    = null;

                var pageRouteValuePair = GetAttributeValue(AttributeKey.RootPage).SplitDelimitedValues(false).AsGuidOrNullList();
                if (pageRouteValuePair.Any() && pageRouteValuePair[0].HasValue && !pageRouteValuePair[0].Value.IsEmpty())
                {
                    rootPage = PageCache.Get(pageRouteValuePair[0].Value);
                }

                // If a root page was not found, use current page
                if (rootPage == null)
                {
                    rootPage = currentPage;
                }

                int levelsDeep = Convert.ToInt32(GetAttributeValue(AttributeKey.NumberofLevels));

                Dictionary <string, string> pageParameters = null;
                if (GetAttributeValue(AttributeKey.IncludeCurrentParameters).AsBoolean())
                {
                    pageParameters = CurrentPageReference.Parameters;
                }

                NameValueCollection queryString = null;
                if (GetAttributeValue(AttributeKey.IncludeCurrentQueryString).AsBoolean())
                {
                    queryString = CurrentPageReference.QueryString;
                }

                // Get list of pages in current page's hierarchy
                var pageHeirarchy = new List <int>();
                if (currentPage != null)
                {
                    pageHeirarchy = currentPage.GetPageHierarchy().Select(p => p.Id).ToList();
                }

                // Get default merge fields.
                var pageProperties = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                pageProperties.Add("Site", GetSiteProperties(RockPage.Site));
                pageProperties.Add("IncludePageList", GetIncludePageList());
                pageProperties.Add("CurrentPage", this.PageCache);

                using (var rockContext = new RockContext())
                {
                    pageProperties.Add("Page", rootPage.GetMenuProperties(levelsDeep, CurrentPerson, rockContext, pageHeirarchy, pageParameters, queryString));
                }

                if (LavaService.RockLiquidIsEnabled)
                {
#pragma warning disable CS0618 // Type or member is obsolete
                    var lavaTemplate = GetTemplate();
#pragma warning restore CS0618 // Type or member is obsolete

                    // Apply Enabled Lava Commands
                    var enabledCommands = GetAttributeValue(AttributeKey.EnabledLavaCommands);
                    lavaTemplate.Registers.AddOrReplace("EnabledCommands", enabledCommands);

                    content = lavaTemplate.Render(Hash.FromDictionary(pageProperties));

                    // Check for Lava rendering errors.
                    if (lavaTemplate.Errors.Any())
                    {
                        throw lavaTemplate.Errors.First();
                    }
                }
                else
                {
                    var templateText = GetAttributeValue(AttributeKey.Template);

                    // Apply Enabled Lava Commands
                    var lavaContext = LavaService.NewRenderContext(pageProperties);

                    var enabledCommands = GetAttributeValue(AttributeKey.EnabledLavaCommands);

                    lavaContext.SetEnabledCommands(enabledCommands.SplitDelimitedValues());

                    var result = LavaService.RenderTemplate(templateText,
                                                            new LavaRenderParameters {
                        Context = lavaContext, CacheKey = CacheKey()
                    });

                    content = result.Text;

                    if (result.HasErrors)
                    {
                        throw result.GetLavaException("PageMenu Block Lava Error");
                    }
                }

                phContent.Controls.Clear();
                phContent.Controls.Add(new LiteralControl(content));
            }
            catch (Exception ex)
            {
                LogException(ex);

                // Create a block showing the error and the attempted content render.
                // Show the error first to ensure that it is visible, because the rendered content may disrupt subsequent output if it is malformed.
                StringBuilder errorMessage = new StringBuilder();
                errorMessage.Append("<div class='alert alert-warning'>");
                errorMessage.Append("<h4>Warning</h4>");
                errorMessage.Append("An error has occurred while generating the page menu. Error details:<br/>");
                errorMessage.Append(ex.Message);

                if (!string.IsNullOrWhiteSpace(content))
                {
                    errorMessage.Append("<h4>Rendered Content</h4>");
                    errorMessage.Append(content);
                    errorMessage.Append("</div>");
                }

                phContent.Controls.Add(new LiteralControl(errorMessage.ToString()));
            }
        }
Exemple #4
0
        private void Map()
        {
            string mapStylingFormat = @"
                        <style>
                            #map_wrapper {{
                                height: {0}px;
                            }}

                            #map_canvas {{
                                width: 100%;
                                height: 100%;
                                border-radius: var(--border-radius-base);
                            }}
                        </style>";

            lMapStyling.Text = string.Format(mapStylingFormat, GetAttributeValue("MapHeight"));

            string settingGroupTypeId     = GetAttributeValue("GroupType");
            string queryStringGroupTypeId = PageParameter("GroupTypeId");

            if ((string.IsNullOrWhiteSpace(settingGroupTypeId) && string.IsNullOrWhiteSpace(queryStringGroupTypeId)))
            {
                pnlMap.Visible = false;
                lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display as a block setting or pass a GroupTypeId as a query parameter.</div>";
            }
            else
            {
                var rockContext = new RockContext();

                pnlMap.Visible = true;

                int groupsMapped    = 0;
                int groupsWithNoGeo = 0;

                StringBuilder sbGroupJson       = new StringBuilder();
                StringBuilder sbGroupsWithNoGeo = new StringBuilder();

                Guid?groupType   = null;
                int  groupTypeId = -1;

                if (!string.IsNullOrWhiteSpace(settingGroupTypeId))
                {
                    groupType = new Guid(settingGroupTypeId);
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(queryStringGroupTypeId) && Int32.TryParse(queryStringGroupTypeId, out groupTypeId))
                    {
                        groupType = new GroupTypeService(rockContext).Get(groupTypeId).Guid;
                    }
                }

                if (groupType != null)
                {
                    Template      template     = null;
                    ILavaTemplate lavaTemplate = null;

                    if (LavaService.RockLiquidIsEnabled)
                    {
                        if (GetAttributeValue("ShowMapInfoWindow").AsBoolean())
                        {
                            template = Template.Parse(GetAttributeValue("InfoWindowContents").Trim());

                            LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue("InfoWindowContents").Trim());
                        }
                        else
                        {
                            template = Template.Parse(string.Empty);
                        }
                    }
                    else
                    {
                        string templateContent;

                        if (GetAttributeValue("ShowMapInfoWindow").AsBoolean())
                        {
                            templateContent = GetAttributeValue("InfoWindowContents").Trim();
                        }
                        else
                        {
                            templateContent = string.Empty;
                        }

                        var parseResult = LavaService.ParseTemplate(templateContent);

                        lavaTemplate = parseResult.Template;
                    }

                    var groupPageRef = new PageReference(GetAttributeValue("GroupDetailPage"));

                    // create group detail link for use in map's info window
                    var personPageParams = new Dictionary <string, string>();
                    personPageParams.Add("PersonId", string.Empty);
                    var personProfilePage = LinkedPageUrl("PersonProfilePage", personPageParams);

                    var groupEntityType = EntityTypeCache.Get(typeof(Group));
                    var dynamicGroups   = new List <dynamic>();


                    // Create query to get attribute values for selected attribute keys.
                    var attributeKeys   = GetAttributeValue("Attributes").SplitDelimitedValues().ToList();
                    var attributeValues = new AttributeValueService(rockContext).Queryable("Attribute")
                                          .Where(v =>
                                                 v.Attribute.EntityTypeId == groupEntityType.Id &&
                                                 attributeKeys.Contains(v.Attribute.Key));

                    GroupService groupService = new GroupService(rockContext);
                    var          groups       = groupService.Queryable()
                                                .Where(g => g.GroupType.Guid == groupType)
                                                .Select(g => new
                    {
                        Group           = g,
                        GroupId         = g.Id,
                        GroupName       = g.Name,
                        GroupGuid       = g.Guid,
                        GroupMemberTerm = g.GroupType.GroupMemberTerm,
                        GroupCampus     = g.Campus.Name,
                        IsActive        = g.IsActive,
                        GroupLocation   = g.GroupLocations
                                          .Where(l => l.Location.GeoPoint != null)
                                          .Select(l => new
                        {
                            l.Location.Street1,
                            l.Location.Street2,
                            l.Location.City,
                            l.Location.State,
                            PostalCode = l.Location.PostalCode,
                            Latitude   = l.Location.GeoPoint.Latitude,
                            Longitude  = l.Location.GeoPoint.Longitude,
                            Name       = l.GroupLocationTypeValue.Value
                        }).FirstOrDefault(),
                        GroupMembers    = g.Members,
                        AttributeValues = attributeValues
                                          .Where(v => v.EntityId == g.Id)
                    });


                    if (GetAttributeValue("IncludeInactiveGroups").AsBoolean() == false)
                    {
                        groups = groups.Where(g => g.IsActive == true);
                    }

                    // Create dynamic object to include attribute values
                    foreach (var group in groups)
                    {
                        dynamic dynGroup = new ExpandoObject();
                        dynGroup.GroupId   = group.GroupId;
                        dynGroup.GroupName = group.GroupName;

                        // create group detail link for use in map's info window
                        if (groupPageRef.PageId > 0)
                        {
                            var groupPageParams = new Dictionary <string, string>();
                            groupPageParams.Add("GroupId", group.GroupId.ToString());
                            groupPageRef.Parameters  = groupPageParams;
                            dynGroup.GroupDetailPage = groupPageRef.BuildUrl();
                        }
                        else
                        {
                            dynGroup.GroupDetailPage = string.Empty;
                        }

                        dynGroup.PersonProfilePage = personProfilePage;
                        dynGroup.GroupMemberTerm   = group.GroupMemberTerm;
                        dynGroup.GroupCampus       = group.GroupCampus;
                        dynGroup.GroupLocation     = group.GroupLocation;

                        var groupAttributes = new List <dynamic>();
                        foreach (AttributeValue value in group.AttributeValues)
                        {
                            var attrCache     = AttributeCache.Get(value.AttributeId);
                            var dictAttribute = new Dictionary <string, object>();
                            dictAttribute.Add("Key", attrCache.Key);
                            dictAttribute.Add("Name", attrCache.Name);

                            if (attrCache != null)
                            {
                                dictAttribute.Add("Value", attrCache.FieldType.Field.FormatValueAsHtml(null, attrCache.EntityTypeId, group.GroupId, value.Value, attrCache.QualifierValues, false));
                            }
                            else
                            {
                                dictAttribute.Add("Value", value.Value);
                            }

                            groupAttributes.Add(dictAttribute);
                        }

                        dynGroup.Attributes = groupAttributes;

                        var groupMembers = new List <dynamic>();
                        foreach (GroupMember member in group.GroupMembers)
                        {
                            var dictMember = new Dictionary <string, object>();
                            dictMember.Add("Id", member.Person.Id);
                            dictMember.Add("GuidP", member.Person.Guid);
                            dictMember.Add("NickName", member.Person.NickName);
                            dictMember.Add("LastName", member.Person.LastName);
                            dictMember.Add("RoleName", member.GroupRole.Name);
                            dictMember.Add("Email", member.Person.Email);
                            dictMember.Add("PhotoGuid", member.Person.Photo != null ? member.Person.Photo.Guid : Guid.Empty);

                            var phoneTypes = new List <dynamic>();
                            foreach (PhoneNumber p in member.Person.PhoneNumbers)
                            {
                                var dictPhoneNumber = new Dictionary <string, object>();
                                dictPhoneNumber.Add("Name", p.NumberTypeValue.Value);
                                dictPhoneNumber.Add("Number", p.ToString());
                                phoneTypes.Add(dictPhoneNumber);
                            }

                            dictMember.Add("PhoneTypes", phoneTypes);

                            groupMembers.Add(dictMember);
                        }

                        dynGroup.GroupMembers = groupMembers;

                        dynamicGroups.Add(dynGroup);
                    }

                    foreach (var group in dynamicGroups)
                    {
                        if (group.GroupLocation != null && group.GroupLocation.Latitude != null)
                        {
                            groupsMapped++;
                            var groupDict = group as IDictionary <string, object>;

                            string infoWindow;

                            if (LavaService.RockLiquidIsEnabled)
                            {
                                infoWindow = template.Render(Hash.FromDictionary(groupDict)).Replace("\n", string.Empty);
                            }
                            else
                            {
                                var result = LavaService.RenderTemplate(lavaTemplate, groupDict);

                                infoWindow = result.Text;

                                if (!result.HasErrors)
                                {
                                    infoWindow = infoWindow.Replace("\n", string.Empty);
                                }
                            }

                            sbGroupJson.Append(string.Format(
                                                   @"{{ ""name"":""{0}"" , ""latitude"":""{1}"", ""longitude"":""{2}"", ""infowindow"":""{3}"" }},",
                                                   HttpUtility.HtmlEncode(group.GroupName),
                                                   group.GroupLocation.Latitude,
                                                   group.GroupLocation.Longitude,
                                                   HttpUtility.HtmlEncode(infoWindow)));
                        }
                        else
                        {
                            groupsWithNoGeo++;

                            if (!string.IsNullOrWhiteSpace(group.GroupDetailPage))
                            {
                                sbGroupsWithNoGeo.Append(string.Format(@"<li><a href='{0}'>{1}</a></li>", group.GroupDetailPage, group.GroupName));
                            }
                            else
                            {
                                sbGroupsWithNoGeo.Append(string.Format(@"<li>{0}</li>", group.GroupName));
                            }
                        }
                    }

                    string groupJson = sbGroupJson.ToString();

                    // remove last comma
                    if (groupJson.Length > 0)
                    {
                        groupJson = groupJson.Substring(0, groupJson.Length - 1);
                    }

                    // add styling to map
                    string styleCode   = "null";
                    string markerColor = "FE7569";

                    DefinedValueCache dvcMapStyle = DefinedValueCache.Get(GetAttributeValue("MapStyle").AsGuid());
                    if (dvcMapStyle != null)
                    {
                        styleCode = dvcMapStyle.GetAttributeValue("DynamicMapStyle");
                        var colors = dvcMapStyle.GetAttributeValue("Colors").Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        if (colors.Any())
                        {
                            markerColor = colors.First().Replace("#", "");
                        }
                    }

                    // write script to page
                    string mapScriptFormat = @" <script>
                                                Sys.Application.add_load(function () {{
                                                    var groupData = JSON.parse('{{ ""groups"" : [ {0} ]}}');
                                                    var showInfoWindow = {1};
                                                    var mapStyle = {2};
                                                    var pinColor = '{3}';

                                                    var pinImage = {{
                                                        path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
                                                        fillColor: '#' + pinColor,
                                                        fillOpacity: 1,
                                                        strokeColor: '#000',
                                                        strokeWeight: 1,
                                                        scale: 1,
                                                        labelOrigin: new google.maps.Point(0,-28)
                                                    }};

                                                    initializeMap();

                                                    function initializeMap() {{
                                                        console.log(mapStyle);
                                                        var map;
                                                        var bounds = new google.maps.LatLngBounds();
                                                        var mapOptions = {{
                                                            mapTypeId: 'roadmap',
                                                            styles: mapStyle
                                                        }};

                                                        // Display a map on the page
                                                        map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
                                                        map.setTilt(45);

                                                        // Display multiple markers on a map
                                                        if (showInfoWindow) {{
                                                            var infoWindow = new google.maps.InfoWindow(), marker, i;
                                                        }}

                                                        // Loop through our array of markers & place each one on the map
                                                        $.each(groupData.groups, function (i, group) {{

                                                            var position = new google.maps.LatLng(group.latitude, group.longitude);
                                                            bounds.extend(position);

                                                            marker = new google.maps.Marker({{
                                                                position: position,
                                                                map: map,
                                                                title: htmlDecode(group.name),
                                                                icon: pinImage,
                                                                label: String.fromCharCode(9679)
                                                            }});

                                                            // Allow each marker to have an info window
                                                            if (showInfoWindow) {{
                                                                google.maps.event.addListener(marker, 'click', (function (marker, i) {{
                                                                    return function () {{
                                                                        infoWindow.setContent(htmlDecode(groupData.groups[i].infowindow));
                                                                        infoWindow.open(map, marker);
                                                                    }}
                                                                }})(marker, i));
                                                            }}

                                                            map.fitBounds(bounds);

                                                        }});

                                                        // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
                                                        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {{
                                                            google.maps.event.removeListener(boundsListener);
                                                        }});
                                                    }}

                                                    function htmlDecode(input) {{
                                                        var e = document.createElement('div');
                                                        e.innerHTML = input;
                                                        return e.childNodes.length === 0 ? """" : e.childNodes[0].nodeValue;
                                                    }}
                                                }});
                                            </script>";

                    string mapScript = string.Format(
                        mapScriptFormat,
                        groupJson,
                        GetAttributeValue("ShowMapInfoWindow").AsBoolean().ToString().ToLower(),
                        styleCode,
                        markerColor);

                    ScriptManager.RegisterStartupScript(pnlMap, pnlMap.GetType(), "group-mapper-script", mapScript, false);

                    if (groupsMapped == 0)
                    {
                        pnlMap.Visible = false;
                        lMessages.Text = @" <p>
                                                <div class='alert alert-warning fade in'>No groups were able to be mapped. You may want to check your configuration.</div>
                                        </p>";
                    }
                    else
                    {
                        // output any warnings
                        if (groupsWithNoGeo > 0)
                        {
                            string messagesFormat = @" <p>
                                                <div class='alert alert-warning fade in'>Some groups could not be mapped.
                                                    <button type='button' class='close' data-dismiss='alert' aria-hidden='true'><i class='fa fa-times'></i></button>
                                                    <small><a data-toggle='collapse' data-parent='#accordion' href='#map-error-details'>Show Details</a></small>
                                                    <div id='map-error-details' class='collapse'>
                                                        <p class='margin-t-sm'>
                                                            <strong>Groups That Could Not Be Mapped</strong>
                                                            <ul>
                                                                {0}
                                                            </ul>
                                                        </p>
                                                    </div>
                                                </div>
                                            </p>";
                            lMessages.Text = string.Format(messagesFormat, sbGroupsWithNoGeo.ToString());
                        }
                    }
                }
                else
                {
                    pnlMap.Visible = false;
                    lMessages.Text = "<div class='alert alert-warning'><strong>Group Mapper</strong> Please configure a group type to display and a location type to use.</div>";
                }
            }
        }
        /// <summary>
        /// Uses Lava to resolve any merge codes within the content using the values in the merge objects.
        /// </summary>
        /// <param name="content">The content.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="enabledLavaCommands">The enabled lava commands.</param>
        /// <param name="encodeStrings">if set to <c>true</c> [encode strings].</param>
        /// <param name="throwExceptionOnErrors">if set to <c>true</c> [throw exception on errors].</param>
        /// <returns></returns>
        public static string RenderLava(this string content, IDictionary <string, object> mergeObjects, IEnumerable <string> enabledLavaCommands, bool encodeStrings = false, bool throwExceptionOnErrors = false)
        {
            try
            {
                if (!content.HasMergeFields())
                {
                    return(content ?? string.Empty);
                }

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

                if (GlobalAttributesCache.Get().LavaSupportLevel == Lava.LavaSupportLevel.LegacyWithWarning && mergeObjects.ContainsKey("GlobalAttribute"))
                {
                    if (hasLegacyGlobalAttributeLavaMergeFields.IsMatch(content))
                    {
                        Rock.Model.ExceptionLogService.LogException(new Rock.Lava.LegacyLavaSyntaxDetectedException("GlobalAttribute", ""), System.Web.HttpContext.Current);
                    }
                }

                var context = LavaService.NewRenderContext(mergeObjects);

                if (enabledLavaCommands != null)
                {
                    context.SetEnabledCommands(enabledLavaCommands);
                }

                var renderParameters = new LavaRenderParameters {
                    Context = context
                };

                renderParameters.ShouldEncodeStringsAsXml = encodeStrings;

                // Try and parse the template, or retrieve it from the cache if it has been previously parsed.
                var result = LavaService.RenderTemplate(content, renderParameters);

                if (result.HasErrors)
                {
                    throw result.GetLavaException();
                }

                return(result.Text);
            }
            catch (System.Threading.ThreadAbortException)
            {
                // Do nothing...it's just a Lava PageRedirect that just happened.
                return(string.Empty);
            }
            catch (Exception ex)
            {
                if (throwExceptionOnErrors)
                {
                    throw;
                }
                else
                {
                    ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                    return("Error resolving Lava merge fields: " + ex.Message);
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// Shows the wall.
        /// </summary>
        private void ShowWall()
        {
            var pageRef = CurrentPageReference;

            pageRef.Parameters.AddOrReplace("Page", "PageNum");

            var prayerRequests = new List <PrayerRequest>();

            var qry = new PrayerRequestService(new RockContext())
                      .Queryable()
                      .AsNoTracking()
                      .Where(r => r.ExpirationDate >= RockDateTime.Now &&
                             r.IsApproved == true &&
                             r.IsPublic == true);

            var categoryGuids = (GetAttributeValue("CategoryFilter") ?? string.Empty).SplitDelimitedValues().AsGuidList();

            if (categoryGuids.Any())
            {
                qry = qry.Where(a => a.CategoryId.HasValue && (categoryGuids.Contains(a.Category.Guid) || (a.Category.ParentCategoryId.HasValue && categoryGuids.Contains(a.Category.ParentCategory.Guid))));
            }

            var campusEntity = RockPage.GetCurrentContext(EntityTypeCache.Get(typeof(Campus)));

            if (campusEntity != null)
            {
                var campusId = campusEntity.Id;
                qry = qry.Where(r => r.CampusId.HasValue && r.CampusId == campusId);
            }

            var sortOrder = GetAttributeValue("SortOrder").AsInteger();

            switch (sortOrder)
            {
            case 0:
                qry = qry.OrderByDescending(a => a.EnteredDateTime);
                break;

            case 1:
                qry = qry.OrderBy(a => a.EnteredDateTime);
                break;
            }

            prayerRequests = qry.ToList();

            var pagination = new Pagination();

            pagination.ItemCount   = prayerRequests.Count();
            pagination.PageSize    = GetAttributeValue("PageSize").AsInteger();
            pagination.CurrentPage = PageParameter("Page").AsIntegerOrNull() ?? 1;
            pagination.UrlTemplate = pageRef.BuildUrl();

            var currentPrayerRequests = pagination.GetCurrentPageItems(prayerRequests);

            var commonMergeFields = LavaHelper.GetCommonMergeFields(RockPage);

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

            mergeFields.Add("Pagination", pagination);
            mergeFields.Add("PrayerRequests", currentPrayerRequests);

            Template      template     = null;
            ILavaTemplate lavaTemplate = null;
            var           error        = string.Empty;

            try
            {
                if (LavaService.RockLiquidIsEnabled)
                {
                    template = Template.Parse(GetAttributeValue("LavaTemplate"));

                    LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue("LavaTemplate"));
                }
                else
                {
                    var parseResult = LavaService.ParseTemplate(GetAttributeValue("LavaTemplate"));

                    lavaTemplate = parseResult.Template;
                }
            }
            catch (Exception ex)
            {
                error = string.Format("Lava error: {0}", ex.Message);
            }
            finally
            {
                if (error.IsNotNullOrWhiteSpace())
                {
                    nbError.Text    = error;
                    nbError.Visible = true;
                }

                if (template != null || lavaTemplate != null)
                {
                    if (LavaService.RockLiquidIsEnabled)
                    {
                        template.Registers["EnabledCommands"] = GetAttributeValue("EnabledLavaCommands");
                        lContent.Text = template.Render(Hash.FromDictionary(mergeFields));
                    }
                    else
                    {
                        var lavaContext = LavaService.NewRenderContext(mergeFields, GetAttributeValue("EnabledLavaCommands").SplitDelimitedValues());
                        var result      = LavaService.RenderTemplate(lavaTemplate, lavaContext);

                        lContent.Text = result.Text;
                    }
                }
            }
        }
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            using (var rockContext = new RockContext())
            {
                var channelQry = new InteractionChannelService(rockContext)
                                 .Queryable().AsNoTracking();

                var channelMediumValueId = gfFilter.GetUserPreference(MEDIUM_TYPE_FILTER).AsIntegerOrNull();
                if (channelMediumValueId.HasValue)
                {
                    channelQry = channelQry.Where(a => a.ChannelTypeMediumValueId == channelMediumValueId.Value);
                }

                if (!cbIncludeInactive.Checked)
                {
                    channelQry = channelQry.Where(a => a.IsActive);
                }

                if (!string.IsNullOrWhiteSpace(GetAttributeValue("InteractionChannels")))
                {
                    var selectedChannelIds = Array.ConvertAll(GetAttributeValue("InteractionChannels").Split(','), s => new Guid(s)).ToList();
                    channelQry = channelQry.Where(a => selectedChannelIds.Contains(a.Guid));
                }

                var personId = GetPersonId();
                if (personId.HasValue)
                {
                    var interactionQry = new InteractionService(rockContext).Queryable();
                    channelQry = channelQry.Where(a => interactionQry.Any(b => b.PersonAlias.PersonId == personId.Value && b.InteractionComponent.InteractionChannelId == a.Id));
                }

                // Parse the default template so that it does not need to be parsed multiple times.
                Template      defaultTemplate     = null;
                ILavaTemplate defaultLavaTemplate = null;

                if (LavaService.RockLiquidIsEnabled)
                {
                    defaultTemplate = Template.Parse(GetAttributeValue("DefaultTemplate"));

                    LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue("DefaultTemplate"));
                }
                else
                {
                    var parseResult = LavaService.ParseTemplate(GetAttributeValue("DefaultTemplate"));

                    defaultLavaTemplate = parseResult.Template;
                }

                var options = new Rock.Lava.CommonMergeFieldsOptions();
                options.GetPageContext             = false;
                options.GetLegacyGlobalMergeFields = false;

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, options);
                mergeFields.Add("ComponentListPage", LinkedPageRoute("ComponentListPage"));
                mergeFields.Add("SessionListPage", LinkedPageRoute("SessionListPage"));

                var channelItems = new List <ChannelItem>();

                if (LavaService.RockLiquidIsEnabled)
                {
                    foreach (var channel in channelQry)
                    {
                        if (!channel.IsAuthorized(Authorization.VIEW, CurrentPerson))
                        {
                            continue;
                        }
                        var channelMergeFields = new Dictionary <string, object>(mergeFields);
                        channelMergeFields.Add("InteractionChannel", channel);

                        string html = channel.ChannelListTemplate.IsNotNullOrWhiteSpace() ?
                                      channel.ChannelListTemplate.ResolveMergeFields(channelMergeFields) :
                                      defaultTemplate.Render(Hash.FromDictionary(channelMergeFields));

                        channelItems.Add(new ChannelItem
                        {
                            Id          = channel.Id,
                            ChannelHtml = html
                        });
                    }
                }
                else
                {
                    foreach (var channel in channelQry)
                    {
                        if (!channel.IsAuthorized(Authorization.VIEW, CurrentPerson))
                        {
                            continue;
                        }
                        var channelMergeFields = new Dictionary <string, object>(mergeFields);
                        channelMergeFields.Add("InteractionChannel", channel);

                        string html = channel.ChannelListTemplate.IsNotNullOrWhiteSpace() ?
                                      channel.ChannelListTemplate.ResolveMergeFields(channelMergeFields) :
                                      LavaService.RenderTemplate(defaultLavaTemplate, channelMergeFields).Text;

                        channelItems.Add(new ChannelItem
                        {
                            Id          = channel.Id,
                            ChannelHtml = html
                        });
                    }
                }

                rptChannel.DataSource = channelItems;
                rptChannel.DataBind();
            }
        }
Exemple #8
0
        private void LoadFeedItem(string feedItemId)
        {
            string feedUrl = GetAttributeValue(AttributeKey.RSSFeedUrl);
            Dictionary <string, string> messages = new Dictionary <string, string>();
            bool isError = false;

            try
            {
                Dictionary <string, object> feedDictionary = SyndicationFeedHelper.GetFeed(feedUrl, RockPage.Guid.ToString(), GetAttributeValue(AttributeKey.CacheDuration).AsInteger(), ref messages, ref isError);

                if (feedDictionary != null && feedDictionary.Count > 0)
                {
                    if (!String.IsNullOrWhiteSpace(GetAttributeValue(AttributeKey.RSSFeedUrl)) && GetAttributeValue(AttributeKey.IncludeRSSLink).AsBoolean())
                    {
                        string rssLink = string.Format("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{0}\" href=\"{1}\" />",
                                                       feedDictionary.ContainsKey("title") ? feedDictionary["title"].ToString() : "RSS",
                                                       GetAttributeValue(AttributeKey.RSSFeedUrl));

                        Page.Header.Controls.Add(new LiteralControl(rssLink));
                    }

                    Dictionary <string, object> previousItem = null;
                    Dictionary <string, object> selectedItem = null;
                    Dictionary <string, object> nextItem     = null;
                    if (feedDictionary.ContainsKey("item") || feedDictionary.ContainsKey("entry"))
                    {
                        List <Dictionary <string, object> > items = ((List <Dictionary <string, object> >)feedDictionary.Where(i => i.Key == "item" || i.Key == "entry").FirstOrDefault().Value);
                        for (int i = 0; i < items.Count; i++)
                        {
                            if (items[i]["articleHash"].ToString() == feedItemId)
                            {
                                selectedItem = items[i];


                                if (i > 0)
                                {
                                    nextItem = items[i - 1];
                                }

                                if (i < (items.Count - 1))
                                {
                                    previousItem = items[i + 1];
                                }
                                break;
                            }
                        }
                    }

                    Dictionary <string, object> feedFinal = new Dictionary <string, object>();
                    feedFinal.Add("Feed", feedDictionary);
                    feedFinal.Add("SelectedItem", selectedItem);
                    feedFinal.Add("PreviousItem", previousItem);
                    feedFinal.Add("NextItem", nextItem);

                    if (selectedItem == null)
                    {
                        messages.Add("Requested item not available", "The item that you requested is currently not available.");
                    }
                    else
                    {
                        string content;

                        if (LavaService.RockLiquidIsEnabled)
                        {
#pragma warning disable CS0618 // Type or member is obsolete
                            content = GetTemplate().Render(Hash.FromDictionary(feedFinal));
#pragma warning restore CS0618 // Type or member is obsolete
                        }
                        else
                        {
                            var renderParameters = new LavaRenderParameters
                            {
                                Context  = LavaService.NewRenderContext(feedFinal),
                                CacheKey = this.TemplateCacheKey
                            };

                            var result = LavaService.RenderTemplate(GetAttributeValue(AttributeKey.Template), renderParameters);

                            content = result.Text;
                        }

                        if (content.Contains("No such template"))
                        {
                            System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(GetAttributeValue(AttributeKey.Template), @"'([^']*)");
                            if (match.Success)
                            {
                                messages.Add("Warning", string.Format("Could not find the template _{0}.liquid in {1}.", match.Groups[1].Value, ResolveRockUrl("~~/Assets/Liquid")));
                                isError = true;
                            }
                            else
                            {
                                messages.Add("Warning", "Unable to parse the template name from settings.");
                                isError = true;
                            }
                        }
                        else
                        {
                            phFeedItem.Controls.Clear();
                            phFeedItem.Controls.Add(new LiteralControl(content));
                            pnlContent.Visible = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (IsUserAuthorized(Rock.Security.Authorization.ADMINISTRATE))
                {
                    throw ex;
                }
                else
                {
                    messages.Add("Content not available.", "Oops. The requested content is not currently available. Please try again later.");
                    isError = true;
                }
            }


            if (messages.Count > 0)
            {
                if (IsUserAuthorized(Rock.Security.Authorization.ADMINISTRATE))
                {
                    SetNotificationBox(messages.FirstOrDefault().Key, messages.FirstOrDefault().Value, isError ? NotificationBoxType.Warning : NotificationBoxType.Info);
                }
                else
                {
                    SetNotificationBox("Content not available", "Oops. The requested content is not currently available. Please try again later.");
                }
            }
        }
Exemple #9
0
        private void LoadFeed()
        {
            string feedUrl = GetAttributeValue(AttributeKey.RSSFeedUrl);

            Dictionary <string, string> messages = new Dictionary <string, string>();
            bool isError = false;

            try
            {
                Dictionary <string, object> feedDictionary = SyndicationFeedHelper.GetFeed(feedUrl, GetAttributeValue(AttributeKey.DetailPage), GetAttributeValue(AttributeKey.CacheDuration).AsInteger(), ref messages, ref isError);

                if (feedDictionary != null)
                {
                    int    articlesPerPage = GetAttributeValue(AttributeKey.Resultsperpage).AsInteger();
                    int    currentPage     = 0;
                    string baseUrl         = new PageReference(RockPage.PageId).BuildUrl();

                    int.TryParse(PageParameter(PageParameterKey.ArticlePage), out currentPage);

                    if (feedDictionary.ContainsKey("ResultsPerPage"))
                    {
                        feedDictionary["ResultsPerPage"] = articlesPerPage;
                    }
                    else
                    {
                        feedDictionary.Add("ResultsPerPage", articlesPerPage);
                    }


                    if (feedDictionary.ContainsKey("CurrentPage"))
                    {
                        feedDictionary["CurrentPage"] = currentPage;
                    }
                    else
                    {
                        feedDictionary.Add("CurrentPage", currentPage);
                    }

                    if (feedDictionary.ContainsKey("BaseUrl"))
                    {
                        feedDictionary["BaseUrl"] = baseUrl;
                    }
                    else
                    {
                        feedDictionary.Add("BaseUrl", baseUrl);
                    }


                    if (!String.IsNullOrWhiteSpace(GetAttributeValue(AttributeKey.RSSFeedUrl)) && GetAttributeValue(AttributeKey.IncludeRSSLink).AsBoolean())
                    {
                        string rssLink = string.Format("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"{0}\" href=\"{1}\" />",
                                                       feedDictionary.ContainsKey("title") ? feedDictionary["title"].ToString() : "RSS",
                                                       GetAttributeValue(AttributeKey.RSSFeedUrl));

                        Page.Header.Controls.Add(new LiteralControl(rssLink));
                    }


                    // rearrange the dictionary for cleaning purposes
                    if (feedDictionary.ContainsKey("entry"))
                    {
                        var item = feedDictionary["entry"];

                        if (item != null)
                        {
                            feedDictionary.Remove("entry");
                            feedDictionary["Entries"] = item;
                        }
                    }


                    // remove the link item
                    if (feedDictionary.ContainsKey("link"))
                    {
                        var item = feedDictionary["link"];

                        if (item != null)
                        {
                            feedDictionary.Remove("link");
                        }
                    }

                    string content = String.Empty;

                    if (LavaService.RockLiquidIsEnabled)
                    {
#pragma warning disable CS0618 // Type or member is obsolete
                        content = GetTemplate().Render(Hash.FromDictionary(feedDictionary));
#pragma warning restore CS0618 // Type or member is obsolete
                    }
                    else
                    {
                        var renderParameters = new LavaRenderParameters
                        {
                            Context  = LavaService.NewRenderContext(feedDictionary),
                            CacheKey = this.TemplateCacheKey
                        };

                        var result = LavaService.RenderTemplate(GetAttributeValue(AttributeKey.Template), renderParameters);

                        content = result.Text;
                    }

                    if (content.Contains("No such template"))
                    {
                        System.Text.RegularExpressions.Match match = System.Text.RegularExpressions.Regex.Match(GetAttributeValue(AttributeKey.Template), @"'([^']*)");
                        if (match.Success)
                        {
                            messages.Add("Warning", string.Format("Could not find the template _{0}.liquid in {1}.", match.Groups[1].Value, ResolveRockUrl("~~/Assets/Liquid")));
                            isError = true;
                        }
                        else
                        {
                            messages.Add("Warning", "Unable to parse the template name from settings.");
                            isError = true;
                        }
                    }
                    else
                    {
                        phRSSFeed.Controls.Clear();
                        phRSSFeed.Controls.Add(new LiteralControl(content));
                    }

                    pnlContent.Visible = true;
                }
            }
            catch (Exception ex)
            {
                if (IsUserAuthorized(Authorization.ADMINISTRATE))
                {
                    throw ex;
                }
                else
                {
                    messages.Add("exception", "An exception has occurred.");
                }
            }

            if (messages.Count > 0)
            {
                if (IsUserAuthorized(Authorization.ADMINISTRATE))
                {
                    SetNotificationBox(messages.FirstOrDefault().Key, messages.FirstOrDefault().Value, isError ? NotificationBoxType.Warning : NotificationBoxType.Info);
                }
                else
                {
                    SetNotificationBox("Content not available", "Oops. The requested content is not currently available. Please try again later.");
                }
            }
        }