Helper class to work with the PageReference field type
Exemple #1
0
        /// <summary>
        /// Handles the Click event of the btnAddTransaction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnAddTransaction_Click(object sender, EventArgs e)
        {
            var addTransactionPage = new Rock.Web.PageReference(this.GetAttributeValue(AttributeKey.AddTransactionPage));

            if (addTransactionPage != null)
            {
                if (!this.Person.IsPersonTokenUsageAllowed())
                {
                    mdWarningAlert.Show($"Due to their protection profile level you cannot add a transaction on behalf of this person.", ModalAlertType.Warning);
                    return;
                }

                // create a limited-use personkey that will last long enough for them to go thru all the 'postbacks' while posting a transaction
                var personKey = this.Person.GetImpersonationToken(
                    RockDateTime.Now.AddMinutes(this.GetAttributeValue(AttributeKey.PersonTokenExpireMinutes).AsIntegerOrNull() ?? 60),
                    this.GetAttributeValue(AttributeKey.PersonTokenUsageLimit).AsIntegerOrNull(),
                    addTransactionPage.PageId);

                if (personKey.IsNotNullOrWhiteSpace())
                {
                    addTransactionPage.QueryString["Person"] = personKey;
                    Response.Redirect(addTransactionPage.BuildUrl());
                }
            }
        }
        /// <summary>
        /// Handles the ItemDataBound event of the rConnectionTypes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void rConnectionTypes_ItemDataBound( object sender, RepeaterItemEventArgs e )
        {
            var lConnectionOpportunityList = e.Item.FindControl( "lConnectionOpportunityList" ) as Literal;
            if ( lConnectionOpportunityList != null )
            {
                var connectionType = e.Item.DataItem as ConnectionType;
                var pageGuid = this.GetAttributeValue( "ConnectionRequestDetail" ).AsGuidOrNull();
                PageReference connectionRequestDetailPage = null;
                if ( pageGuid.HasValue )
                {
                    connectionRequestDetailPage = new PageReference( pageGuid.Value.ToString() );
                }

                if ( connectionType != null && this.Person != null )
                {
                    using ( var rockContext = new RockContext() )
                    {
                        int personId = this.Person.Id;
                        var connectionRequestService = new ConnectionRequestService( rockContext );
                        var connectionRequestList = connectionRequestService.Queryable().Where( a => a.PersonAlias.PersonId == personId && a.ConnectionOpportunity.ConnectionTypeId == connectionType.Id ).OrderBy( a => a.ConnectionOpportunity.Name ).AsNoTracking().ToList();
                        string listHtml = string.Empty;
                        foreach ( var connectionRequest in connectionRequestList )
                        {
                            string connectionNameHtml;
                            string connectionName;
                            if ( connectionRequest.CampusId.HasValue )
                            {
                                connectionName = string.Format( "{0} ({1})", connectionRequest.ConnectionOpportunity, CampusCache.Read( connectionRequest.CampusId.Value ) );
                            }
                            else
                            {
                                connectionName = string.Format( "{0}", connectionRequest.ConnectionOpportunity );
                            }

                            if ( connectionRequestDetailPage != null && connectionRequestDetailPage.PageId > 0 )
                            {
                                connectionRequestDetailPage.Parameters = new System.Collections.Generic.Dictionary<string, string>();
                                connectionRequestDetailPage.Parameters.Add( "ConnectionRequestId", connectionRequest.Id.ToString() );
                                connectionRequestDetailPage.Parameters.Add( "ConnectionOpportunityId", connectionRequest.ConnectionOpportunityId.ToString() );

                                connectionNameHtml = string.Format( "<a href='{0}'>{1}</a>", connectionRequestDetailPage.BuildUrl(), connectionName );
                            }
                            else
                            {
                                connectionNameHtml = connectionName;
                            }

                            listHtml += string.Format(
                                "<li {0}>{1} - <small>{2}</small></li>",
                                connectionRequest.ConnectionState == ConnectionState.Connected ? "class='is-inactive'" : string.Empty,
                                connectionNameHtml,
                                connectionRequest.ConnectionState == ConnectionState.Connected ? "Connected" : connectionRequest.ConnectionStatus.ToString() );
                        }

                        lConnectionOpportunityList.Text = listHtml;
                    }
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Handles the Click event of the btnTextToGiveSettings control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnTextToGiveSettings_Click(object sender, EventArgs e)
        {
            var settingsPage = new Rock.Web.PageReference(GetAttributeValue(AttributeKey.TextToGiveSettingsPage));

            if (settingsPage != null && Person != null)
            {
                NavigateToLinkedPage(AttributeKey.TextToGiveSettingsPage, new Dictionary <string, string> {
                    { "PersonId", Person.Id.ToString() }
                });
            }
        }
Exemple #4
0
        /// <summary>
        /// Handles the Click event of the btnAddTransaction control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnAddTransaction_Click(object sender, EventArgs e)
        {
            var addTransactionPage = new Rock.Web.PageReference(this.GetAttributeValue(AttributeKey.AddTransactionPage));

            if (addTransactionPage != null)
            {
                // create a limited-use personkey that will last long enough for them to go thru all the 'postbacks' while posting a transaction
                var personKey = this.Person.GetImpersonationToken(RockDateTime.Now.AddMinutes(this.GetAttributeValue(AttributeKey.PersonTokenExpireMinutes).AsIntegerOrNull() ?? 60), this.GetAttributeValue(AttributeKey.PersonTokenUsageLimit).AsIntegerOrNull(), addTransactionPage.PageId);
                addTransactionPage.QueryString["Person"] = personKey;
                Response.Redirect(addTransactionPage.BuildUrl());
            }
        }
 /// <summary>
 /// Gets the parent page references.
 /// </summary>
 /// <param name="rockPage">The rock page.</param>
 /// <param name="currentPage">The current page.</param>
 /// <param name="currentPageReference">The current page reference.</param>
 /// <returns></returns>
 public static List <PageReference> GetParentPageReferences(RockPage rockPage, PageCache currentPage, PageReference currentPageReference)
 {
     return(GetParentPageReferences(rockPage, currentPage, currentPageReference, null));
 }
        private void Map()
        {
            string mapStylingFormat = @"
                        <style>
                            #map_wrapper {{
                                height: {0}px;
                            }}

                            #map_canvas {{
                                width: 100%;
                                height: 100%;
                                border-radius: 8px;
                            }}
                        </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;
                    if ( GetAttributeValue( "ShowMapInfoWindow" ).AsBoolean() )
                    {
                        template = Template.Parse( GetAttributeValue( "InfoWindowContents" ).Trim() );
                    }
                    else
                    {
                        template = Template.Parse( string.Empty );
                    }

                    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.Read( 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.Read( 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, 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 );
                    }

                    // enable showing debug info
                    if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                    {
                        lDebug.Visible = true;
                        lDebug.Text = dynamicGroups.Take( 5 ).lavaDebugInfo();
                    }
                    else
                    {
                        lDebug.Visible = false;
                        lDebug.Text = string.Empty;
                    }

                    foreach ( var group in dynamicGroups )
                    {
                        if ( group.GroupLocation != null && group.GroupLocation.Latitude != null )
                        {
                            groupsMapped++;
                            var groupDict = group as IDictionary<string, object>;
                            string infoWindow = template.Render( Hash.FromDictionary( groupDict ) ).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.Read( 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 = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|' + pinColor,
                                                        new google.maps.Size(21, 34),
                                                        new google.maps.Point(0,0),
                                                        new google.maps.Point(10, 34));
                                                    var pinShadow = new google.maps.MarkerImage('http://chart.apis.google.com/chart?chst=d_map_pin_shadow',
                                                        new google.maps.Size(40, 37),
                                                        new google.maps.Point(0, 0),
                                                        new google.maps.Point(12, 35));

                                                    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,
                                                                shadow: pinShadow
                                                            }});

                                                            // 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>";
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Shows the summary.
        /// </summary>
        /// <param name="business">The business.</param>
        private void ShowSummary(int businessId)
        {
            SetEditMode(false);
            hfBusinessId.SetValue(businessId);
            lTitle.Text = "View Business".FormatAsHtmlTitle();

            var business = new PersonService(new RockContext()).Get(businessId);

            if (business != null)
            {
                SetHeadingStatusInfo(business);
                var detailsLeft = new DescriptionList();
                detailsLeft.Add("Business Name", business.LastName);

                if (business.GivingGroup != null)
                {
                    detailsLeft.Add("Campus", business.GivingGroup.Campus);
                }

                if (business.RecordStatusReasonValue != null)
                {
                    detailsLeft.Add("Record Status Reason", business.RecordStatusReasonValue);
                }

                lDetailsLeft.Text = detailsLeft.Html;

                var detailsRight = new DescriptionList();

                // Get address
                var workLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK.AsGuid());
                if (workLocationType != null)
                {
                    if (business.GivingGroup != null)   // Giving Group is a shortcut to Family Group for business
                    {
                        var location = business.GivingGroup.GroupLocations
                                       .Where(gl => gl.GroupLocationTypeValueId == workLocationType.Id)
                                       .Select(gl => gl.Location)
                                       .FirstOrDefault();
                        if (location != null)
                        {
                            detailsRight.Add("Address", location.GetFullStreetAddress().ConvertCrLfToHtmlBr());
                        }
                    }
                }

                var workPhoneType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid());
                if (workPhoneType != null)
                {
                    var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == workPhoneType.Id);
                    if (phoneNumber != null)
                    {
                        detailsRight.Add("Phone Number", phoneNumber.ToString());
                    }
                }

                var communicationLinkedPageValue = this.GetAttributeValue("CommunicationPage");
                Rock.Web.PageReference communicationPageReference;
                if (communicationLinkedPageValue.IsNotNullOrWhiteSpace())
                {
                    communicationPageReference = new Rock.Web.PageReference(communicationLinkedPageValue);
                }
                else
                {
                    communicationPageReference = null;
                }

                detailsRight.Add("Email Address", business.GetEmailTag(ResolveRockUrl("/"), communicationPageReference));

                lDetailsRight.Text = detailsRight.Html;
            }
        }
        /// <summary>
        /// Updates the list.
        /// </summary>
        private void UpdateList()
        {
            using ( var rockContext = new RockContext() )
            {
                var searchSelections = new Dictionary<string, string>();

                var connectionTypeId = GetAttributeValue( "ConnectionTypeId" ).AsInteger();
                var connectionType = new ConnectionTypeService( rockContext ).Get( connectionTypeId );
                var connectionOpportunityService = new ConnectionOpportunityService( rockContext );

                var qrySearch = connectionOpportunityService.Queryable().Where( a => a.ConnectionTypeId == connectionTypeId && a.IsActive == true ).ToList();

                if ( GetAttributeValue( "DisplayNameFilter" ).AsBoolean() )
                {
                    if ( !string.IsNullOrWhiteSpace( tbSearchName.Text ) )
                    {
                        searchSelections.Add( "tbSearchName", tbSearchName.Text );
                        var searchTerms = tbSearchName.Text.ToLower().SplitDelimitedValues( true );
                        qrySearch = qrySearch.Where( o => searchTerms.Any( t => t.Contains( o.Name.ToLower() ) || o.Name.ToLower().Contains( t ) ) ).ToList();
                    }
                }

                if ( GetAttributeValue( "DisplayCampusFilter" ).AsBoolean() )
                {
                    var searchCampuses = cblCampus.SelectedValuesAsInt;
                    if ( searchCampuses.Count > 0 )
                    {
                        searchSelections.Add( "cblCampus", searchCampuses.AsDelimited("|") );
                        qrySearch = qrySearch.Where( o => o.ConnectionOpportunityCampuses.Any( c => searchCampuses.Contains( c.CampusId ) ) ).ToList();
                    }
                }

                if ( GetAttributeValue( "DisplayAttributeFilters" ).AsBoolean() )
                {
                    // Filter query by any configured attribute filters
                    if ( AvailableAttributes != null && AvailableAttributes.Any() )
                    {
                        var attributeValueService = new AttributeValueService( rockContext );
                        var parameterExpression = attributeValueService.ParameterExpression;

                        foreach ( var attribute in AvailableAttributes )
                        {
                            string filterControlId = "filter_" + attribute.Id.ToString();
                            var filterControl = phAttributeFilters.FindControl( filterControlId );
                            if ( filterControl != null )
                            {
                                var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter );
                                var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression );
                                if ( expression != null )
                                {
                                    searchSelections.Add( filterControlId, filterValues.ToJson() );
                                    var attributeValues = attributeValueService
                                        .Queryable()
                                        .Where( v => v.Attribute.Id == attribute.Id );

                                    attributeValues = attributeValues.Where( parameterExpression, expression, null );

                                    qrySearch = qrySearch.Where( o => attributeValues.Select( v => v.EntityId ).Contains( o.Id ) ).ToList();
                                }
                            }
                        }
                    }
                }

                string sessionKey = string.Format( "ConnectionSearch_{0}", this.BlockId );
                Session[sessionKey] = searchSelections;

                var opportunities = qrySearch.OrderBy( s => s.PublicName ).ToList();

                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "Opportunities", opportunities);
                mergeFields.Add( "CurrentPerson", CurrentPerson );

                var pageReference = new PageReference( GetAttributeValue( "DetailPage" ), null );
                mergeFields.Add( "DetailPage", BuildDetailPageUrl(pageReference.BuildUrl()) );

                lOutput.Text = GetAttributeValue( "LavaTemplate" ).ResolveMergeFields( mergeFields );

                if ( GetAttributeValue( "SetPageTitle" ).AsBoolean() )
                {
                    string pageTitle = "Connection";
                    RockPage.PageTitle = pageTitle;
                    RockPage.BrowserTitle = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                    RockPage.Header.Title = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                }

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
        }
        public InfoWindowResult GetMapInfoWindow( int groupId, int locationId, [FromBody] InfoWindowRequest infoWindowDetails )
        {
            // Enable proxy creation since security is being checked and need to navigate parent authorities
            SetProxyCreation( true );

            // Use new service with new context so properties can be navigated by liquid
            var group = new GroupService( new RockContext() ).Queryable( "GroupType,GroupLocations.Location,Campus,Members.Person" )
                .Where( g => g.Id == groupId )
                .FirstOrDefault();

            if ( group != null )
            {
                var person = GetPerson();

                if ( group.IsAuthorized( Rock.Security.Authorization.VIEW, person ) )
                {
                    string infoWindow = group.Name;

                    if ( infoWindowDetails != null )
                    {
                        var groupPageParams = new Dictionary<string, string>();
                        groupPageParams.Add( "GroupId", group.Id.ToString() );
                        var groupDetailUrl = new PageReference( infoWindowDetails.GroupPage, groupPageParams ).BuildUrl();

                        var personPageParams = new Dictionary<string, string>();
                        personPageParams.Add( "PersonId", string.Empty );
                        var personProfileUrl = new PageReference( infoWindowDetails.PersonProfilePage, personPageParams ).BuildUrl();

                        var mapPageParams = new Dictionary<string, string>();
                        mapPageParams.Add( "GroupId", group.Id.ToString() );
                        var groupMapUrl = new PageReference( infoWindowDetails.MapPage, mapPageParams ).BuildUrl();

                        var grouplocation = group.GroupLocations
                            .Where( g => g.LocationId == locationId )
                            .FirstOrDefault();

                        dynamic dynGroup = new ExpandoObject();
                        dynGroup.GroupId = group.Id;
                        dynGroup.GroupName = group.Name;
                        dynGroup.DetailPageUrl = groupDetailUrl;
                        dynGroup.MapPageUrl = groupMapUrl;

                        var dictCampus = new Dictionary<string, object>();
                        dictCampus.Add( "Name", group.Campus != null ? group.Campus.Name : string.Empty );
                        dynGroup.Campus = dictCampus;

                        var dictGroupType = new Dictionary<string, object>();
                        dictGroupType.Add( "Id", group.GroupType.Id );
                        dictGroupType.Add( "Guid", group.GroupType.Guid.ToString().ToUpper() );
                        dictGroupType.Add( "GroupTerm", group.GroupType.GroupTerm );
                        dictGroupType.Add( "GroupMemberTerm", group.GroupType.GroupMemberTerm );
                        dynGroup.GroupType = dictGroupType;

                        var dictLocation = new Dictionary<string, object>();
                        dictLocation.Add( "Type", grouplocation.GroupLocationTypeValue.Value );
                        dictLocation.Add( "Address", grouplocation.Location.GetFullStreetAddress().ConvertCrLfToHtmlBr() );
                        dictLocation.Add( "Street1", grouplocation.Location.Street1 );
                        dictLocation.Add( "Street2", grouplocation.Location.Street2 );
                        dictLocation.Add( "City", grouplocation.Location.City );
                        dictLocation.Add( "State", grouplocation.Location.State );
                        dictLocation.Add( "PostalCode", grouplocation.Location.PostalCode );
                        dictLocation.Add( "Country", grouplocation.Location.Country );
                        dynGroup.Location = dictLocation;

                        var members = new List<Dictionary<string, object>>();
                        foreach ( var member in group.Members.OrderBy( m => m.GroupRole.Order ).ThenBy( m => m.Person.BirthDate ) )
                        {
                            var dictMember = new Dictionary<string, object>();
                            dictMember.Add( "PersonId", member.Person.Id );
                            dictMember.Add( "ProfilePageUrl", personProfileUrl + member.Person.Id.ToString() );
                            dictMember.Add( "Role", member.GroupRole.Name );
                            dictMember.Add( "NickName", member.Person.NickName );
                            dictMember.Add( "LastName", member.Person.LastName );
                            dictMember.Add( "PhotoUrl", member.Person.PhotoId.HasValue ? member.Person.PhotoUrl : string.Empty );
                            dictMember.Add( "PhotoId", member.Person.PhotoId );
                            dictMember.Add(
                                "ConnectionStatus",
                                member.Person.ConnectionStatusValue != null ? member.Person.ConnectionStatusValue.Value : string.Empty );
                            dictMember.Add( "Email", member.Person.Email );

                            var phoneTypes = new List<Dictionary<string, object>>();
                            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 );

                            members.Add( dictMember );
                        }

                        dynGroup.Members = members;

                        var groupDict = dynGroup as IDictionary<string, object>;
                        string result = System.Web.HttpUtility.HtmlDecode( infoWindowDetails.Template ).ResolveMergeFields( groupDict );

                        return new InfoWindowResult( result );
                    }

                    return new InfoWindowResult( infoWindow );
                }
                else
                {
                    throw new HttpResponseException( HttpStatusCode.Unauthorized );
                }
            }
            else
            {
                throw new HttpResponseException( HttpStatusCode.BadRequest );
            }
        }
    /// <summary>
    /// Builds a dictionary containing the content of the provided <see cref="System.ServiceModel.Syndication.SyndicationItem"/>
    /// </summary>
    /// <param name="i">The <see cref="System.ServiceModel.Syndicawtion.SyndicationItem"/> to be converted to a dictionary.</param>
    /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page.</param>
    /// <returns>A <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the provided syndication item.</returns>
    private static Dictionary<string, object> BuildSyndicationItem( SyndicationItem i, string detailPage )
    {
        Dictionary<string, object> itemDictionary = new Dictionary<string, object>();

        if ( i != null )
        {
            itemDictionary.Add( "AttributeExtensions", i.AttributeExtensions.ToDictionary( a => a.Key.ToString(), a => a.Value ) );

            string detailPageUrl = string.Empty;

            if ( !String.IsNullOrWhiteSpace( detailPage ) )
            {
                Rock.Model.Page page = new Rock.Model.PageService().Get( new Guid( detailPage ) );
                Dictionary<string, string> queryString = new Dictionary<string, string>();
                queryString.Add( "feedItemId", System.Web.HttpUtility.UrlEncode( i.Id ) );
                detailPageUrl = new PageReference( page.Id, 0, queryString ).BuildUrl();
            }

            List<Dictionary<string, object>> authors = new List<Dictionary<string, object>>();
            foreach ( var a in i.Authors )
            {
                authors.Add( BuildSyndicationPerson( a ) );
            }
            itemDictionary.Add( "Authors", authors );

            itemDictionary.Add( "BaseUri", i.BaseUri == null ? null : i.BaseUri.ToString() );

            List<Dictionary<string, object>> categories = new List<Dictionary<string, object>>();
            foreach ( var c in i.Categories )
            {
                categories.Add( BuildSyndicationCategory( c ) );
            }
            itemDictionary.Add( "Categories", categories );
            itemDictionary.Add( "Content", i.Content == null ? null : System.Web.HttpUtility.HtmlDecode( ( (TextSyndicationContent)i.Content ).Text ) );

            List<Dictionary<string, object>> contributors = new List<Dictionary<string, object>>();
            foreach ( var c in i.Contributors )
            {
                contributors.Add( BuildSyndicationPerson( c ) );
            }
            itemDictionary.Add( "Contributors", contributors );

            itemDictionary.Add( "Copyright", i.Copyright == null ? null : i.Copyright.Text );
            itemDictionary.Add( "DetailPageUrl", detailPageUrl );

            itemDictionary.Add( "ElementExtensions", i.ElementExtensions );
            itemDictionary.Add( "Id", i.Id );
            itemDictionary.Add( "LastUpdatedTime", i.LastUpdatedTime.ToLocalTime().DateTime );

            List<Dictionary<string, object>> link = new List<Dictionary<string, object>>();
            foreach ( var l in i.Links )
            {
                link.Add( BuildSyndicationLink( l ) );
            }
            itemDictionary.Add( "Links", link );

            itemDictionary.Add( "PublishDate", i.PublishDate.ToLocalTime().DateTime );
            itemDictionary.Add( "Summary", i.Summary == null ? null : i.Summary.Text );
            itemDictionary.Add( "Title", i.Title == null ? null : i.Title.Text );
        }


        return itemDictionary;

    }
