Ejemplo n.º 1
0
        protected override LavaRenderResult OnRenderTemplate(ILavaTemplate inputTemplate, LavaRenderParameters parameters)
        {
            var templateProxy = inputTemplate as FluidTemplateProxy;
            var template      = templateProxy?.FluidTemplate;

            var templateContext = parameters.Context as FluidRenderContext;

            if (templateContext == null)
            {
                throw new LavaException("Invalid LavaContext parameter. This context type is not compatible with the Fluid templating engine.");
            }

            var result = new LavaRenderResult();
            var sb     = new StringBuilder();

            // Set the render options for culture and timezone if they are specified.
            if (parameters.Culture != null)
            {
                templateContext.FluidContext.Options.CultureInfo = parameters.Culture;
            }
            if (parameters.TimeZone != null)
            {
                templateContext.FluidContext.Options.TimeZone = parameters.TimeZone;
            }

            // Set the render options for encoding.
            System.Text.Encodings.Web.TextEncoder encoder;
            if (parameters.ShouldEncodeStringsAsXml)
            {
                encoder = System.Text.Encodings.Web.HtmlEncoder.Default;
            }
            else
            {
                encoder = NullEncoder.Default;
            }

            var writer = new StringWriter(sb);

            try
            {
                template.Render(templateContext.FluidContext, encoder, writer);

                writer.Flush();
                result.Text = sb.ToString();
            }
            catch (LavaInterruptException)
            {
                // The render was terminated intentionally, so return the current buffer content.
                writer.Flush();
                result.Text = sb.ToString();
            }
            finally
            {
                writer.Dispose();
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Render the provided template in a new context with the specified parameters.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="parameters">The settings applied to the rendering process.</param>
        /// <returns>
        /// A LavaRenderResult object, containing the rendered output of the template or any errors encountered during the rendering process.
        /// </returns>
        public static LavaRenderResult RenderTemplate(ILavaTemplate inputTemplate, LavaRenderParameters parameters)
        {
            if (_engine == null)
            {
                return(null);
            }

            return(_engine.RenderTemplate(inputTemplate, parameters));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Render the provided template in a new context with the specified parameters.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="context">The settings applied to the rendering process.</param>
        /// <returns>
        /// A LavaRenderResult object, containing the rendered output of the template or any errors encountered during the rendering process.
        /// </returns>
        public static LavaRenderResult RenderTemplate(ILavaTemplate inputTemplate, ILavaRenderContext context)
        {
            if (_engine == null)
            {
                return(null);
            }

            return(RenderTemplate(inputTemplate, LavaRenderParameters.WithContext(context)));
        }
        void ILavaTemplateCacheService.AddTemplate(ILavaTemplate template, string cacheKey)
        {
            if (string.IsNullOrWhiteSpace(cacheKey))
            {
                throw new Exception("WebsiteLavaTemplateCache template add failed. A cache key must be specified.");
            }

            WebsiteLavaTemplateCache.UpdateCacheItem(cacheKey, new WebsiteLavaTemplateCache()
            {
                Template = template
            });
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Render the Lava template using the DotLiquid rendering engine.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="output"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        protected override LavaRenderResult OnRenderTemplate(ILavaTemplate template, LavaRenderParameters parameters)
        {
            var result = new LavaRenderResult();

            var renderSettings = new RenderParameters();

            // Set the flag to rethrow exceptions generated by the DotLiquid framework, so they can be intercepted and handled as Lava errors.
            // Note that this flag is required in addition to the Context(rethrowErrors) constructor parameter.
            renderSettings.RethrowErrors = true;

            var templateContext = parameters.Context as DotLiquidRenderContext;

            if (templateContext == null)
            {
                throw new LavaException("Invalid LavaContext parameter. This context type is not compatible with the DotLiquid templating engine.");
            }

            var dotLiquidContext = templateContext.DotLiquidContext;

            renderSettings.Context = dotLiquidContext;

            if (parameters.ShouldEncodeStringsAsXml)
            {
                renderSettings.ValueTypeTransformers = new Dictionary <Type, Func <object, object> >();
                renderSettings.ValueTypeTransformers.Add(typeof(string), EncodeStringTransformer);
            }

            // Call the Render method of the underlying DotLiquid template.
            var templateProxy = template as DotLiquidTemplateProxy;

            if (templateProxy == null)
            {
                throw new Exception("Render failed. The provided template instance is not compatible with the DotLiquid engine.");
            }

            result.Text = templateProxy.DotLiquidTemplate.Render(renderSettings);

            if (renderSettings.Context.Errors != null)
            {
                if (renderSettings.Context.Errors.Count > 1)
                {
                    result.Error = new AggregateException(renderSettings.Context.Errors);
                }
                else
                {
                    result.Error = renderSettings.Context.Errors.FirstOrDefault();
                }
            }

            return(result);
        }
Ejemplo n.º 6
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>";
                }
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Render the provided template in a new context with the specified merge fields.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="mergeFields">The collection of merge fields to be added to the context used to render the template.</param>
        /// <returns>
        /// The rendered output of the template.
        /// If the template is invalid, returns an error message or an empty string according to the current ExceptionHandlingStrategy setting.
        /// </returns>
        public static LavaRenderResult RenderTemplate(ILavaTemplate inputTemplate, IDictionary <string, object> mergeFields)
        {
            var result = RenderTemplate(inputTemplate, LavaRenderParameters.WithContext(_engine.NewRenderContext(mergeFields)));

            return(result);
        }
Ejemplo n.º 8
0
 void ILavaTemplateCacheService.AddTemplate(ILavaTemplate template, string cacheKey)
 {
     return;
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Override this method to render the Lava template using the underlying rendering engine.
 /// </summary>
 /// <param name="inputTemplate"></param>
 /// <param name="parameters"></param>
 /// <returns></returns>
 protected abstract LavaRenderResult OnRenderTemplate(ILavaTemplate inputTemplate, LavaRenderParameters parameters);
Ejemplo n.º 10
0
        /// <summary>
        /// Render the provided template using the specified parameters.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="parameters"></param>
        /// <returns>
        /// The result of the render operation.
        /// If the template is invalid, the Text property may contain  an error message or an empty string according to the current ExceptionHandlingStrategy setting.
        /// </returns>
        public LavaRenderResult RenderTemplate(ILavaTemplate template, LavaRenderParameters parameters)
        {
            parameters = parameters ?? new LavaRenderParameters();

            LavaRenderResult     result;
            LavaRenderParameters callParameters;

            try
            {
                if (parameters == null)
                {
                    callParameters = new LavaRenderParameters();
                }
                else if (parameters.Context == null)
                {
                    callParameters         = parameters.Clone();
                    callParameters.Context = NewRenderContext();
                }
                else
                {
                    if (parameters.Context.GetType() == typeof(LavaRenderContext))
                    {
                        callParameters = parameters.Clone();

                        // Convert the default context to an engine-specific implementation.
                        var engineContext = NewRenderContext();

                        engineContext.SetInternalFields(parameters.Context.GetInternalFields());
                        engineContext.SetMergeFields(parameters.Context.GetMergeFields());
                        engineContext.SetEnabledCommands(parameters.Context.GetEnabledCommands());

                        // Create a copy of the parameters to ensure the input parameter remains unchanged.
                        callParameters.Context = engineContext;
                    }
                    else
                    {
                        callParameters = parameters;
                    }
                }

                result = OnRenderTemplate(template, callParameters);

                if (result.Error != null)
                {
                    result.Error = GetLavaRenderException(result.Error);
                }
            }
            catch (LavaInterruptException)
            {
                // This exception is intentionally thrown by a component to halt the render process.
                result = new LavaRenderResult();

                result.Text = string.Empty;
            }
            catch (Exception ex)
            {
                if (ex is ThreadAbortException)
                {
                    // Ignore this exception, the calling thread is terminating and no result is required.
                    return(null);
                }

                result = new LavaRenderResult();

                var lre = GetLavaRenderException(ex);

                string message;

                ProcessException(lre, parameters.ExceptionHandlingStrategy, out message);

                result.Error = lre;
                result.Text  = message;
            }

            return(result);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Render the provided template using the specified parameters.
 /// </summary>
 /// <param name="inputTemplate"></param>
 /// <param name="context"></param>
 /// <returns>
 /// The result of the render operation.
 /// If the template is invalid, the Text property may contain  an error message or an empty string according to the current ExceptionHandlingStrategy setting.
 /// </returns>
 public LavaRenderResult RenderTemplate(ILavaTemplate template, ILavaRenderContext context)
 {
     return(RenderTemplate(template, new LavaRenderParameters {
         Context = context
     }));
 }
Ejemplo n.º 12
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();
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Render the Lava template using the DotLiquid rendering engine.
        /// </summary>
        /// <param name="inputTemplate"></param>
        /// <param name="output"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        protected override LavaRenderResult OnRenderTemplate(ILavaTemplate template, LavaRenderParameters parameters)
        {
            var result = new LavaRenderResult();

            try
            {
                var renderSettings = new RenderParameters();

                // Set the flag to rethrow exceptions generated by the DotLiquid framework, so they can be intercepted and handled as Lava errors.
                // Note that this flag is required in addition to the Context(rethrowErrors) constructor parameter.
                renderSettings.RethrowErrors = true;

                var templateContext = parameters.Context as RockLiquidRenderContext;

                if (templateContext == null)
                {
                    throw new LavaException("Invalid LavaContext parameter. This context type is not compatible with the RockLiquid templating engine.");
                }

                var dotLiquidContext = templateContext.DotLiquidContext;

                renderSettings.Context = dotLiquidContext;

                if (parameters.ShouldEncodeStringsAsXml)
                {
                    renderSettings.ValueTypeTransformers = new Dictionary <Type, Func <object, object> >();
                    renderSettings.ValueTypeTransformers.Add(typeof(string), EncodeStringTransformer);
                }

                // Call the Render method of the underlying DotLiquid template.
                var templateProxy = template as DotLiquidTemplateProxy;

                result.Text = templateProxy.DotLiquidTemplate.Render(renderSettings);

                if (renderSettings.Context.Errors != null)
                {
                    if (renderSettings.Context.Errors.Count > 1)
                    {
                        result.Error = new AggregateException(renderSettings.Context.Errors);
                    }
                    else
                    {
                        result.Error = renderSettings.Context.Errors.FirstOrDefault();
                    }
                }
            }
            catch (LavaInterruptException)
            {
                // Ignore this exception, it is thrown by custom Lava components to terminate the render process prematurely.
            }
            catch (Exception ex)
            {
                string output;

                ProcessException(ex, parameters.ExceptionHandlingStrategy, out output);

                result.Text  = output;
                result.Error = ex;
            }

            return(result);
        }