Ejemplo n.º 1
0
        private Template GetTemplate()
        {
            var cacheTemplate = LavaTemplateCache.Get(CacheKey(), GetAttributeValue(AttributeKey.Template));

            LavaHelper.VerifyParseTemplateForCurrentEngine(GetAttributeValue(AttributeKey.Template));

            return(cacheTemplate != null ? cacheTemplate.Template as Template : null);
        }
Ejemplo n.º 2
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;
                    }
                }
            }
        }
Ejemplo n.º 3
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>
        /// 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();
            }
        }