Exemple #11
0
        /// <summary>
        /// Shows the view.
        /// </summary>
        protected void ShowView()
        {
            var rockContext = new RockContext();

            int resultCount = Int32.Parse(GetAttributeValue("ResultCount"));
            int pageNumber  = 0;

            if (!String.IsNullOrEmpty(PageParameter("page")))
            {
                pageNumber = Int32.Parse(PageParameter("page"));
            }

            var skipCount = pageNumber * resultCount;

            var query = new NcoaHistoryService(rockContext).Queryable();

            var processed = gfNcoaFilter.GetUserPreference("Processed").ConvertToEnumOrNull <Processed>();

            if (processed.HasValue)
            {
                if (processed.Value != Processed.All && processed.Value != Processed.ManualUpdateRequiredOrNotProcessed)
                {
                    query = query.Where(i => i.Processed == processed);
                }
                else if (processed.Value == Processed.ManualUpdateRequiredOrNotProcessed)
                {
                    query = query.Where(i => i.Processed == Processed.ManualUpdateRequired || i.Processed == Processed.NotProcessed);
                }
            }

            var moveDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(gfNcoaFilter.GetUserPreference("Move Date"));

            if (moveDateRange.Start.HasValue)
            {
                query = query.Where(e => e.MoveDate.HasValue && e.MoveDate.Value >= moveDateRange.Start.Value);
            }
            if (moveDateRange.End.HasValue)
            {
                query = query.Where(e => e.MoveDate.HasValue && e.MoveDate.Value < moveDateRange.End.Value);
            }

            var ncoaDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(gfNcoaFilter.GetUserPreference("NCOA Processed Date"));

            if (ncoaDateRange.Start.HasValue)
            {
                query = query.Where(e => e.NcoaRunDateTime >= ncoaDateRange.Start.Value);
            }
            if (ncoaDateRange.End.HasValue)
            {
                query = query.Where(e => e.NcoaRunDateTime < ncoaDateRange.End.Value);
            }

            var moveType = gfNcoaFilter.GetUserPreference("Move Type").ConvertToEnumOrNull <MoveType>();

            if (moveType.HasValue)
            {
                query = query.Where(i => i.MoveType == moveType);
            }

            var addressStatus = gfNcoaFilter.GetUserPreference("Address Status").ConvertToEnumOrNull <AddressStatus>();

            if (addressStatus.HasValue)
            {
                query = query.Where(i => i.AddressStatus == addressStatus);
            }

            var addressInvalidReason = gfNcoaFilter.GetUserPreference("Address Invalid Reason").ConvertToEnumOrNull <AddressInvalidReason>();

            if (addressInvalidReason.HasValue)
            {
                query = query.Where(i => i.AddressInvalidReason == addressInvalidReason);
            }

            decimal?moveDistance = gfNcoaFilter.GetUserPreference("Move Distance").AsDecimalOrNull();

            if (moveDistance.HasValue)
            {
                query = query.Where(i => i.MoveDistance <= moveDistance.Value);
            }

            string lastName = gfNcoaFilter.GetUserPreference("Last Name");

            if (!string.IsNullOrWhiteSpace(lastName))
            {
                var personAliasQuery = new PersonAliasService(rockContext)
                                       .Queryable()
                                       .Where(p =>
                                              p.Person != null &&
                                              p.Person.LastName.Contains(lastName))
                                       .Select(p => p.Id);
                query = query.Where(i => personAliasQuery.Contains(i.PersonAliasId));
            }

            var campusId = gfNcoaFilter.GetUserPreference("Campus").AsIntegerOrNull();

            if (campusId.HasValue)
            {
                var familyGroupType  = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
                var personAliasQuery = new PersonAliasService(rockContext).Queryable().AsNoTracking();
                var campusQuery      = new GroupMemberService(rockContext)
                                       .Queryable().AsNoTracking()
                                       .Where(m =>
                                              m.Group.GroupTypeId == familyGroupType.Id &&
                                              m.Group.CampusId.HasValue &&
                                              m.Group.CampusId.Value == campusId.Value)
                                       .Select(m => m.PersonId)
                                       .Join(personAliasQuery, m => m, p => p.PersonId, (m, p) => p.Id);

                query = query.Where(i => campusQuery.Contains(i.PersonAliasId));
            }

            var filteredRecords = query.ToList();

            lTotal.Text = string.Format("Records: {0}", filteredRecords.Count());

            #region Grouping rows

            var ncoaRows = filteredRecords
                           .Where(a => a.MoveType != MoveType.Individual)
                           .GroupBy(a => new { a.FamilyId, a.MoveType, a.MoveDate })
                           .Select(a => new NcoaRow
            {
                Id = a.Select(b => b.Id).Max(),
                FamilyMemberPersonAliasIds = a.Select(b => b.PersonAliasId).ToList()
            }).ToList();

            var ncoaIndividualRows = filteredRecords
                                     .Where(a => a.MoveType == MoveType.Individual)
                                     .Select(a => new NcoaRow
            {
                Id = a.Id,
                IndividualPersonAliasId = a.PersonAliasId
            }).ToList();

            ncoaRows.AddRange(ncoaIndividualRows);

            #endregion

            var pagedNcoaRows = ncoaRows.OrderBy(a => a.Id).Skip(skipCount).Take(resultCount + 1).ToList();
            var familyMemberPersonAliasIds = pagedNcoaRows.SelectMany(r => r.FamilyMemberPersonAliasIds).ToList();
            var individualPersonAliasIds   = pagedNcoaRows.Select(r => r.IndividualPersonAliasId).ToList();

            var people = new PersonAliasService(rockContext)
                         .Queryable().AsNoTracking()
                         .Where(p =>
                                familyMemberPersonAliasIds.Contains(p.Id) ||
                                individualPersonAliasIds.Contains(p.Id))
                         .Select(p => new
            {
                PersonAliasId = p.Id,
                Person        = p.Person
            })
                         .ToList();

            foreach (var ncoaRow in pagedNcoaRows)
            {
                ncoaRow.FamilyMembers = people
                                        .Where(p => ncoaRow.FamilyMemberPersonAliasIds.Contains(p.PersonAliasId))
                                        .Select(p => p.Person)
                                        .ToList();

                ncoaRow.Individual = people
                                     .Where(p => p.PersonAliasId == ncoaRow.IndividualPersonAliasId)
                                     .Select(p => p.Person)
                                     .FirstOrDefault();

                var ncoaHistoryRecord = filteredRecords.Single(a => a.Id == ncoaRow.Id);

                ncoaRow.OriginalAddress = FormattedAddress(ncoaHistoryRecord.OriginalStreet1, ncoaHistoryRecord.OriginalStreet2,
                                                           ncoaHistoryRecord.OriginalCity, ncoaHistoryRecord.OriginalState, ncoaHistoryRecord.OriginalPostalCode)
                                          .ConvertCrLfToHtmlBr();
                ncoaRow.Status         = ncoaHistoryRecord.Processed == Processed.Complete ? "Processed" : "Not Processed";
                ncoaRow.StatusCssClass = ncoaHistoryRecord.Processed == Processed.Complete ? "label-success" : "label-default";
                ncoaRow.ShowButton     = false;

                var family = new GroupService(rockContext).Get(ncoaHistoryRecord.FamilyId);
                var person = ncoaRow.Individual ?? ncoaRow.FamilyMembers.First();
                if (family == null)
                {
                    family = person.GetFamily(rockContext);
                }

                var personService = new PersonService(rockContext);

                ncoaRow.FamilyName         = family.Name;
                ncoaRow.HeadOftheHousehold = personService.GetHeadOfHousehold(person, family);

                if (ncoaHistoryRecord.MoveType != MoveType.Individual)
                {
                    ncoaRow.FamilyMembers = personService.GetFamilyMembers(family, person.Id, true).Select(a => a.Person).ToList();
                }
                else
                {
                    ncoaRow.FamilyMembers = personService.GetFamilyMembers(family, person.Id, false).Select(a => a.Person).ToList();
                }

                if (ncoaHistoryRecord.AddressStatus == AddressStatus.Invalid)
                {
                    ncoaRow.TagLine         = "Invalid Address";
                    ncoaRow.TagLineCssClass = "label-warning";

                    if (ncoaHistoryRecord.Processed != Processed.Complete)
                    {
                        ncoaRow.CommandName = "MarkAddressAsPrevious";
                        ncoaRow.CommandText = "Mark Address As Previous";
                        ncoaRow.ShowButton  = true;
                    }
                }

                if (ncoaHistoryRecord.NcoaType == NcoaType.Month48Move)
                {
                    ncoaRow.TagLine         = "48 Month Move";
                    ncoaRow.TagLineCssClass = "label-info";

                    if (ncoaHistoryRecord.Processed != Processed.Complete)
                    {
                        ncoaRow.CommandName = "MarkAddressAsPrevious";
                        ncoaRow.CommandText = "Mark Address As Previous";
                        ncoaRow.ShowButton  = true;
                    }
                }

                if (ncoaHistoryRecord.NcoaType == NcoaType.Move)
                {
                    ncoaRow.TagLine         = ncoaHistoryRecord.MoveType.ConvertToString();
                    ncoaRow.TagLineCssClass = "label-success";
                    ncoaRow.MoveDate        = ncoaHistoryRecord.MoveDate;
                    ncoaRow.MoveDistance    = ncoaHistoryRecord.MoveDistance;
                    ncoaRow.NewAddress      = FormattedAddress(ncoaHistoryRecord.UpdatedStreet1, ncoaHistoryRecord.UpdatedStreet2,
                                                               ncoaHistoryRecord.UpdatedCity, ncoaHistoryRecord.UpdatedState, ncoaHistoryRecord.UpdatedPostalCode)
                                              .ConvertCrLfToHtmlBr();
                    if (ncoaHistoryRecord.Processed != Processed.Complete)
                    {
                        ncoaRow.CommandText = "Mark Processed";
                        ncoaRow.CommandName = "MarkProcessed";
                        ncoaRow.ShowButton  = true;
                    }
                }
            }

            rptNcoaResultsFamily.DataSource = pagedNcoaRows.Take(resultCount).GroupBy(n => n.FamilyName);
            rptNcoaResultsFamily.DataBind();

            if (pagedNcoaRows.Count() > resultCount)
            {
                hlNext.Visible = hlNext.Enabled = true;
                Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                queryStringNext.Add("page", (pageNumber + 1).ToString());
                var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
            }
            else
            {
                hlNext.Visible = hlNext.Enabled = false;
            }

            // build prev button
            if (pageNumber == 0)
            {
                hlPrev.Visible = hlPrev.Enabled = false;
            }
            else
            {
                hlPrev.Visible = hlPrev.Enabled = true;
                Dictionary <string, string> queryStringPrev = new Dictionary <string, string>();
                queryStringPrev.Add("page", (pageNumber - 1).ToString());
                var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
            }
        }
Exemple #12
0
 /// <summary>
 /// Handles the Click event of the lbAddCheckinType control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
 protected void lbAddCheckinType_Click( object sender, EventArgs e )
 {
     var pageRef = new PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId );
     pageRef.Parameters.Add( "CheckinTypeId", "0" );
     NavigateToPage( pageRef );
 }
Exemple #13
0
 /// <summary>
 /// Handles the ItemCommand event of the rptCheckinTypes control.
 /// </summary>
 /// <param name="source">The source of the event.</param>
 /// <param name="e">The <see cref="RepeaterCommandEventArgs"/> instance containing the event data.</param>
 protected void rptCheckinTypes_ItemCommand( object source, RepeaterCommandEventArgs e )
 {
     int? groupTypeId = e.CommandArgument.ToString().AsIntegerOrNull();
     if ( groupTypeId.HasValue )
     {
         var pageRef = new PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId );
         pageRef.Parameters.Add( "CheckinTypeId", groupTypeId.Value.ToString() );
         NavigateToPage( pageRef );
     }
 }
Exemple #14
0
        /// <summary>
        /// Updates the list.
        /// </summary>
        private void UpdateList()
        {
            using ( var rockContext = new RockContext() )
            {
                var connectionType = new ConnectionTypeService( rockContext ).Get( GetAttributeValue( "ConnectionTypeId" ).AsInteger() );
                var qrySearch = connectionType.ConnectionOpportunities.ToList();

                if ( GetAttributeValue( "DisplayNameFilter" ).AsBoolean() )
                {
                    if ( !string.IsNullOrWhiteSpace( tbSearchName.Text ) )
                    {
                        var searchTerms = tbSearchName.Text.ToLower().SplitDelimitedValues( true );
                        qrySearch = qrySearch.Where( o => searchTerms.Any( t => t.Contains( o.Name.ToLower() ) || o.Name.ToLower().Contains( t ) ) ).ToList();
                    }
                }

                if ( GetAttributeValue( "DisplayCampusFilter" ).AsBoolean() )
                {
                    var searchCampuses = cblCampus.SelectedValuesAsInt;
                    if ( searchCampuses.Count > 0 )
                    {
                        qrySearch = qrySearch.Where( o => o.ConnectionOpportunityCampuses.Any( c => searchCampuses.Contains( c.CampusId ) ) ).ToList();
                    }
                }

                if ( GetAttributeValue( "DisplayAttributeFilters" ).AsBoolean() )
                {
                    // Filter query by any configured attribute filters
                    if ( AvailableAttributes != null && AvailableAttributes.Any() )
                    {
                        var attributeValueService = new AttributeValueService( rockContext );
                        var parameterExpression = attributeValueService.ParameterExpression;

                        foreach ( var attribute in AvailableAttributes )
                        {
                            var filterControl = phAttributeFilters.FindControl( "filter_" + attribute.Id.ToString() );
                            if ( filterControl != null )
                            {
                                var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter );
                                var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression );
                                if ( expression != null )
                                {
                                    var attributeValues = attributeValueService
                                        .Queryable()
                                        .Where( v => v.Attribute.Id == attribute.Id );

                                    attributeValues = attributeValues.Where( parameterExpression, expression, null );

                                    qrySearch = qrySearch.Where( o => attributeValues.Select( v => v.EntityId ).Contains( o.Id ) ).ToList();
                                }
                            }
                        }
                    }
                }

                var opportunitySummaries = new List<OpportunitySummary>();
                foreach ( var opportunity in qrySearch )
                {
                    opportunitySummaries.Add( new OpportunitySummary
                    {
                        IconCssClass = opportunity.IconCssClass,
                        Name = opportunity.PublicName,
                        PhotoUrl = opportunity.PhotoUrl,
                        Description = opportunity.Description.ScrubHtmlAndConvertCrLfToBr(),
                        Id = opportunity.Id
                    } );
                }

                var opportunities = opportunitySummaries
                    .OrderBy( e => e.Name )
                    .ToList();

                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "Opportunities", opportunities );
                mergeFields.Add( "CurrentPerson", CurrentPerson );

                var pageReference = new PageReference( GetAttributeValue( "DetailPage" ), null );
                mergeFields.Add( "DetailPage", pageReference.BuildUrl() );

                lOutput.Text = GetAttributeValue( "LavaTemplate" ).ResolveMergeFields( mergeFields );

                if ( GetAttributeValue( "SetPageTitle" ).AsBoolean() )
                {
                    string pageTitle = "Connection";
                    RockPage.PageTitle = pageTitle;
                    RockPage.BrowserTitle = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                    RockPage.Header.Title = String.Format( "{0} | {1}", pageTitle, RockPage.Site.Name );
                }

                // show debug info
                if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PageReference" /> class.
 /// </summary>
 /// <param name="pageReference">The page reference.</param>
 public PageReference(PageReference pageReference)
     : this(pageReference.PageId, pageReference.RouteId, pageReference.Parameters, pageReference.QueryString)
 {
 }
    /// <summary>
    /// Gets a <see cref="System.Collections.Generic.Dictionary{string,object}"/> representing the contents of the syndicated feed.
    /// </summary>
    /// <param name="feedUrl">A <see cref="System.String"/> representing the URL of the feed.</param>
    /// <param name="detailPage">A <see cref="System.String"/> representing the Guid of the detail page. </param>
    /// <param name="cacheDuration">A <see cref="System.Int32"/> representing the length of time that the content of the RSS feed will be saved to cache.</param>
    /// <param name="message">A <see cref="System.Collections.Generic.Dictionary{string,object}"/> that will contain any error or alert messages that are returned.</param>
    /// <param name="isError">A <see cref="System.Boolean"/> that is <c>true</c> if an error has occurred, otherwise <c>false</c>.</param>
    /// <returns></returns>
    public static Dictionary<string, object> GetFeed( string feedUrl, string detailPage, int cacheDuration, ref Dictionary<string, string> message, ref bool isError )
    {
        Dictionary<string, object> feedDictionary = new Dictionary<string, object>();

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

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

        ObjectCache feedCache = RockMemoryCache.Default;

        if ( feedCache[GetFeedCacheKey( feedUrl )] != null )
        {
            feedDictionary = (Dictionary<string, object>)feedCache[GetFeedCacheKey( feedUrl )];
        }
        else
        {
            XDocument feed = null;

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

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

                    feedReader.Close();

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

            if ( feed != null )
            {

                string detailPageBaseUrl = string.Empty;
                int detailPageID = 0;

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

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

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

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

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

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

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

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

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

                    foreach ( var article in articles )
                    {

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

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

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

                            idEntryHashed = sb.ToString();

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

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

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

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

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

                    }
                }

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

            if ( feedDictionary != null )
            {
                feedCache.Set( GetFeedCacheKey( feedUrl ), feedDictionary, DateTimeOffset.Now.AddMinutes( cacheDuration ) );
            }

        }

        return feedDictionary;
    }
        /// <summary>
        /// Gets the parent page references.
        /// </summary>
        /// <returns></returns>
        public static List <PageReference> GetParentPageReferences(RockPage rockPage, PageCache currentPage, PageReference currentPageReference)
        {
            // Get previous page references in nav history
            var pageReferenceHistory = HttpContext.Current.Session["RockPageReferenceHistory"] as List <PageReference>;

            // Current page heirarchy references
            var pageReferences = new List <PageReference>();

            if (currentPage != null)
            {
                var parentPage = currentPage.ParentPage;
                if (parentPage != null)
                {
                    var currentParentPages = parentPage.GetPageHierarchy();
                    if (currentParentPages != null && currentParentPages.Count > 0)
                    {
                        currentParentPages.Reverse();
                        foreach (PageCache page in currentParentPages)
                        {
                            PageReference parentPageReference = null;
                            if (pageReferenceHistory != null)
                            {
                                parentPageReference = pageReferenceHistory.Where(p => p.PageId == page.Id).FirstOrDefault();
                            }

                            if (parentPageReference == null)
                            {
                                parentPageReference        = new PageReference( );
                                parentPageReference.PageId = page.Id;

                                parentPageReference.BreadCrumbs = new List <BreadCrumb>();
                                parentPageReference.QueryString = new NameValueCollection();
                                parentPageReference.Parameters  = new Dictionary <string, string>();

                                string bcName = page.BreadCrumbText;
                                if (bcName != string.Empty)
                                {
                                    parentPageReference.BreadCrumbs.Add(new BreadCrumb(bcName, parentPageReference.BuildUrl()));
                                }

                                foreach (var block in page.Blocks.Where(b => b.BlockLocation == Model.BlockLocation.Page))
                                {
                                    try
                                    {
                                        System.Web.UI.Control control = rockPage.TemplateControl.LoadControl(block.BlockType.Path);
                                        if (control is RockBlock)
                                        {
                                            RockBlock rockBlock = control as RockBlock;
                                            rockBlock.SetBlock(page, block);
                                            rockBlock.GetBreadCrumbs(parentPageReference).ForEach(c => parentPageReference.BreadCrumbs.Add(c));
                                        }
                                        control = null;
                                    }
                                    catch (Exception ex)
                                    {
                                        ExceptionLogService.LogException(ex, HttpContext.Current, currentPage.Id, currentPage.Layout.SiteId);
                                    }
                                }
                            }

                            parentPageReference.BreadCrumbs.ForEach(c => c.Active = false);
                            pageReferences.Add(parentPageReference);
                        }
                    }
                }
            }

            return(pageReferences);
        }
Exemple #18
0
        /// <summary>
        /// Shows the summary.
        /// </summary>
        /// <param name="business">The business.</param>
        private void ShowSummary(int businessId)
        {
            SetEditMode(false);
            hfBusinessId.SetValue(businessId);
            lTitle.Text = "Business Details".FormatAsHtmlTitle();
            var rockContext = new RockContext();

            var business = new PersonService(rockContext).Get(businessId);

            if (business != null)
            {
                SetHeadingStatusInfo(business);
                lViewPanelBusinessName.Text = business.LastName;

                var detailsLeft  = new DescriptionList();
                var detailsRight = new DescriptionList();

                if (business.RecordStatusReasonValue != null)
                {
                    detailsLeft.Add("Record Status Reason", business.RecordStatusReasonValue);
                }

                // Get addresses
                var workLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK.AsGuid());
                if (workLocationType != null)
                {
                    if (business.GivingGroup != null)   // Giving Group is a shortcut to Family Group for business
                    {
                        var location = business.GivingGroup.GroupLocations
                                       .Where(gl => gl.GroupLocationTypeValueId == workLocationType.Id)
                                       .Select(gl => gl.Location)
                                       .FirstOrDefault();
                        if (location != null)
                        {
                            detailsLeft.Add("Address", location.GetFullStreetAddress().ConvertCrLfToHtmlBr());
                        }

                        // Get Previous Addresses
                        var previousLocations = new GroupLocationHistoricalService(rockContext)
                                                .Queryable()
                                                .Where(h => h.GroupId == business.GivingGroup.Id && h.GroupLocationTypeValueId == workLocationType.Id)
                                                .OrderBy(h => h.EffectiveDateTime)
                                                .Select(h => h.Location)
                                                .ToList();

                        foreach (var previouslocation in previousLocations)
                        {
                            detailsLeft.Add("Previous Address", previouslocation.GetFullStreetAddress().ConvertCrLfToHtmlBr());
                        }
                    }
                }

                var workPhoneType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid());
                if (workPhoneType != null)
                {
                    var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == workPhoneType.Id);
                    if (phoneNumber != null)
                    {
                        detailsRight.Add("Phone Number", phoneNumber.ToString());
                    }
                }

                var communicationLinkedPageValue = this.GetAttributeValue(AttributeKey.CommunicationPage);
                Rock.Web.PageReference communicationPageReference;
                if (communicationLinkedPageValue.IsNotNullOrWhiteSpace())
                {
                    communicationPageReference = new Rock.Web.PageReference(communicationLinkedPageValue);
                }
                else
                {
                    communicationPageReference = null;
                }

                detailsRight.Add("Email Address", business.GetEmailTag(ResolveRockUrl("/"), communicationPageReference));

                lDetailsLeft.Text  = detailsLeft.Html;
                lDetailsRight.Text = detailsRight.Html;

                ShowViewAttributes(business);
            }
        }