コード例 #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());
                }
            }
        }
コード例 #2
0
ファイル: PageMap.ascx.cs プロジェクト: SparkDevNetwork/Rock
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _pageId     = PageParameter(PageParameterKey.Page).AsIntegerOrNull();
            _pageSearch = PageParameter(PageParameterKey.PageSearch);

            var detailPageReference = new Rock.Web.PageReference(GetAttributeValue(AttributeKey.DetailPage));

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavior)
            if (detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId)
            {
                hfPageRouteTemplate.Value = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url;
                hfDetailPageUrl.Value     = new Rock.Web.PageReference(this.RockPage.PageId).BuildUrl();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Get(detailPageReference.PageId);
                if (pageCache != null)
                {
                    var route = pageCache.PageRoutes.FirstOrDefault(a => a.Id == detailPageReference.RouteId);
                    if (route != null)
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl();
            }

            InitializeSettingsNotification(upPanel);
        }
コード例 #3
0
        /// <summary>
        /// Executes the action.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var transactionId = GetAttributeValue(action, TRANSACTION_ID_KEY, true).AsIntegerOrNull();

            if (!action.CompletedDateTime.HasValue && transactionId.HasValue)
            {
                return(true);
            }

            if (action.Activity.Workflow.Guid != null && HttpContext.Current != null)
            {
                var workflowGuid = action.Activity.Workflow.Guid;
                var pageParams   = new Dictionary <string, string>();
                pageParams.Add("WorkflowGuid", workflowGuid.ToString());
                var transactionEntryPage = GetAttributeValue(action, TRANSACTION_ENTRY_PAGE_KEY, true);
                var pageReference        = new Rock.Web.PageReference(transactionEntryPage, pageParams);
                var url = pageReference.BuildUrl();
                if (!string.IsNullOrWhiteSpace(url))
                {
                    HttpContext.Current.Response.Redirect(url, false);
                }
            }
            else
            {
                errorMessages.Add("The current workflow is not persisted.");
            }

            return(false);
        }
コード例 #4
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _groupId = PageParameter("GroupId");

            var detailPageReference = new Rock.Web.PageReference(GetAttributeValue("DetailPage"));

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavoir)
            if (detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId)
            {
                hfPageRouteTemplate.Value = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url;
                hfDetailPageUrl.Value     = new Rock.Web.PageReference(this.RockPage.PageId).BuildUrl().RemoveLeadingForwardslash();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Read(detailPageReference.PageId);
                if (pageCache != null)
                {
                    var route = pageCache.PageRoutes.FirstOrDefault(a => a.Id == detailPageReference.RouteId);
                    if (route != null)
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl().RemoveLeadingForwardslash();
            }

            hfLimitToSecurityRoleGroups.Value = GetAttributeValue("LimittoSecurityRoleGroups");
            Guid?rootGroupGuid = GetAttributeValue("RootGroup").AsGuidOrNull();

            if (rootGroupGuid.HasValue)
            {
                var group = new GroupService(new RockContext()).Get(rootGroupGuid.Value);
                if (group != null)
                {
                    hfRootGroupId.Value = group.Id.ToString();
                }
            }

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upGroupType);

            tglHideInactiveGroups.Visible = this.GetAttributeValue("ShowFilterOption").AsBooleanOrNull() ?? true;
            if (tglHideInactiveGroups.Visible)
            {
                tglHideInactiveGroups.Checked = this.GetUserPreference("HideInactiveGroups").AsBooleanOrNull() ?? true;
            }
            else
            {
                // if the filter is hidden, don't show inactive groups
                tglHideInactiveGroups.Checked = true;
            }
        }
コード例 #5
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _accountId = PageParameter("AccountId");

            var detailPageReference = new Rock.Web.PageReference(GetAttributeValue("DetailPage"));

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavior)
            if (detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId)
            {
                hfPageRouteTemplate.Value = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url;
                hfDetailPageUrl.Value     = new Rock.Web.PageReference(this.RockPage.PageId).BuildUrl();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Get(detailPageReference.PageId);
                if (pageCache != null)
                {
                    var route = pageCache.PageRoutes.FirstOrDefault(a => a.Id == detailPageReference.RouteId);
                    if (route != null)
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl();
            }

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upAccountType);

            pnlConfigPanel.Visible    = this.GetAttributeValue("ShowFilterOption").AsBooleanOrNull() ?? false;
            pnlRolloverConfig.Visible = this.GetAttributeValue("ShowFilterOption").AsBooleanOrNull() ?? false;
            hfUsePublicName.Value     = this.GetAttributeValue("UsePublicName").AsBoolean(false).ToTrueFalse();

            if (pnlConfigPanel.Visible)
            {
                var hideInactiveAccounts = this.GetUserPreference("HideInactiveAccounts").AsBooleanOrNull();
                if (!hideInactiveAccounts.HasValue)
                {
                    hideInactiveAccounts = this.GetAttributeValue("InitialActiveSetting") == "1";
                }

                tglHideInactiveAccounts.Checked = hideInactiveAccounts ?? true;
            }
            else
            {
                // if the filter is hidden, don't show inactive accounts
                tglHideInactiveAccounts.Checked = true;
            }
        }
コード例 #6
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList(int componentId)
        {
            int pageSize = GetAttributeValue("PageSize").AsInteger();

            int skipCount = pageNumber * pageSize;

            using (var rockContext = new RockContext())
            {
                var component = new InteractionComponentService(rockContext).Get(componentId);
                if (component != null && (UserCanEdit || component.IsAuthorized(Authorization.VIEW, CurrentPerson)))
                {
                    var interactions = new InteractionService(rockContext)
                                       .Queryable().AsNoTracking()
                                       .Where(a =>
                                              a.InteractionComponentId == componentId)
                                       .OrderByDescending(a => a.InteractionDateTime)
                                       .Skip(skipCount)
                                       .Take(pageSize + 1);

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.AddOrIgnore("Person", CurrentPerson);
                    mergeFields.Add("InteractionDetailPage", LinkedPageRoute("InteractionDetailPage"));
                    mergeFields.Add("InteractionChannel", component.Channel);
                    mergeFields.Add("InteractionComponent", component);
                    mergeFields.Add("Interactions", interactions.ToList().Take(pageSize));

                    // set next button
                    if (interactions.Count() > pageSize)
                    {
                        Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                        queryStringNext.Add("ComponentId", componentId.ToString());
                        queryStringNext.Add("Page", (pageNumber + 1).ToString());

                        var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                        mergeFields.Add("NextPageNavigateUrl", pageReferenceNext.BuildUrl());
                    }

                    // set prev button
                    if (pageNumber != 0)
                    {
                        Dictionary <string, string> queryStringPrev = new Dictionary <string, string>();
                        queryStringPrev.Add("ComponentId", componentId.ToString());
                        queryStringPrev.Add("Page", (pageNumber - 1).ToString());

                        var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                        mergeFields.Add("PreviousPageNavigateUrl", pageReferencePrev.BuildUrl());
                    }

                    lContent.Text = component.Channel.InteractionListTemplate.IsNotNullOrWhitespace() ?
                                    component.Channel.InteractionListTemplate.ResolveMergeFields(mergeFields) :
                                    GetAttributeValue("DefaultTemplate").ResolveMergeFields(mergeFields);
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            int pageSize = GetAttributeValue("PageSize").AsInteger();

            int skipCount = pageNumber * pageSize;

            using (var rockContext = new RockContext())
            {
                var interactionChannel = new InteractionChannelService(rockContext).Get(_channelId.Value);
                if (interactionChannel != null)
                {
                    var interactionComponentQry = new InteractionComponentService(rockContext)
                                                  .Queryable().AsNoTracking()
                                                  .Where(a =>
                                                         a.ChannelId == _channelId.Value)
                                                  .OrderByDescending(a => a.ModifiedDateTime)
                                                  .Skip(skipCount)
                                                  .Take(pageSize + 1);

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.Add("ComponentDetailPage", LinkedPageRoute("ComponentDetailPage"));
                    mergeFields.Add("InteractionDetailPage", LinkedPageRoute("InteractionDetailPage"));
                    mergeFields.Add("InteractionChannel", interactionChannel);
                    mergeFields.Add("InteractionComponents", interactionComponentQry.ToList().Take(pageSize));

                    // set next button
                    if (interactionComponentQry.Count() > pageSize)
                    {
                        Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                        queryStringNext.Add("ChannelId", _channelId.ToString());
                        queryStringNext.Add("Page", (pageNumber + 1).ToString());

                        var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                        mergeFields.Add("NextPageNavigateUrl", pageReferenceNext.BuildUrl());
                    }

                    // set prev button
                    if (pageNumber != 0)
                    {
                        Dictionary <string, string> queryStringPrev = new Dictionary <string, string>();
                        queryStringPrev.Add("ChannelId", _channelId.ToString());
                        queryStringPrev.Add("Page", (pageNumber - 1).ToString());

                        var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                        mergeFields.Add("PreviousPageNavigateUrl", pageReferencePrev.BuildUrl());
                    }

                    lContent.Text = interactionChannel.ComponentListTemplate.IsNotNullOrWhitespace() ?
                                    interactionChannel.ComponentListTemplate.ResolveMergeFields(mergeFields) :
                                    GetAttributeValue("DefaultTemplate").ResolveMergeFields(mergeFields);
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Builds and returns the URL for a linked <see cref="Rock.Model.Page"/>
        /// from a <see cref="Rock.Attribute.LinkedPageAttribute"/> and any necessary
        /// query parameters.
        /// </summary>
        /// <param name="block">The block to get instance data from.</param>
        /// <param name="attributeKey">The attribute key that contains the linked page value.</param>
        /// <param name="queryParams">Any query string parameters that should be included in the built URL.</param>
        /// <returns>A string representing the URL to the linked <see cref="Rock.Model.Page"/>.</returns>
        public static string GetLinkedPageUrl(this RockBlockType block, string attributeKey, IDictionary <string, string> queryParams = null)
        {
            var pageReference = new Rock.Web.PageReference(block.GetAttributeValue(attributeKey), queryParams != null ? new Dictionary <string, string>(queryParams) : null);

            if (pageReference.PageId > 0)
            {
                return(pageReference.BuildUrl());
            }
            else
            {
                return(string.Empty);
            }
        }
コード例 #9
0
        /// <summary>
        /// Builds and returns the URL for the current <see cref="Rock.Model.Page"/>
        /// and any necessary query parameters.
        /// </summary>
        /// <param name="block">The block to get instance data from.</param>
        /// <param name="queryParams">Any query string parameters that should be included in the built URL.</param>
        /// <returns>A string representing the URL to the current <see cref="Rock.Model.Page"/>.</returns>
        public static string GetCurrentPageUrl(this RockBlockType block, IDictionary <string, string> queryParams = null)
        {
            var pageReference = new Rock.Web.PageReference(block.PageCache.Guid.ToString(), queryParams != null ? new Dictionary <string, string>(queryParams) : null);

            if (pageReference.PageId > 0)
            {
                return(pageReference.BuildUrl());
            }
            else
            {
                return(string.Empty);
            }
        }
コード例 #10
0
        /// <summary>
        /// Adds or updates the given person into the given group.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="group">The group.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddOrUpdatePersonInGroup(Person person, Group group, RockContext rockContext)
        {
            try
            {
                var groupMember = group.Members.Where(m => m.PersonId == person.Id).FirstOrDefault();
                if (groupMember == null)
                {
                    groupMember             = new GroupMember();
                    groupMember.GroupId     = group.Id;
                    groupMember.PersonId    = person.Id;
                    groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId ?? 0;
                    group.Members.Add(groupMember);
                }
                var groupMemberStatus = GetAttributeValue("GroupMemberStatus");
                groupMember.GroupMemberStatus = (GroupMemberStatus)groupMemberStatus.AsInteger();
                rockContext.SaveChanges();

                // Now update any member attributes for the person...
                AddOrUpdateGroupMemberAttributes(person, group, rockContext);

                string successPage = GetAttributeValue("SuccessPage");
                if (!string.IsNullOrWhiteSpace(successPage))
                {
                    var pageReference = new Rock.Web.PageReference(successPage);
                    Response.Redirect(pageReference.BuildUrl(), false);
                    // this remaining stuff prevents .NET from quietly throwing ThreadAbortException
                    Context.ApplicationInstance.CompleteRequest();
                    return;
                }
                else
                {
                    lSuccess.Visible = true;
                    lSuccess.Text    = GetAttributeValue("SuccessMessage");
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                nbMessage.Visible             = true;
                nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbMessage.Text = "Something went wrong and we could not save your request. If it happens again please contact our office at the number below.";
            }
        }
コード例 #11
0
        public void RaisePostBackEvent(string eventArgument)
        {
            if (_batch != null)
            {
                if (eventArgument == "MoveTransactions" &&
                    _ddlMove != null &&
                    _ddlMove.SelectedValue != null &&
                    !String.IsNullOrWhiteSpace(_ddlMove.SelectedValue))
                {
                    var txnsSelected = new List <int>();

                    gTransactions.SelectedKeys.ToList().ForEach(b => txnsSelected.Add(b.ToString().AsInteger()));

                    if (txnsSelected.Any())
                    {
                        var rockContext  = new RockContext();
                        var batchService = new FinancialBatchService(rockContext);

                        var newBatch = batchService.Get(_ddlMove.SelectedValue.AsInteger());
                        var oldBatch = batchService.Get(_batch.Id);

                        if (oldBatch != null && newBatch != null && newBatch.Status == BatchStatus.Open)
                        {
                            var txnService   = new FinancialTransactionService(rockContext);
                            var txnsToUpdate = txnService.Queryable("AuthorizedPersonAlias.Person")
                                               .Where(t => txnsSelected.Contains(t.Id))
                                               .ToList();

                            decimal oldBatchControlAmount = oldBatch.ControlAmount;
                            decimal newBatchControlAmount = newBatch.ControlAmount;

                            foreach (var txn in txnsToUpdate)
                            {
                                string caption = (txn.AuthorizedPersonAlias != null && txn.AuthorizedPersonAlias.Person != null) ?
                                                 txn.AuthorizedPersonAlias.Person.FullName :
                                                 string.Format("Transaction: {0}", txn.Id);

                                var changes = new List <string>();
                                History.EvaluateChange(changes, "Batch",
                                                       string.Format("{0} (Id:{1})", oldBatch.Name, oldBatch.Id),
                                                       string.Format("{0} (Id:{1})", newBatch.Name, newBatch.Id));

                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof(FinancialBatch),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    oldBatch.Id,
                                    changes,
                                    caption,
                                    typeof(FinancialTransaction),
                                    txn.Id,
                                    false
                                    );

                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof(FinancialBatch),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    newBatch.Id,
                                    changes,
                                    caption,
                                    typeof(FinancialTransaction),
                                    txn.Id, false
                                    );

                                txn.BatchId            = newBatch.Id;
                                oldBatchControlAmount -= txn.TotalAmount;
                                newBatchControlAmount += txn.TotalAmount;
                            }

                            var oldBatchChanges = new List <string>();
                            History.EvaluateChange(oldBatchChanges, "Control Amount", oldBatch.ControlAmount.FormatAsCurrency(), oldBatchControlAmount.FormatAsCurrency());
                            oldBatch.ControlAmount = oldBatchControlAmount;

                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                oldBatch.Id,
                                oldBatchChanges,
                                false
                                );

                            var newBatchChanges = new List <string>();
                            History.EvaluateChange(newBatchChanges, "Control Amount", newBatch.ControlAmount.FormatAsCurrency(), newBatchControlAmount.FormatAsCurrency());
                            newBatch.ControlAmount = newBatchControlAmount;

                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                newBatch.Id,
                                newBatchChanges,
                                false
                                );

                            rockContext.SaveChanges();

                            var pageRef = new Rock.Web.PageReference(RockPage.PageId);
                            pageRef.Parameters = new Dictionary <string, string>();
                            pageRef.Parameters.Add("batchid", newBatch.Id.ToString());
                            string newBatchLink = string.Format("<a href='{0}'>{1}</a>",
                                                                pageRef.BuildUrl(), newBatch.Name);

                            RockPage.UpdateBlocks("~/Blocks/Finance/BatchDetail.ascx");

                            nbResult.Text = string.Format("{0} transactions were moved to the '{1}' batch.",
                                                          txnsToUpdate.Count().ToString("N0"), newBatchLink);
                            nbResult.NotificationBoxType = NotificationBoxType.Success;
                            nbResult.Visible             = true;
                        }
                        else
                        {
                            nbResult.Text = string.Format("The selected batch does not exist, or is no longer open.");
                            nbResult.NotificationBoxType = NotificationBoxType.Danger;
                            nbResult.Visible             = true;
                        }
                    }
                    else
                    {
                        nbResult.Text = string.Format("There were not any transactions selected.");
                        nbResult.NotificationBoxType = NotificationBoxType.Warning;
                        nbResult.Visible             = true;
                    }
                }

                _ddlMove.SelectedIndex = 0;
            }

            BindGrid();
        }
コード例 #12
0
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void ShowActiveUsers()
        {
            int? siteId = GetAttributeValue( "Site" ).AsIntegerOrNull();
            if (!siteId.HasValue)
            {
                lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>";
                return;
            }
            else
            {
                int? pageViewCount = GetAttributeValue( "PageViewCount" ).AsIntegerOrNull();
                if ( !pageViewCount.HasValue || pageViewCount.Value == 0 )
                {
                    pageViewCount = 1;
                }

                StringBuilder sbUsers = new StringBuilder();

                var site = SiteCache.Read( siteId.Value );
                lSiteName.Text = "<h4>" + site.Name + "</h4>";
                lSiteName.Visible = GetAttributeValue( "ShowSiteNameAsTitle" ).AsBoolean();

                lMessages.Text = string.Empty;

                using ( var rockContext = new RockContext() )
                {
                    IQueryable<PageView> pageViewQry = new PageViewService( rockContext ).Queryable( "Page" );

                    // Query to get who is logged in and last visit was to selected site
                    var activeLogins = new UserLoginService( rockContext ).Queryable( "Person" )
                        .Where( l =>
                            l.PersonId.HasValue &&
                            l.IsOnLine == true )
                        .OrderByDescending( l => l.LastActivityDateTime )
                        .Select( l => new
                        {
                            login = l,
                            pageViews = pageViewQry
                                .Where( v => v.PersonAlias.PersonId == l.PersonId )
                                .OrderByDescending( v => v.DateTimeViewed )
                                .Take( pageViewCount.Value )
                        } )
                        .Where( a =>
                            a.pageViews.Any() &&
                            a.pageViews.FirstOrDefault().SiteId == site.Id );

                    if ( CurrentUser != null )
                    {
                        activeLogins = activeLogins.Where( m => m.login.UserName != CurrentUser.UserName );
                    }

                    foreach ( var activeLogin in activeLogins )
                    {
                        var login = activeLogin.login;
                        var pageViews = activeLogin.pageViews.ToList();
                        Guid? latestSession = pageViews.FirstOrDefault().SessionId;

                        string pageViewsHtml = activeLogin.pageViews.ToList()
                                                .Where( v => v.SessionId == latestSession )
                                                .Select( v => HttpUtility.HtmlEncode( v.Page.PageTitle ) ).ToList().AsDelimited( "<br> " );

                        TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract( login.LastActivityDateTime.Value ) : TimeSpan.MaxValue;
                        string className = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent";

                        // create link to the person
                        string personLink = login.Person.FullName;

                        if ( GetAttributeValue( "PersonProfilePage" ) != null )
                        {
                            string personProfilePage = GetAttributeValue( "PersonProfilePage" );
                            var pageParams = new Dictionary<string, string>();
                            pageParams.Add( "PersonId", login.Person.Id.ToString() );
                            var pageReference = new Rock.Web.PageReference( personProfilePage, pageParams );
                            personLink = string.Format( @"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), login.Person.FullName );
                        }

                        // determine whether to show last page views
                        if ( GetAttributeValue( "PageViewCount" ).AsInteger() > 0 )
                        {
                            string format = @"
            <li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";

                            sbUsers.Append( string.Format( format, className, personLink, pageViewsHtml ) );
                        }
                        else
                        {
                            string format = @"
            <li class='active-user {0}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            sbUsers.Append( string.Format( format, className, personLink ) );
                        }
                    }
                }

                if ( sbUsers.Length > 0 )
                {
                    lUsers.Text = string.Format( @"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString() );
                }
                else
                {
                    lMessages.Text = string.Format( "There are no logged in users on the {0} site.", site.Name );
                }
            }
        }
コード例 #13
0
 protected void btnCancel_Click( object sender, EventArgs e )
 {
     if ( _editingApproved )
     {
         var communicationService = new CommunicationService( new RockContext() );
         var communication = communicationService.Get( CommunicationId.Value );
         if ( communication != null && communication.Status == CommunicationStatus.PendingApproval )
         {
             // Redirect back to same page without the edit param
             var pageRef = new Rock.Web.PageReference();
             pageRef.PageId = CurrentPageReference.PageId;
             pageRef.RouteId = CurrentPageReference.RouteId;
             pageRef.Parameters = new Dictionary<string, string>();
             pageRef.Parameters.Add("CommunicationId", communication.Id.ToString());
             Response.Redirect( pageRef.BuildUrl() );
             Context.ApplicationInstance.CompleteRequest();
         }
     }
 }
コード例 #14
0
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void ShowActiveUsers()
        {
            int?siteId = GetAttributeValue("Site").AsIntegerOrNull();

            if (!siteId.HasValue || SiteCache.Get(siteId.Value) == null)
            {
                lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>";
                return;
            }
            else
            {
                int pageViewCount = GetAttributeValue("PageViewCount").AsIntegerOrNull() ?? 0;

                StringBuilder sbUsers = new StringBuilder();

                var site = SiteCache.Get(siteId.Value);
                lSiteName.Text    = "<h4>" + site.Name + "</h4>";
                lSiteName.Visible = GetAttributeValue("ShowSiteNameAsTitle").AsBoolean();

                if (!site.EnablePageViews)
                {
                    lMessages.Text = "<div class='alert alert-warning'>Active " + site.Name + " users not available because page views are not enabled for site.</div>";
                    return;
                }

                lMessages.Text = string.Empty;
                string guestVisitorsStr = string.Empty;

                using (var rockContext = new RockContext())
                {
                    var qryPageViews = new InteractionService(rockContext).Queryable();

                    var qryPersonAlias = new PersonAliasService(rockContext).Queryable();
                    var pageViewQry    = qryPageViews.Join(
                        qryPersonAlias,
                        pv => pv.PersonAliasId,
                        pa => pa.Id,
                        (pv, pa) =>
                        new
                    {
                        PersonAliasPersonId = pa.PersonId,
                        pv.InteractionDateTime,
                        pv.InteractionComponent.Channel.ChannelEntityId,
                        pv.InteractionSessionId,
                        PagePageTitle = pv.InteractionComponent.Name
                    });

                    var last24Hours = RockDateTime.Now.AddDays(-1);

                    int pageViewTakeCount = pageViewCount;
                    if (pageViewTakeCount == 0)
                    {
                        pageViewTakeCount = 1;
                    }

                    // Query to get who is logged in and last visit was to selected site
                    var activeLogins = new UserLoginService(rockContext).Queryable()
                                       .Where(l =>
                                              l.PersonId.HasValue &&
                                              l.IsOnLine == true)
                                       .OrderByDescending(l => l.LastActivityDateTime)
                                       .Select(l => new
                    {
                        login = new
                        {
                            l.UserName,
                            l.LastActivityDateTime,
                            l.PersonId,
                            Person = new
                            {
                                l.Person.NickName,
                                l.Person.LastName,
                                l.Person.SuffixValueId
                            }
                        },
                        pageViews = pageViewQry
                                    .Where(v => v.PersonAliasPersonId == l.PersonId)
                                    .Where(v => v.InteractionDateTime > last24Hours)
                                    .OrderByDescending(v => v.InteractionDateTime)
                                    .Take(pageViewTakeCount)
                    })
                                       .Select(a => new
                    {
                        a.login,
                        pageViews = a.pageViews.ToList()
                    });

                    if (CurrentUser != null)
                    {
                        activeLogins = activeLogins.Where(m => m.login.UserName != CurrentUser.UserName);
                    }

                    foreach (var activeLogin in activeLogins)
                    {
                        var login = activeLogin.login;

                        if (!activeLogin.pageViews.Any() || activeLogin.pageViews.FirstOrDefault().ChannelEntityId != site.Id)
                        {
                            // only show active logins with PageViews and the most recent pageview is for the specified site
                            continue;
                        }

                        var latestPageViewSessionId = activeLogin.pageViews.FirstOrDefault().InteractionSessionId;

                        TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract(login.LastActivityDateTime.Value) : TimeSpan.MaxValue;
                        string   className      = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent";

                        // create link to the person
                        string personFullName = Person.FormatFullName(login.Person.NickName, login.Person.LastName, login.Person.SuffixValueId);
                        string personLink     = personFullName;

                        if (GetAttributeValue("PersonProfilePage") != null)
                        {
                            string personProfilePage = GetAttributeValue("PersonProfilePage");
                            var    pageParams        = new Dictionary <string, string>();
                            pageParams.Add("PersonId", login.PersonId.ToString());
                            var pageReference = new Rock.Web.PageReference(personProfilePage, pageParams);
                            personLink = string.Format(@"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), personFullName);
                        }

                        // determine whether to show last page views
                        if (GetAttributeValue("PageViewCount").AsInteger() > 0)
                        {
                            string activeLoginFormat = @"
<li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'>
    <i class='fa-li fa fa-circle'></i> {1}
</li>";
                            // define the formatting for each user entry
                            if (activeLogin.pageViews != null)
                            {
                                string pageViewsHtml = activeLogin.pageViews
                                                       .Where(v => v.InteractionSessionId == latestPageViewSessionId)
                                                       .Select(v => HttpUtility.HtmlEncode(v.PagePageTitle)).ToList().AsDelimited("<br> ");

                                sbUsers.Append(string.Format(activeLoginFormat, className, personLink, pageViewsHtml));
                            }
                        }
                        else
                        {
                            string inactiveLoginFormat = @"
<li class='active-user {0}'>
    <i class='fa-li fa fa-circle'></i> {1}
</li>";
                            sbUsers.Append(string.Format(inactiveLoginFormat, className, personLink));
                        }
                    }

                    // get the 'show guests' attribute and if it's true, determine how many guests there are.
                    bool showGuestVisitors = GetAttributeValue("ShowGuestVisitors").AsBoolean();
                    if (showGuestVisitors)
                    {
                        // build a list of unique sessions views in the past 15 minutes.
                        // We'll only take entries with a null personAliasID, which means they're not logged in,
                        // and thus ARE guests.
                        var last5Minutes  = RockDateTime.Now.AddMinutes(-5);
                        var last15Minutes = RockDateTime.Now.AddMinutes(-15);

                        var qryGuests = new InteractionService(rockContext).Queryable().AsNoTracking()
                                        .Where(
                            i => i.InteractionComponent.Channel.ChannelEntityId == site.Id &&
                            i.InteractionDateTime > last15Minutes &&
                            i.PersonAliasId == null &&
                            i.InteractionSession.DeviceType.ClientType != "Other" &&
                            i.InteractionSession.DeviceType.ClientType != "Crawler")
                                        .GroupBy(i => i.InteractionSessionId)
                                        .Select(g => new
                        {
                            SessionId = g.Key,
                            LastVisit = g.Max(i => i.InteractionDateTime)
                        })
                                        .ToList();

                        var numRecentGuests   = qryGuests.Where(g => g.LastVisit >= last5Minutes).Count();
                        var numInactiveGuests = qryGuests.Where(g => g.LastVisit < last5Minutes).Count();

                        // now build the formatted entry, which is "Current Guests (0) (1)" where the first is a green badge, and the second yellow.
                        if (numRecentGuests > 0 || numInactiveGuests > 0)
                        {
                            guestVisitorsStr = "Current Guests:";
                            if (numRecentGuests > 0)
                            {
                                guestVisitorsStr += string.Format(" <span class=\"badge badge-success\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Users active in the past 5 minutes.\">{0}</span>", numRecentGuests);
                            }

                            if (numInactiveGuests > 0)
                            {
                                guestVisitorsStr += string.Format(" <span class=\"badge badge-warning\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"Users active in the past 15 minutes.\">{0}</span>", numInactiveGuests);
                            }
                        }
                    }
                }

                if (sbUsers.Length > 0)
                {
                    lUsers.Text  = string.Format(@"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString());
                    lUsers.Text += string.Format(@"<p class='margin-l-sm js-current-guests'>{0}</p>", guestVisitorsStr);
                }
                else
                {
                    lMessages.Text  = string.Format("There are no logged in users on the {0} site.", site.Name);
                    lMessages.Text += "<br /><br />" + guestVisitorsStr;
                }
            }
        }
コード例 #15
0
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void ShowActiveUsers()
        {
            int?siteId = GetAttributeValue("Site").AsIntegerOrNull();

            if (!siteId.HasValue)
            {
                lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>";
                return;
            }
            else
            {
                int pageViewCount = GetAttributeValue("PageViewCount").AsIntegerOrNull() ?? 0;

                StringBuilder sbUsers = new StringBuilder();

                var site = SiteCache.Read(siteId.Value);
                lSiteName.Text    = "<h4>" + site.Name + "</h4>";
                lSiteName.Visible = GetAttributeValue("ShowSiteNameAsTitle").AsBoolean();

                lMessages.Text = string.Empty;

                using (var rockContext = new RockContext())
                {
                    var qryPageViews   = new PageViewService(rockContext).Queryable();
                    var qryPersonAlias = new PersonAliasService(rockContext).Queryable();
                    var pageViewQry    = qryPageViews.Join(
                        qryPersonAlias,
                        pv => pv.PersonAliasId,
                        pa => pa.Id,
                        (pv, pa) =>
                        new
                    {
                        PersonAliasPersonId = pa.PersonId,
                        pv.DateTimeViewed,
                        pv.SiteId,
                        pv.SessionId,
                        PagePageTitle = pv.Page.PageTitle
                    });

                    var last24Hours = RockDateTime.Now.AddDays(-1);

                    int pageViewTakeCount = pageViewCount;
                    if (pageViewTakeCount == 0)
                    {
                        pageViewTakeCount = 1;
                    }

                    // Query to get who is logged in and last visit was to selected site
                    var activeLogins = new UserLoginService(rockContext).Queryable("Person")
                                       .Where(l =>
                                              l.PersonId.HasValue &&
                                              l.IsOnLine == true)
                                       .OrderByDescending(l => l.LastActivityDateTime)
                                       .Select(l => new
                    {
                        login     = l,
                        pageViews = pageViewQry
                                    .Where(v => v.PersonAliasPersonId == l.PersonId)
                                    .Where(v => v.DateTimeViewed > last24Hours)
                                    .OrderByDescending(v => v.DateTimeViewed)
                                    .Take(pageViewTakeCount)
                    })
                                       .Where(a =>
                                              a.pageViews.Any() &&
                                              a.pageViews.FirstOrDefault().SiteId == site.Id)
                                       .Select(a => new
                    {
                        a.login,
                        pageViews       = a.pageViews,
                        LatestSessionId = a.pageViews.FirstOrDefault().SessionId
                    });

                    if (CurrentUser != null)
                    {
                        activeLogins = activeLogins.Where(m => m.login.UserName != CurrentUser.UserName);
                    }

                    foreach (var activeLogin in activeLogins)
                    {
                        var login = activeLogin.login;

                        Guid?latestSession = activeLogin.LatestSessionId;


                        TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract(login.LastActivityDateTime.Value) : TimeSpan.MaxValue;
                        string   className      = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent";

                        // create link to the person
                        string personLink = login.Person.FullName;

                        if (GetAttributeValue("PersonProfilePage") != null)
                        {
                            string personProfilePage = GetAttributeValue("PersonProfilePage");
                            var    pageParams        = new Dictionary <string, string>();
                            pageParams.Add("PersonId", login.Person.Id.ToString());
                            var pageReference = new Rock.Web.PageReference(personProfilePage, pageParams);
                            personLink = string.Format(@"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), login.Person.FullName);
                        }

                        // determine whether to show last page views
                        if (GetAttributeValue("PageViewCount").AsInteger() > 0)
                        {
                            string format = @"
<li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'>
    <i class='fa-li fa fa-circle'></i> {1}
</li>";
                            if (activeLogin.pageViews != null)
                            {
                                var    pageViews     = activeLogin.pageViews.ToList();
                                string pageViewsHtml = activeLogin.pageViews.ToList()
                                                       .Where(v => v.SessionId == latestSession)
                                                       .Select(v => HttpUtility.HtmlEncode(v.PagePageTitle)).ToList().AsDelimited("<br> ");


                                sbUsers.Append(string.Format(format, className, personLink, pageViewsHtml));
                            }
                        }
                        else
                        {
                            string format = @"
<li class='active-user {0}'>
    <i class='fa-li fa fa-circle'></i> {1}
</li>";
                            sbUsers.Append(string.Format(format, className, personLink));
                        }
                    }
                }

                if (sbUsers.Length > 0)
                {
                    lUsers.Text = string.Format(@"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString());
                }
                else
                {
                    lMessages.Text = string.Format("There are no logged in users on the {0} site.", site.Name);
                }
            }
        }
コード例 #16
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            _groupId = PageParameter( "GroupId" );

            var detailPageReference = new Rock.Web.PageReference( GetAttributeValue( "DetailPage" ) );

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavoir)
            if ( detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId )
            {
                hfPageRouteTemplate.Value = ( this.RockPage.RouteData.Route as System.Web.Routing.Route ).Url;
                hfDetailPageUrl.Value = new Rock.Web.PageReference( this.RockPage.PageId ).BuildUrl().RemoveLeadingForwardslash();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Read( detailPageReference.PageId );
                if ( pageCache != null )
                {
                    var route = pageCache.PageRoutes.FirstOrDefault( a => a.Id == detailPageReference.RouteId );
                    if ( route != null )
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl().RemoveLeadingForwardslash();
            }

            hfLimitToSecurityRoleGroups.Value = GetAttributeValue( "LimittoSecurityRoleGroups" );
            Guid? rootGroupGuid = GetAttributeValue( "RootGroup" ).AsGuidOrNull();
            if ( rootGroupGuid.HasValue )
            {
                var group = new GroupService( new RockContext() ).Get( rootGroupGuid.Value );
                if ( group != null )
                {
                    hfRootGroupId.Value = group.Id.ToString();
                }
            }

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger( upGroupType );

            pnlConfigPanel.Visible = this.GetAttributeValue( "ShowFilterOption" ).AsBooleanOrNull() ?? false;
            pnlRolloverConfig.Visible = this.GetAttributeValue( "ShowFilterOption" ).AsBooleanOrNull() ?? false;

            if ( pnlConfigPanel.Visible )
            {
                var hideInactiveGroups = this.GetUserPreference( "HideInactiveGroups" ).AsBooleanOrNull();
                if ( !hideInactiveGroups.HasValue )
                {
                    hideInactiveGroups = this.GetAttributeValue( "InitialActiveSetting" ) == "1";
                }

                tglHideInactiveGroups.Checked = hideInactiveGroups ?? true;
            }
            else
            {
                // if the filter is hidden, don't show inactive groups
                tglHideInactiveGroups.Checked = true;
            }

            ddlCountsType.Items.Clear();
            ddlCountsType.Items.Add( new ListItem( string.Empty, TreeViewItem.GetCountsType.None.ConvertToInt().ToString() ) );
            ddlCountsType.Items.Add( new ListItem( TreeViewItem.GetCountsType.ChildGroups.ConvertToString(), TreeViewItem.GetCountsType.ChildGroups.ConvertToInt().ToString() ) );
            ddlCountsType.Items.Add( new ListItem( TreeViewItem.GetCountsType.GroupMembers.ConvertToString(), TreeViewItem.GetCountsType.GroupMembers.ConvertToInt().ToString() ) );

            var countsType = this.GetUserPreference( "CountsType" );
            if ( string.IsNullOrEmpty( countsType ) )
            {
                countsType = this.GetAttributeValue( "InitialCountSetting" );
            }

            if ( pnlConfigPanel.Visible )
            {
                ddlCountsType.SetValue( countsType );
            }
            else
            {
                ddlCountsType.SetValue( "" );
            }
        }
コード例 #17
0
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void ShowActiveUsers()
        {
            int? siteId = GetAttributeValue( "Site" ).AsIntegerOrNull();
            if ( !siteId.HasValue || SiteCache.Read(siteId.Value) == null )
            {
                lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>";
                return;
            }
            else
            {
                int pageViewCount = GetAttributeValue( "PageViewCount" ).AsIntegerOrNull() ?? 0;

                StringBuilder sbUsers = new StringBuilder();

                var site = SiteCache.Read( siteId.Value );
                lSiteName.Text = "<h4>" + site.Name + "</h4>";
                lSiteName.Visible = GetAttributeValue( "ShowSiteNameAsTitle" ).AsBoolean();

                if ( !site.EnablePageViews )
                {
                    lMessages.Text = "<div class='alert alert-warning'>Active " + site.Name + " users not available because page views are not enabled for site.</div>";
                    return;
                }

                lMessages.Text = string.Empty;
                string guestVisitorsStr = string.Empty;

                using ( var rockContext = new RockContext() )
                {
                    var qryPageViews = new PageViewService( rockContext ).Queryable();
                    var qryPersonAlias = new PersonAliasService( rockContext ).Queryable();
                    var pageViewQry = qryPageViews.Join(
                        qryPersonAlias,
                        pv => pv.PersonAliasId,
                        pa => pa.Id,
                        ( pv, pa ) =>
                        new
                        {
                            PersonAliasPersonId = pa.PersonId,
                            pv.DateTimeViewed,
                            pv.SiteId,
                            pv.PageViewSessionId,
                            PagePageTitle = pv.PageTitle
                        } );

                    var last24Hours = RockDateTime.Now.AddDays( -1 );

                    int pageViewTakeCount = pageViewCount;
                    if ( pageViewTakeCount == 0 )
                    {
                        pageViewTakeCount = 1;
                    }

                    // Query to get who is logged in and last visit was to selected site
                    var activeLogins = new UserLoginService( rockContext ).Queryable()
                        .Where( l =>
                            l.PersonId.HasValue &&
                            l.IsOnLine == true )
                        .OrderByDescending( l => l.LastActivityDateTime )
                        .Select( l => new
                        {
                            login = new
                            {
                                l.UserName,
                                l.LastActivityDateTime,
                                l.PersonId,
                                Person = new
                                {
                                    l.Person.NickName,
                                    l.Person.LastName,
                                    l.Person.SuffixValueId
                                }
                            },
                            pageViews = pageViewQry
                                .Where( v => v.PersonAliasPersonId == l.PersonId )
                                .Where( v => v.DateTimeViewed > last24Hours )
                                .OrderByDescending( v => v.DateTimeViewed )
                                .Take( pageViewTakeCount )
                        } )
                        .Select( a => new
                        {
                            a.login,
                            pageViews = a.pageViews.ToList()
                        } );

                    if ( CurrentUser != null )
                    {
                        activeLogins = activeLogins.Where( m => m.login.UserName != CurrentUser.UserName );
                    }

                    foreach ( var activeLogin in activeLogins )
                    {
                        var login = activeLogin.login;

                        if ( !activeLogin.pageViews.Any() || activeLogin.pageViews.FirstOrDefault().SiteId != site.Id )
                        {
                            // only show active logins with PageViews and the most recent pageview is for the specified site
                            continue;
                        }

                        var latestPageViewSessionId = activeLogin.pageViews.FirstOrDefault().PageViewSessionId;

                        TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract( login.LastActivityDateTime.Value ) : TimeSpan.MaxValue;
                        string className = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent";

                        // create link to the person
                        string personFullName = Person.FormatFullName( login.Person.NickName, login.Person.LastName, login.Person.SuffixValueId );
                        string personLink = personFullName;

                        if ( GetAttributeValue( "PersonProfilePage" ) != null )
                        {
                            string personProfilePage = GetAttributeValue( "PersonProfilePage" );
                            var pageParams = new Dictionary<string, string>();
                            pageParams.Add( "PersonId", login.PersonId.ToString() );
                            var pageReference = new Rock.Web.PageReference( personProfilePage, pageParams );
                            personLink = string.Format( @"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), personFullName );
                        }

                        // determine whether to show last page views
                        if ( GetAttributeValue( "PageViewCount" ).AsInteger() > 0 )
                        {
                            string activeLoginFormat = @"
            <li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            // define the formatting for each user entry
                            if ( activeLogin.pageViews != null )
                            {
                                string pageViewsHtml = activeLogin.pageViews
                                                    .Where( v => v.PageViewSessionId == latestPageViewSessionId )
                                                    .Select( v => HttpUtility.HtmlEncode( v.PagePageTitle ) ).ToList().AsDelimited( "<br> " );

                                sbUsers.Append( string.Format( activeLoginFormat, className, personLink, pageViewsHtml ) );
                            }
                        }
                        else
                        {
                            string inactiveLoginFormat = @"
            <li class='active-user {0}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            sbUsers.Append( string.Format( inactiveLoginFormat, className, personLink ) );
                        }
                    }

                    // get the 'show guests' attribute and if it's true, determine how many guests there are.
                    bool showGuestVisitors = GetAttributeValue( "ShowGuestVisitors" ).AsBoolean();
                    if ( showGuestVisitors )
                    {
                        // build a list of unique sessions views in the past 15 minutes.
                        // We'll only take entries with a null personAliasID, which means they're not logged in,
                        // and thus ARE guests.
                        var last5Minutes = RockDateTime.Now.AddMinutes( -5 );
                        var last15Minutes = RockDateTime.Now.AddMinutes( -15 );

                        var qryGuests = new PageViewService( rockContext ).Queryable().AsNoTracking()
                                          .Where(
                                                p => p.SiteId == site.Id
                                                && p.DateTimeViewed > last15Minutes
                                                && p.PersonAliasId == null
                                                && p.PageViewSession.PageViewUserAgent.Browser != "Other"
                                                && p.PageViewSession.PageViewUserAgent.ClientType != "Crawler" )
                                          .GroupBy( p => p.PageViewSessionId )
                                          .Select( g => new
                                          {
                                              SessionId = g.Key,
                                              LastVisit = g.Max( p => p.DateTimeViewed )
                                          } )
                                          .ToList();

                        var numRecentGuests = qryGuests.Where( g => g.LastVisit >= last5Minutes ).Count();
                        var numInactiveGuests = qryGuests.Where( g => g.LastVisit < last5Minutes ).Count();

                        // now build the formatted entry, which is "Current Guests (0) (1)" where the first is a green badge, and the second yellow.
                        if ( numRecentGuests > 0 || numInactiveGuests > 0 )
                        {
                            guestVisitorsStr = "Current Guests:";
                            if ( numRecentGuests > 0 )
                            {
                                guestVisitorsStr += string.Format( " <span class=\"badge badge-success\">{0}</span>", numRecentGuests );
                            }

                            if ( numInactiveGuests > 0 )
                            {
                                guestVisitorsStr += string.Format( " <span class=\"badge badge-warning\">{0}</span>", numInactiveGuests );
                            }
                        }
                    }
                }

                if ( sbUsers.Length > 0 )
                {
                    lUsers.Text = string.Format( @"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString() );
                    lUsers.Text += string.Format( @"<p class='margin-l-sm'>{0}</p>", guestVisitorsStr );
                }
                else
                {
                    lMessages.Text = string.Format( "There are no logged in users on the {0} site.", site.Name );
                    lMessages.Text += "<br /><br />" + guestVisitorsStr;
                }
            }
        }
コード例 #18
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            if (HttpContext.Current != null)
            {
                _rockContext = rockContext;

                var workflow = action.Activity.Workflow;

                var    page = GetAttributeValue(action, "Page");
                string url  = null;

                if (string.IsNullOrEmpty(page))
                {
                    var guidPageAttributeValue = GetAttributeValue(action, "PageAttribute").AsGuidOrNull();

                    if (guidPageAttributeValue.HasValue)
                    {
                        var attributePage = AttributeCache.Read(guidPageAttributeValue.Value, rockContext);
                        if (attributePage != null)
                        {
                            if (attributePage.FieldType.Class == "Rock.Field.Types.PageReferenceFieldType")
                            {
                                page = action.GetWorklowAttributeValue(guidPageAttributeValue.Value);
                            }
                            else
                            {
                                var urlValue = action.GetWorklowAttributeValue(guidPageAttributeValue.Value);
                                Uri uri;
                                if (Uri.TryCreate(urlValue, UriKind.RelativeOrAbsolute, out uri))
                                {
                                    url = uri.ToString();
                                }
                            }
                        }
                    }
                }

                if (workflow.IsPersisted)
                {
                    PersistWorkflow(workflow);   //ensure any changes are saved before redirecting.
                }

                if (!String.IsNullOrEmpty(page))
                {
                    var queryParams = new Dictionary <string, string>();
                    queryParams.Add("WorkflowTypeId", action.Activity.Workflow.WorkflowTypeId.ToString());

                    if (workflow.Id != 0)
                    {
                        queryParams.Add("WorkflowId", action.Activity.WorkflowId.ToString());
                    }

                    var pageReference = new Rock.Web.PageReference(page, queryParams);
                    HttpContext.Current.Response.Redirect(pageReference.BuildUrl(), false);
                }
                else if (!String.IsNullOrEmpty(url))
                {
                    HttpContext.Current.Response.Redirect(url, false);
                }
            }
            return(true);
        }
コード例 #19
0
        protected void SaveDetails()
        {
            var      checkValue = false;
            CheckBox check      = ( CheckBox )fsAttributes.FindControl("SimpleCheckBox");

            if (check != null && check.Checked)
            {
                checkValue = true;
            }

            IHasAttributes entity = ContextEntity() as IHasAttributes;

            var rockContext          = new RockContext();
            var sourceAttributeKey   = GetAttributeValue("SourceEntityAttributeKey");
            var sourceAttributeValue = entity.GetAttributeValue(sourceAttributeKey);
            var attributeService     = new AttributeService(rockContext);
            var targetAttribute      = attributeService.GetByGuids(new List <Guid>()
            {
                sourceAttributeValue.AsGuid()
            }).ToList().FirstOrDefault();

            int personEntityTypeId = EntityTypeCache.Get(typeof(Person)).Id;

            var changes = new History.HistoryChangeList();

            var attribute = AttributeCache.Get(targetAttribute);

            if (CurrentPerson != null)
            {
                Control attributeControl = fsAttributes.FindControl(string.Format("attribute_field_{0}", attribute.Id));
                if (GetAttributeValue("CheckboxMode").AsBoolean(false) || attributeControl != null)
                {
                    string originalValue = CurrentPerson.GetAttributeValue(attribute.Key);
                    string newValue      = string.Empty;

                    if (GetAttributeValue("CheckboxMode").AsBoolean(false))
                    {
                        var valueMode = GetAttributeValue("CheckboxAttributeValueMode");
                        if (valueMode == "Date")
                        {
                            if (checkValue)
                            {
                                newValue = RockDateTime.Now.ToString();
                            }
                            else
                            {
                                newValue = string.Empty;
                            }
                        }
                        else if (valueMode == "Boolean")
                        {
                            if (checkValue)
                            {
                                newValue = "True";
                            }
                            else
                            {
                                newValue = "False";
                            }
                        }
                    }
                    else
                    {
                        newValue = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues);
                    }

                    Rock.Attribute.Helper.SaveAttributeValue(CurrentPerson, attribute, newValue, rockContext);

                    // Check for changes to write to history
                    if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                    {
                        string formattedOriginalValue = string.Empty;
                        if (!string.IsNullOrWhiteSpace(originalValue))
                        {
                            formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                        }

                        string formattedNewValue = string.Empty;
                        if (!string.IsNullOrWhiteSpace(newValue))
                        {
                            formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                        }

                        History.EvaluateChange(changes, attribute.Name, formattedOriginalValue, formattedNewValue, attribute.FieldType.Field.IsSensitive());
                    }
                }
            }

            if (changes.Any())
            {
                HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                           CurrentPerson.Id, changes);
            }

            string linkedPage = GetAttributeValue("RedirectPage");

            if (string.IsNullOrWhiteSpace(linkedPage))
            {
                ShowDetails();
            }
            else
            {
                var pageParams = new Dictionary <string, string>();
                pageParams.Add("av", "updated");
                var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                Response.Redirect(pageReference.BuildUrl(), false);
            }
        }
コード例 #20
0
ファイル: DynamicChart.ascx.cs プロジェクト: NewSpring/Rock
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger( upnlContent );

            var pageReference = new Rock.Web.PageReference( this.PageCache.Id );
            pageReference.QueryString = new System.Collections.Specialized.NameValueCollection();
            pageReference.QueryString.Add( this.Request.QueryString );
            pageReference.QueryString.Add( "GetChartData", "true" );
            pageReference.QueryString.Add( "GetChartDataBlockId", this.BlockId.ToString() );
            pageReference.QueryString.Add( "TimeStamp", RockDateTime.Now.ToJavascriptMilliseconds().ToString() );
            lcLineChart.DataSourceUrl = pageReference.BuildUrl();
            lcLineChart.ChartHeight = this.GetAttributeValue( "ChartHeight" ).AsIntegerOrNull() ?? 200;
            lcLineChart.Options.SetChartStyle( this.GetAttributeValue( "ChartStyle" ).AsGuidOrNull() );
            lcLineChart.Options.legend = lcLineChart.Options.legend ?? new Legend();
            lcLineChart.Options.legend.show = this.GetAttributeValue( "ShowLegend" ).AsBooleanOrNull();
            lcLineChart.Options.legend.position = this.GetAttributeValue( "LegendPosition" );

            bcBarChart.DataSourceUrl = pageReference.BuildUrl();
            bcBarChart.ChartHeight = this.GetAttributeValue( "ChartHeight" ).AsIntegerOrNull() ?? 200;
            bcBarChart.Options.SetChartStyle( this.GetAttributeValue( "ChartStyle" ).AsGuidOrNull() );
            bcBarChart.Options.xaxis = new AxisOptions { mode = AxisMode.categories, tickLength = 0 };
            bcBarChart.Options.series.bars.barWidth = 0.6;
            bcBarChart.Options.series.bars.align = "center";

            bcBarChart.Options.legend = lcLineChart.Options.legend ?? new Legend();
            bcBarChart.Options.legend.show = this.GetAttributeValue( "ShowLegend" ).AsBooleanOrNull();
            bcBarChart.Options.legend.position = this.GetAttributeValue( "LegendPosition" );

            pcPieChart.DataSourceUrl = pageReference.BuildUrl();
            pcPieChart.ChartHeight = this.GetAttributeValue( "ChartHeight" ).AsIntegerOrNull() ?? 200;
            pcPieChart.Options.SetChartStyle( this.GetAttributeValue( "ChartStyle" ).AsGuidOrNull() );

            pcPieChart.PieOptions.label = new PieLabel { show = this.GetAttributeValue( "PieShowLabels" ).AsBooleanOrNull() ?? true };
            pcPieChart.PieOptions.label.formatter = @"
            function labelFormatter(label, series) {
            return ""<div style='font-size:8pt; text-align:center; padding:2px; '>"" + label + ""<br/>"" + Math.round(series.percent) + ""%</div>"";
            }
            ".Trim();
            pcPieChart.Legend.show = this.GetAttributeValue( "ShowLegend" ).AsBooleanOrNull();

            pcPieChart.PieOptions.innerRadius = this.GetAttributeValue( "PieInnerRadius" ).AsDoubleOrNull();

            lcLineChart.Visible = false;
            bcBarChart.Visible = false;
            pcPieChart.Visible = false;
            var chartType = this.GetAttributeValue( "ChartType" );
            if ( chartType == "Pie" )
            {
                pcPieChart.Visible = true;
            }
            else if ( chartType == "Bar" )
            {
                bcBarChart.Visible = true;
            }
            else
            {
                lcLineChart.Visible = true;
            }

            pnlDashboardTitle.Visible = !string.IsNullOrEmpty( this.Title );
            pnlDashboardSubtitle.Visible = !string.IsNullOrEmpty( this.Subtitle );
            lDashboardTitle.Text = this.Title;
            lDashboardSubtitle.Text = this.Subtitle;

            var sql = this.GetAttributeValue( "SQL" );

            if ( string.IsNullOrWhiteSpace( sql ) )
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text = "SQL needs to be configured in block settings";
            }
            else
            {
                nbConfigurationWarning.Visible = false;
            }

            if ( PageParameter( "GetChartData" ).AsBoolean() && ( PageParameter( "GetChartDataBlockId" ).AsInteger() == this.BlockId ) )
            {
                GetChartData();
            }
        }
コード例 #21
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            var rockContext = new RockContext();

            int sessionCount = GetAttributeValue( "SessionCount" ).AsInteger();

            int skipCount = pageNumber * sessionCount;

            var person = new PersonService( rockContext ).GetByUrlEncodedKey( PageParameter( "Person" ) );

            if ( person != null )
            {
                lPersonName.Text = person.FullName;

                InteractionService interactionService = new InteractionService( rockContext );

                var pageViews = interactionService.Queryable();

                var sessionInfo = interactionService.Queryable()
                    .Where( s => s.PersonAlias.PersonId == person.Id );

                if ( startDate != DateTime.MinValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.InteractionDateTime > drpDateFilter.LowerValue );
                }

                if ( endDate != DateTime.MaxValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.InteractionDateTime < drpDateFilter.UpperValue );
                }

                if ( siteId != -1 )
                {
                    var site = SiteCache.Read( siteId );

                    string siteName = string.Empty;
                    if (site != null )
                    {
                        siteName = site.Name;
                    }
                    // lookup the interactionDeviceType, and create it if it doesn't exist
                    int channelMediumValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid() ).Id;

                    var interactionChannelId = new InteractionChannelService( rockContext ).Queryable()
                                                        .Where( a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId )
                                                        .Select( a => a.Id)
                                                        .FirstOrDefault();

                    sessionInfo = sessionInfo.Where( p => p.InteractionComponent.ChannelId == interactionChannelId );
                }

                var pageviewInfo = sessionInfo.GroupBy( s => new
                                {
                                    s.InteractionSession,
                                    s.InteractionComponent.Channel,
                                } )
                                .Select( s => new WebSession
                                {
                                    PageViewSession = s.Key.InteractionSession,
                                    StartDateTime = s.Min( x => x.InteractionDateTime ),
                                    EndDateTime = s.Max( x => x.InteractionDateTime ),
                                    SiteId = siteId,
                                    Site = s.Key.Channel.Name,
                                    PageViews = pageViews.Where( p => p.InteractionSessionId == s.Key.InteractionSession.Id && p.InteractionComponent.ChannelId == s.Key.Channel.Id ).OrderBy(p => p.InteractionDateTime).ToList()
                                } );

                pageviewInfo = pageviewInfo.OrderByDescending( p => p.StartDateTime )
                                .Skip( skipCount )
                                .Take( sessionCount + 1 );

                rptSessions.DataSource = pageviewInfo.ToList().Take( sessionCount );
                rptSessions.DataBind();

                // set next button
                if ( pageviewInfo.Count() > sessionCount )
                {
                    hlNext.Visible = hlNext.Enabled = true;
                    Dictionary<string, string> queryStringNext = new Dictionary<string, string>();
                    queryStringNext.Add( "Page", ( pageNumber + 1 ).ToString() );
                    queryStringNext.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringNext.Add( "SiteId", siteId.ToString() );
                    }

                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringNext.Add( "StartDate", startDate.ToShortDateString() );
                    }

                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringNext.Add( "EndDate", endDate.ToShortDateString() );
                    }

                    var pageReferenceNext = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext );
                    hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                }
                else
                {
                    hlNext.Visible = hlNext.Enabled = false;
                }

                // set 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() );
                    queryStringPrev.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringPrev.Add( "SiteId", siteId.ToString() );
                    }

                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringPrev.Add( "StartDate", startDate.ToShortDateString() );
                    }

                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringPrev.Add( "EndDate", endDate.ToShortDateString() );
                    }

                    var pageReferencePrev = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev );
                    hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>";
            }
        }
コード例 #22
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            mdCategoryTreeConfig.Visible = false;

            bool canEditBlock = IsUserAuthorized( Authorization.EDIT );

            // hide all the actions if user doesn't have EDIT to the block
            divTreeviewActions.Visible = canEditBlock;

            var detailPageReference = new Rock.Web.PageReference( GetAttributeValue( "DetailPage" ) );

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavior)
            if ( detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId )
            {
                hfPageRouteTemplate.Value = ( this.RockPage.RouteData.Route as System.Web.Routing.Route ).Url;
                hfDetailPageUrl.Value = new Rock.Web.PageReference( this.RockPage.PageId ).BuildUrl().RemoveLeadingForwardslash();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Read( detailPageReference.PageId );
                if ( pageCache != null )
                {
                    var route = pageCache.PageRoutes.FirstOrDefault( a => a.Id == detailPageReference.RouteId );
                    if ( route != null )
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl().RemoveLeadingForwardslash();
            }

            // Get EntityTypeName
            Guid? entityTypeGuid = GetAttributeValue( "EntityType" ).AsGuidOrNull();
            nbWarning.Text = "Please select an entity type in the block settings.";
            nbWarning.Visible = !entityTypeGuid.HasValue;
            if ( entityTypeGuid.HasValue )
            {
                int entityTypeId = Rock.Web.Cache.EntityTypeCache.Read( entityTypeGuid.Value ).Id;
                string entityTypeQualiferColumn = GetAttributeValue( "EntityTypeQualifierProperty" );
                string entityTypeQualifierValue = GetAttributeValue( "EntityTypeQualifierValue" );
                bool showUnnamedEntityItems = GetAttributeValue( "ShowUnnamedEntityItems" ).AsBooleanOrNull() ?? true;

                string parms = string.Format( "?getCategorizedItems=true&showUnnamedEntityItems={0}", showUnnamedEntityItems.ToTrueFalse().ToLower() );
                parms += string.Format( "&entityTypeId={0}", entityTypeId );

                var rootCategory = CategoryCache.Read( this.GetAttributeValue( "RootCategory" ).AsGuid() );

                // make sure the rootCategory matches the EntityTypeId (just in case they changed the EntityType after setting RootCategory
                if ( rootCategory != null && rootCategory.EntityTypeId == entityTypeId )
                {
                    parms += string.Format( "&rootCategoryId={0}", rootCategory.Id );
                }

                if ( !string.IsNullOrEmpty( entityTypeQualiferColumn ) )
                {
                    parms += string.Format( "&entityQualifier={0}", entityTypeQualiferColumn );

                    if ( !string.IsNullOrEmpty( entityTypeQualifierValue ) )
                    {
                        parms += string.Format( "&entityQualifierValue={0}", entityTypeQualifierValue );
                    }
                }

                var excludeCategoriesGuids = this.GetAttributeValue( "ExcludeCategories" ).SplitDelimitedValues().AsGuidList();
                List<int> excludedCategoriesIds = new List<int>();
                if ( excludeCategoriesGuids != null && excludeCategoriesGuids.Any() )
                {
                    foreach ( var excludeCategoryGuid in excludeCategoriesGuids )
                    {
                        var excludedCategory = CategoryCache.Read( excludeCategoryGuid );
                        if (excludedCategory != null)
                        {
                            excludedCategoriesIds.Add( excludedCategory.Id );
                        }
                    }

                    parms += string.Format( "&excludedCategoryIds={0}", excludedCategoriesIds.AsDelimited(",") );
                }

                string defaultIconCssClass = GetAttributeValue("DefaultIconCSSClass");
                if ( !string.IsNullOrWhiteSpace( defaultIconCssClass ) )
                {
                    parms += string.Format( "&defaultIconCssClass={0}", defaultIconCssClass );
                }

                RestParms = parms;

                var cachedEntityType = Rock.Web.Cache.EntityTypeCache.Read( entityTypeId );
                if ( cachedEntityType != null )
                {
                    string entityTypeFriendlyName = GetAttributeValue( "EntityTypeFriendlyName" );
                    if ( string.IsNullOrWhiteSpace( entityTypeFriendlyName ) )
                    {
                        entityTypeFriendlyName = cachedEntityType.FriendlyName;
                    }

                    lbAddItem.ToolTip = "Add " + entityTypeFriendlyName;
                    lAddItem.Text = entityTypeFriendlyName;
                }

                // Attempt to retrieve an EntityId from the Page URL parameters.
                PageParameterName = GetAttributeValue( "PageParameterKey" );

                string selectedNodeId = null;

                int? itemId = PageParameter( PageParameterName ).AsIntegerOrNull();
                string selectedEntityType;
                if (itemId.HasValue)
                {
                    selectedNodeId = itemId.ToString();
                    selectedEntityType = (cachedEntityType != null) ? cachedEntityType.Name : string.Empty;
                }
                else
                {
                    // If an EntityId was not specified, check for a CategoryId.
                    itemId = PageParameter( "CategoryId" ).AsIntegerOrNull();

                    selectedNodeId = CategoryNodePrefix + itemId;
                    selectedEntityType = "category";
                }

                lbAddCategoryRoot.Enabled = true;
                lbAddCategoryChild.Enabled = false;
                lbAddItem.Enabled = false;

                CategoryCache selectedCategory = null;

                if ( !string.IsNullOrEmpty( selectedNodeId ) )
                {
                    hfSelectedItemId.Value = selectedNodeId;
                    List<string> parentIdList = new List<string>();

                    if ( selectedEntityType.Equals( "category" ) )
                    {
                        selectedCategory = CategoryCache.Read( itemId.GetValueOrDefault() );
                        if ( selectedCategory != null && !canEditBlock && selectedCategory.IsAuthorized( Authorization.EDIT, CurrentPerson ) )
                        {
                            // Show the action buttons if user has edit rights to category
                            divTreeviewActions.Visible = true;
                        }
                    }
                    else
                    {
                        if ( cachedEntityType != null )
                        {
                            Type entityType = cachedEntityType.GetEntityType();
                            if ( entityType != null )
                            {
                                Type serviceType = typeof( Rock.Data.Service<> );
                                Type[] modelType = { entityType };
                                Type service = serviceType.MakeGenericType( modelType );
                                var serviceInstance = Activator.CreateInstance( service, new object[] { new RockContext() } );
                                var getMethod = service.GetMethod( "Get", new Type[] { typeof( int ) } );
                                ICategorized entity = getMethod.Invoke( serviceInstance, new object[] { itemId } ) as ICategorized;

                                if ( entity != null )
                                {
                                    lbAddCategoryChild.Enabled = false;
                                    if ( entity.CategoryId.HasValue )
                                    {
                                        selectedCategory = CategoryCache.Read( entity.CategoryId.Value );
                                        if ( selectedCategory != null )
                                        {
                                            string categoryExpandedID = CategoryNodePrefix + selectedCategory.Id.ToString();
                                            parentIdList.Insert( 0, CategoryNodePrefix + categoryExpandedID );
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // get the parents of the selected item so we can tell the treeview to expand those
                    var category = selectedCategory;
                    while ( category != null )
                    {
                        category = category.ParentCategory;
                        if ( category != null )
                        {
                            string categoryExpandedID = CategoryNodePrefix + category.Id.ToString();
                            if ( !parentIdList.Contains( categoryExpandedID ) )
                            {
                                parentIdList.Insert( 0, categoryExpandedID );
                            }
                            else
                            {
                                // infinite recursion
                                break;
                            }
                        }

                    }
                    // also get any additional expanded nodes that were sent in the Post
                    string postedExpandedIds = this.Request.Params["ExpandedIds"];
                    if ( !string.IsNullOrWhiteSpace( postedExpandedIds ) )
                    {
                        var postedExpandedIdList = postedExpandedIds.Split( ',' ).ToList();
                        foreach ( var id in postedExpandedIdList )
                        {
                            if ( !parentIdList.Contains( id ) )
                            {
                                parentIdList.Add( id );
                            }
                        }
                    }

                    hfInitialCategoryParentIds.Value = parentIdList.AsDelimited( "," );
                }

                selectedCategory = selectedCategory ?? rootCategory;

                if ( selectedCategory != null )
                {
                    lbAddItem.Enabled = true;
                    lbAddCategoryChild.Enabled = true;
                    this.SelectedCategoryId = selectedCategory.Id;
                }
                else
                {
                    this.SelectedCategoryId = null;
                }
            }
        }
コード例 #23
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages )
        {
            errorMessages = new List<string>();

            if (HttpContext.Current != null)
            {
                _rockContext = rockContext;

                var workflow = action.Activity.Workflow;

                var page = GetAttributeValue( action, "Page" );
                string url = null;

                if (string.IsNullOrEmpty( page ))
                {
                    var guidPageAttributeValue = GetAttributeValue( action, "PageAttribute" ).AsGuidOrNull();

                    if (guidPageAttributeValue.HasValue)
                    {
                        var attributePage = AttributeCache.Read( guidPageAttributeValue.Value, rockContext );
                        if (attributePage != null)
                        {
                            if (attributePage.FieldType.Class == "Rock.Field.Types.PageReferenceFieldType") {
                                page = action.GetWorklowAttributeValue( guidPageAttributeValue.Value );
                            }
                            else
                            {
                                var urlValue = action.GetWorklowAttributeValue( guidPageAttributeValue.Value );
                                Uri uri;
                                if (Uri.TryCreate( urlValue, UriKind.RelativeOrAbsolute, out uri ))
                                {
                                    url = uri.ToString();
                                }
                            }

                        }
                        
                    }
                }

                if (workflow.IsPersisted)
                {
                    PersistWorkflow( workflow ); //ensure any changes are saved before redirecting.
                }

                if (!String.IsNullOrEmpty( page ))
                {
                    var queryParams = new Dictionary<string, string>();
                    queryParams.Add( "WorkflowTypeId", action.Activity.Workflow.WorkflowTypeId.ToString() );

                    if (workflow.Id != 0)
                    {
                        queryParams.Add( "WorkflowId", action.Activity.WorkflowId.ToString() );
                    }

                    var pageReference = new Rock.Web.PageReference( page, queryParams );
                    HttpContext.Current.Response.Redirect( pageReference.BuildUrl(), false );

                }
                else if (!String.IsNullOrEmpty( url ))
                {
                    HttpContext.Current.Response.Redirect( url, false );
                }

            }
            return true;
        }
コード例 #24
0
        /// <summary>
        /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
        /// </summary>
        /// <param name="eventArgument">A <see cref="T:System.String" /> that represents an optional event argument to be passed to the event handler.</param>
        public void RaisePostBackEvent( string eventArgument )
        {
            if ( _canEdit && _batch != null )
            {
                if ( eventArgument == "MoveTransactions" &&
                    _ddlMove != null &&
                    _ddlMove.SelectedValue != null &&
                    !String.IsNullOrWhiteSpace( _ddlMove.SelectedValue ) )
                {
                    var txnsSelected = new List<int>();
                    gTransactions.SelectedKeys.ToList().ForEach( b => txnsSelected.Add( b.ToString().AsInteger() ) );

                    if ( txnsSelected.Any() )
                    {
                        var rockContext = new RockContext();
                        var batchService = new FinancialBatchService( rockContext );

                        var newBatch = batchService.Get( _ddlMove.SelectedValue.AsInteger() );
                        var oldBatch = batchService.Get( _batch.Id );

                        if ( oldBatch != null && newBatch != null && newBatch.Status == BatchStatus.Open )
                        {
                            var txnService = new FinancialTransactionService( rockContext );
                            var txnsToUpdate = txnService.Queryable( "AuthorizedPersonAlias.Person" )
                                .Where( t => txnsSelected.Contains( t.Id ) )
                                .ToList();

                            decimal oldBatchControlAmount = oldBatch.ControlAmount;
                            decimal newBatchControlAmount = newBatch.ControlAmount;

                            foreach ( var txn in txnsToUpdate )
                            {
                                string caption = ( txn.AuthorizedPersonAlias != null && txn.AuthorizedPersonAlias.Person != null ) ?
                                    txn.AuthorizedPersonAlias.Person.FullName :
                                    string.Format( "Transaction: {0}", txn.Id );

                                var changes = new List<string>();
                                History.EvaluateChange( changes, "Batch",
                                    string.Format( "{0} (Id:{1})", oldBatch.Name, oldBatch.Id ),
                                    string.Format( "{0} (Id:{1})", newBatch.Name, newBatch.Id ) );

                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof( FinancialBatch ),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    oldBatch.Id,
                                    changes,
                                    caption,
                                    typeof( FinancialTransaction ),
                                    txn.Id,
                                    false
                                );

                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof( FinancialBatch ),
                                    Rock.SystemGuid.Category.HISTORY_FINANCIAL_TRANSACTION.AsGuid(),
                                    newBatch.Id,
                                    changes,
                                    caption,
                                    typeof( FinancialTransaction ),
                                    txn.Id, false
                                );

                                txn.BatchId = newBatch.Id;
                                oldBatchControlAmount -= txn.TotalAmount;
                                newBatchControlAmount += txn.TotalAmount;
                            }

                            var oldBatchChanges = new List<string>();
                            History.EvaluateChange( oldBatchChanges, "Control Amount", oldBatch.ControlAmount.FormatAsCurrency(), oldBatchControlAmount.FormatAsCurrency() );
                            oldBatch.ControlAmount = oldBatchControlAmount;

                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( FinancialBatch ),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                oldBatch.Id,
                                oldBatchChanges,
                                false
                            );

                            var newBatchChanges = new List<string>();
                            History.EvaluateChange( newBatchChanges, "Control Amount", newBatch.ControlAmount.FormatAsCurrency(), newBatchControlAmount.FormatAsCurrency() );
                            newBatch.ControlAmount = newBatchControlAmount;

                            HistoryService.SaveChanges(
                                rockContext,
                                typeof( FinancialBatch ),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                newBatch.Id,
                                newBatchChanges,
                                false
                            );

                            rockContext.SaveChanges();

                            var pageRef = new Rock.Web.PageReference( RockPage.PageId );
                            pageRef.Parameters = new Dictionary<string, string>();
                            pageRef.Parameters.Add( "batchid", newBatch.Id.ToString() );
                            string newBatchLink = string.Format( "<a href='{0}'>{1}</a>",
                                pageRef.BuildUrl(), newBatch.Name );

                            RockPage.UpdateBlocks( "~/Blocks/Finance/BatchDetail.ascx" );

                            nbResult.Text = string.Format( "{0} transactions were moved to the '{1}' batch.",
                                txnsToUpdate.Count().ToString( "N0" ), newBatchLink );
                            nbResult.NotificationBoxType = NotificationBoxType.Success;
                            nbResult.Visible = true;
                        }
                        else
                        {
                            nbResult.Text = string.Format( "The selected batch does not exist, or is no longer open." );
                            nbResult.NotificationBoxType = NotificationBoxType.Danger;
                            nbResult.Visible = true;
                        }
                    }
                    else
                    {
                        nbResult.Text = string.Format( "There were not any transactions selected." );
                        nbResult.NotificationBoxType = NotificationBoxType.Warning;
                        nbResult.Visible = true;
                    }
                }

                _ddlMove.SelectedIndex = 0;
            }

            BindGrid();
        }
コード例 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var shapePageReference = new Rock.Web.PageReference(GetAttributeValue("SHAPEAssessmentPage"));
            var discPageReference  = new Rock.Web.PageReference(GetAttributeValue("DISCAssessmentPage"));

            if (!string.IsNullOrWhiteSpace(PageParameter("FormId")))
            {
                //Load the person based on the FormId
                var personInUrl = PageParameter("FormId");
                SelectedPerson   = GetPersonFromForm(personInUrl);
                PersonEncodedKey = SelectedPerson.UrlEncodedKey;
            }

            else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
            {
                //Load the person based on the PersonId
                SelectedPerson   = GetPersonFromId(PageParameter("PersonId"));
                PersonEncodedKey = SelectedPerson.UrlEncodedKey;
            }

            else if (CurrentPerson != null)
            {
                //Load the person based on the currently logged in person
                SelectedPerson   = CurrentPerson;
                PersonEncodedKey = SelectedPerson.UrlEncodedKey;
            }

            else
            {
                //Show Error Message
                nbNoPerson.Visible = true;
                Response.Redirect(shapePageReference.BuildUrl(), true);
                return;
            }



            // Load the attributes

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            DefinedValueService   definedValueService   = new DefinedValueService(rockContext);



            string spiritualGift1  = "";
            string spiritualGift2  = "";
            string spiritualGift3  = "";
            string spiritualGift4  = "";
            string heartCategories = "";
            string heartCauses     = "";
            string heartPassion    = "";
            string ability1        = "";
            string ability2        = "";
            string people          = "";
            string places          = "";
            string events          = "";

            var spiritualGift1AttributeValue =
                attributeValueService
                .Queryable()
                .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id);

            // Redirect if they haven't taken the Assessment
            if (spiritualGift1AttributeValue == null)
            {
                Response.Redirect(shapePageReference.BuildUrl(), true);
            }

            else
            {
                var spiritualGift2AttributeValue =
                    attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id);

                var spiritualGift3AttributeValue =
                    attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id);

                var spiritualGift4AttributeValue =
                    attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id);

                var ability1AttributeValue =
                    attributeValueService
                    .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id);

                var ability2AttributeValue =
                    attributeValueService
                    .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id);

                var peopleAttributeValue = attributeValueService
                                           .Queryable()
                                           .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id);

                var placesAttributeValue = attributeValueService
                                           .Queryable()
                                           .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id);

                var eventsAttributeValue = attributeValueService
                                           .Queryable()
                                           .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id);

                var heartCategoriesAttributeValue = attributeValueService
                                                    .Queryable()
                                                    .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id);

                var heartCausesAttributeValue = attributeValueService
                                                .Queryable()
                                                .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id);

                var heartPassionAttributeValue = attributeValueService
                                                 .Queryable()
                                                 .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id);


                if (spiritualGift1AttributeValue.Value != null)
                {
                    spiritualGift1 = spiritualGift1AttributeValue.Value;
                }
                if (spiritualGift2AttributeValue.Value != null)
                {
                    spiritualGift2 = spiritualGift2AttributeValue.Value;
                }
                if (spiritualGift3AttributeValue.Value != null)
                {
                    spiritualGift3 = spiritualGift3AttributeValue.Value;
                }
                if (spiritualGift4AttributeValue.Value != null)
                {
                    spiritualGift4 = spiritualGift4AttributeValue.Value;
                }
                if (heartCategoriesAttributeValue.Value != null)
                {
                    heartCategories = heartCategoriesAttributeValue.Value;
                }
                if (heartCausesAttributeValue.Value != null)
                {
                    heartCauses = heartCausesAttributeValue.Value;
                }
                if (heartPassionAttributeValue.Value != null)
                {
                    heartPassion = heartPassionAttributeValue.Value;
                }
                if (ability1AttributeValue.Value != null)
                {
                    ability1 = ability1AttributeValue.Value;
                }
                if (ability2AttributeValue.Value != null)
                {
                    ability2 = ability2AttributeValue.Value;
                }
                if (peopleAttributeValue.Value != null)
                {
                    people = peopleAttributeValue.Value;
                }
                if (placesAttributeValue.Value != null)
                {
                    places = placesAttributeValue.Value;
                }
                if (eventsAttributeValue.Value != null)
                {
                    events = eventsAttributeValue.Value;
                }

                string spiritualGift1Guid;
                string spiritualGift2Guid;
                string spiritualGift3Guid;
                string spiritualGift4Guid;
                string ability1Guid;
                string ability2Guid;


                // Check to see if there are already values saved as an ID.  If so, convert them to GUID
                if (spiritualGift1.ToString().Length < 5)
                {
                    if (spiritualGift1 != null)
                    {
                        SpiritualGift1 = Int32.Parse(spiritualGift1);
                    }
                    if (spiritualGift2 != null)
                    {
                        SpiritualGift2 = Int32.Parse(spiritualGift2);
                    }
                    if (spiritualGift3 != null)
                    {
                        SpiritualGift3 = Int32.Parse(spiritualGift3);
                    }
                    if (spiritualGift4 != null)
                    {
                        SpiritualGift4 = Int32.Parse(spiritualGift4);
                    }
                    if (ability1 != null)
                    {
                        Ability1 = Int32.Parse(ability1);
                    }
                    if (ability2 != null)
                    {
                        Ability2 = Int32.Parse(ability2);
                    }

                    var intsOfGifts =
                        definedValueService.GetByIds(new List <int>
                    {
                        SpiritualGift1,
                        SpiritualGift2,
                        SpiritualGift3,
                        SpiritualGift4,
                        Ability1,
                        Ability2
                    });

                    spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString();
                    spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString();
                    spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString();
                    spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString();
                    ability1Guid       = intsOfGifts.ToList()[Ability1].Guid.ToString();
                    ability2Guid       = intsOfGifts.ToList()[Ability2].Guid.ToString();
                }
                else
                {
                    spiritualGift1Guid = spiritualGift1;
                    spiritualGift2Guid = spiritualGift2;
                    spiritualGift3Guid = spiritualGift3;
                    spiritualGift4Guid = spiritualGift4;
                    ability1Guid       = ability1;
                    ability2Guid       = ability2;
                }



                // Get all of the data about the assiciated gifts and ability categories
                var shapeGift1Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift1Guid)
                }).FirstOrDefault();
                var shapeGift2Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift2Guid)
                }).FirstOrDefault();
                var shapeGift3Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift3Guid)
                }).FirstOrDefault();
                var shapeGift4Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(spiritualGift4Guid)
                }).FirstOrDefault();
                var ability1Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(ability1Guid)
                }).FirstOrDefault();
                var ability2Object = definedValueService.GetListByGuids(new List <Guid> {
                    new Guid(ability2Guid)
                }).FirstOrDefault();


                shapeGift1Object.LoadAttributes();
                shapeGift2Object.LoadAttributes();
                shapeGift3Object.LoadAttributes();
                shapeGift4Object.LoadAttributes();
                ability1Object.LoadAttributes();
                ability2Object.LoadAttributes();


                // Get heart choices Values from Guids
                string heartCategoriesString = "";
                if (!heartCategories.IsNullOrWhiteSpace())
                {
                    string[] heartCategoryArray = heartCategories.Split(',');
                    foreach (string category in heartCategoryArray)
                    {
                        var definedValueObject =
                            definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category));

                        if (category.Equals(heartCategoryArray.Last()))
                        {
                            heartCategoriesString += definedValueObject.Value;
                        }
                        else
                        {
                            heartCategoriesString += definedValueObject.Value + ", ";
                        }
                    }
                }


                // Get Volunteer Opportunities

                string gift1AssociatedVolunteerOpportunities =
                    shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift2AssociatedVolunteerOpportunities =
                    shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift3AssociatedVolunteerOpportunities =
                    shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift4AssociatedVolunteerOpportunities =
                    shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities");

                string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," +
                                                             gift2AssociatedVolunteerOpportunities + "," +
                                                             gift3AssociatedVolunteerOpportunities + "," +
                                                             gift4AssociatedVolunteerOpportunities;

                if (allAssociatedVolunteerOpportunities != ",,,")
                {
                    List <int> associatedVolunteerOpportunitiesList =
                        allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList();
                    Dictionary <int, int> VolunteerOpportunities = new Dictionary <int, int>();


                    var i = 0;
                    var q = from x in associatedVolunteerOpportunitiesList
                            group x by x
                            into g
                            let count = g.Count()
                                        orderby count descending
                                        select new { Value = g.Key, Count = count };
                    foreach (var x in q)
                    {
                        VolunteerOpportunities.Add(i, x.Value);
                        i++;
                    }

                    ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                    List <ConnectionOpportunity> connectionOpportunityList    = new List <ConnectionOpportunity>();

                    foreach (KeyValuePair <int, int> entry in VolunteerOpportunities.Take(4))
                    {
                        var connection = connectionOpportunityService.GetByIds(new List <int> {
                            entry.Value
                        }).FirstOrDefault();

                        // Only display connection if it is marked Active
                        if (connection.IsActive == true)
                        {
                            connectionOpportunityList.Add(connection);
                        }
                    }

                    rpVolunteerOpportunities.DataSource = connectionOpportunityList;
                    rpVolunteerOpportunities.DataBind();
                }



                //Get DISC Info

                DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson);


                if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType))
                {
                    ShowResults(savedScores);
                    DISCResults.Visible   = true;
                    NoDISCResults.Visible = false;
                }
                else
                {
                    discPageReference.Parameters = new System.Collections.Generic.Dictionary <string, string>();
                    discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey);
                    Response.Redirect(discPageReference.BuildUrl(), true);
                }


                // Build the UI

                lbPersonName.Text = SelectedPerson.FullName;

                lbGift1Title.Text    = shapeGift1Object.Value;
                lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription");

                lbGift2Title.Text    = shapeGift2Object.Value;
                lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription");

                lbGift3Title.Text    = shapeGift3Object.Value;
                lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription");

                lbGift4Title.Text    = shapeGift4Object.Value;
                lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription");

                lbAbility1Title.Text    = ability1Object.Value;
                lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription");

                lbAbility2Title.Text    = ability2Object.Value;
                lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription");

                lbPeople.Text = people;
                lbPlaces.Text = places;
                lbEvents.Text = events;

                lbHeartCategories.Text = heartCategoriesString;
                lbHeartCauses.Text     = heartCauses;
                lbHeartPassion.Text    = heartPassion;

                if (spiritualGift1AttributeValue.ModifiedDateTime != null)
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString();
                }
                else
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString();
                }


                // Show create account panel if this person doesn't have an account
                if (SelectedPerson.Users.Count == 0)
                {
                    pnlAccount.Visible = true;
                }
            }
        }
コード例 #26
0
ファイル: ModelMap.ascx.cs プロジェクト: SparkDevNetwork/Rock
        private void ShowData(Guid?categoryGuid, int?entityTypeId)
        {
            if (EntityCategories == null)
            {
                LoadCategories();
            }

            hfSelectedCategoryGuid.Value = categoryGuid.ToString();
            hfSelectedEntityId.Value     = null;

            // Bind Categories
            rptCategory.DataSource = EntityCategories;
            rptCategory.DataBind();

            pnlModels.Visible  = false;
            pnlKey.Visible     = false;
            lCategoryName.Text = string.Empty;

            EntityTypeCache entityType     = null;
            var             entityTypeList = new List <EntityTypeCache>();

            if (categoryGuid.HasValue)
            {
                var category = EntityCategories.Where(c => c.Guid.Equals(categoryGuid)).FirstOrDefault();
                if (category != null)
                {
                    lCategoryName.Text = category.Name.SplitCase() + " Models";
                    pnlModels.Visible  = true;

                    entityTypeList = category
                                     .RockEntityIds
                                     .Select(a => EntityTypeCache.Get(a))
                                     .Where(a => a != null)
                                     .OrderBy(et => et.FriendlyName)
                                     .ToList();
                    if (entityTypeId.HasValue)
                    {
                        entityType = entityTypeList.Where(t => t.Id == entityTypeId.Value).FirstOrDefault();
                        hfSelectedEntityId.Value = entityType != null?entityType.Id.ToString() : null;
                    }
                    else
                    {
                        entityType = entityTypeList.FirstOrDefault();
                        hfSelectedEntityId.Value = entityTypeList.Any() ? entityTypeList.First().Id.ToString() : null;
                    }
                }
            }

            // Bind Models
            rptModel.DataSource = entityTypeList;
            rptModel.DataBind();

            string details = string.Empty;

            nbClassesWarning.Visible = false;
            pnlClassDetail.Visible   = false;
            if (entityType != null)
            {
                try
                {
                    var type = entityType.GetEntityType();
                    if (type != null)
                    {
                        pnlKey.Visible = true;

                        var xmlComments = GetXmlComments();

                        var mClass = new MClass();
                        mClass.Name    = type.Name;
                        mClass.Comment = GetComments(type, xmlComments);

                        PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                                                    .Where(m => m.MemberType == MemberTypes.Method || m.MemberType == MemberTypes.Property)
                                                    .ToArray();
                        foreach (PropertyInfo p in properties.OrderBy(i => i.Name).ToArray())
                        {
#pragma warning disable CS0618 // LavaIncludeAttribute is obsolete
                            var property = new MProperty
                            {
                                Name            = p.Name,
                                IsInherited     = p.DeclaringType != type,
                                IsVirtual       = p.GetGetMethod() != null && p.GetGetMethod().IsVirtual&& !p.GetGetMethod().IsFinal,
                                IsLavaInclude   = p.IsDefined(typeof(LavaIncludeAttribute)) || p.IsDefined(typeof(LavaVisibleAttribute)) || p.IsDefined(typeof(DataMemberAttribute)),
                                IsObsolete      = p.IsDefined(typeof(ObsoleteAttribute)),
                                ObsoleteMessage = GetObsoleteMessage(p),
                                NotMapped       = p.IsDefined(typeof(NotMappedAttribute)),
                                Required        = p.IsDefined(typeof(RequiredAttribute)),
                                Id             = p.MetadataToken,
                                Comment        = GetComments(p, xmlComments, properties),
                                IsEnum         = p.PropertyType.IsEnum,
                                IsDefinedValue = p.Name.EndsWith("ValueId") && p.IsDefined(typeof(DefinedValueAttribute))
                            };
#pragma warning restore CS0618 // LavaIncludeAttribute is obsolete

                            if (property.IsEnum)
                            {
                                property.KeyValues = new Dictionary <string, string>();
                                var values = p.PropertyType.GetEnumValues();
                                foreach (var value in values)
                                {
                                    property.KeyValues.AddOrReplace((( int )value).ToString(), value.ToString());
                                }
                            }
                            else if (property.IsDefinedValue)
                            {
                                var definedValueAttribute = p.GetCustomAttribute <Rock.Data.DefinedValueAttribute>();
                                if (definedValueAttribute != null && definedValueAttribute.DefinedTypeGuid.HasValue)
                                {
                                    property.KeyValues = new Dictionary <string, string>();
                                    var definedTypeGuid = definedValueAttribute.DefinedTypeGuid.Value;
                                    var definedType     = DefinedTypeCache.Get(definedTypeGuid);
                                    property.DefinedTypeId = definedType.Id;
                                    foreach (var definedValue in definedType.DefinedValues)
                                    {
                                        property.KeyValues.AddOrReplace(string.Format("{0} = {1}", definedValue.Id, definedValue.Value), definedValue.Description);
                                    }
                                }
                            }

                            mClass.Properties.Add(property);
                        }

                        MethodInfo[] methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                               .Where(m => !m.IsSpecialName && (m.MemberType == MemberTypes.Method || m.MemberType == MemberTypes.Property))
                                               .ToArray();
                        foreach (MethodInfo m in methods.OrderBy(i => i.Name).ToArray())
                        {
                            // crazy, right?
                            var param = string.Join(", ", m.GetParameters().Select(pi => { var x = pi.ParameterType + " " + pi.Name; return(x); }));

                            mClass.Methods.Add(new MMethod
                            {
                                Name            = m.Name,
                                IsInherited     = m.DeclaringType != type,
                                Id              = m.MetadataToken,
                                Signature       = string.Format("{0}({1})", m.Name, param),
                                Comment         = GetComments(m, xmlComments),
                                IsObsolete      = m.IsDefined(typeof(ObsoleteAttribute)),
                                ObsoleteMessage = GetObsoleteMessage(m)
                            });
                        }

                        var pageReference = new Rock.Web.PageReference(CurrentPageReference);
                        pageReference.QueryString = new System.Collections.Specialized.NameValueCollection();
                        pageReference.QueryString["EntityType"] = entityType.Guid.ToString();

                        lClassName.Text        = mClass.Name;
                        hlAnchor.NavigateUrl   = pageReference.BuildUrl();
                        lClassDescription.Text = mClass.Comment != null ? mClass.Comment.Summary : string.Empty;
                        lClasses.Text          = ClassNode(mClass);

                        pnlClassDetail.Visible = true;
                    }
                    else
                    {
                        nbClassesWarning.Text        = "Unable to get class details for " + entityType.FriendlyName;
                        nbClassesWarning.Details     = entityType.AssemblyName;
                        nbClassesWarning.Dismissable = true;
                        nbClassesWarning.Visible     = true;
                    }
                }
                catch (Exception ex)
                {
                    nbClassesWarning.Text        = string.Format("Error getting class details for <code>{0}</code>", entityType);
                    nbClassesWarning.Details     = ex.Message;
                    nbClassesWarning.Dismissable = true;
                    nbClassesWarning.Visible     = true;
                }
            }
        }
        public void RaisePostBackEvent( string eventArgument )
        {
            if ( _batch != null )
            {
                if ( eventArgument == "MoveTransactions" &&
                    _ddlMove != null &&
                    _ddlMove.SelectedValue != null &&
                    !String.IsNullOrWhiteSpace( _ddlMove.SelectedValue ) )
                {
                    var txnsSelected = new List<int>();

                    gTransactions.SelectedKeys.ToList().ForEach( b => txnsSelected.Add( b.ToString().AsInteger() ) );

                    if ( txnsSelected.Any() )
                    {
                        var rockContext = new RockContext();
                        var batchService = new FinancialBatchService( rockContext );

                        var newBatch = batchService.Get( _ddlMove.SelectedValue.AsInteger() );
                        var oldBatch = batchService.Get( _batch.Id );

                        if ( newBatch != null && newBatch.Status == BatchStatus.Open )
                        {
                            var txnService = new FinancialTransactionService( rockContext );
                            var txnsToUpdate = txnService.Queryable()
                                .Where( t => txnsSelected.Contains( t.Id ) )
                                .ToList();

                            foreach ( var txn in txnsToUpdate )
                            {
                                txn.BatchId = newBatch.Id;
                                oldBatch.ControlAmount -= txn.TotalAmount;
                                newBatch.ControlAmount += txn.TotalAmount;
                            }

                            rockContext.SaveChanges();

                            var pageRef = new Rock.Web.PageReference( RockPage.PageId );
                            pageRef.Parameters = new Dictionary<string, string>();
                            pageRef.Parameters.Add( "batchid", newBatch.Id.ToString() );
                            string newBatchLink = string.Format( "<a href='{0}'>{1}</a>",
                                pageRef.BuildUrl(), newBatch.Name );

                            RockPage.UpdateBlocks( "~/Blocks/Finance/BatchDetail.ascx" );

                            nbResult.Text = string.Format( "{0} transactions were moved to the '{1}' batch.",
                                txnsToUpdate.Count().ToString( "N0" ), newBatchLink );
                            nbResult.NotificationBoxType = NotificationBoxType.Success;
                            nbResult.Visible = true;
                        }
                        else
                        {
                            nbResult.Text = string.Format( "The selected batch does not exist, or is no longer open." );
                            nbResult.NotificationBoxType = NotificationBoxType.Danger;
                            nbResult.Visible = true;
                        }
                    }
                    else
                    {
                        nbResult.Text = string.Format( "There were not any transactions selected." );
                        nbResult.NotificationBoxType = NotificationBoxType.Warning;
                        nbResult.Visible = true;
                    }
                }

                _ddlMove.SelectedIndex = 0;
            }

            BindGrid();
        }
コード例 #28
0
        /// <summary>
        /// Handles the Click event of the 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 lbToPersonSave_Click(object sender, EventArgs e)
        {
            var context = new RockContext();
            var person  = new PersonService(context).Get(ppSource.PersonId.Value);
            var changes = new List <string>();

            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON).Id;

            History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(dvpPersonConnectionStatus.SelectedValueAsInt()));
            person.ConnectionStatusValueId = dvpPersonConnectionStatus.SelectedValueAsInt();

            History.EvaluateChange(changes, "First Name", person.FirstName, tbPersonFirstName.Text.Trim());
            person.FirstName = tbPersonFirstName.Text.Trim();

            History.EvaluateChange(changes, "Nick Name", person.NickName, tbPersonFirstName.Text.Trim());
            person.NickName = tbPersonFirstName.Text.Trim();

            History.EvaluateChange(changes, "Last Name", person.LastName, tbPersonLastName.Text.Trim());
            person.LastName = tbPersonLastName.Text.Trim();

            History.EvaluateChange(changes, "Gender", person.Gender, rblGender.SelectedValueAsEnum <Gender>());
            person.Gender = rblGender.SelectedValueAsEnum <Gender>();

            History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(dvpMaritalStatus.SelectedValueAsId()));
            person.MaritalStatusValueId = dvpMaritalStatus.SelectedValueAsId();

            context.SaveChanges();
            if (changes.Count > 0)
            {
                HistoryService.SaveChanges(context, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes);
            }

            ppSource.SetValue(null);

            var parameters = new Dictionary <string, string>
            {
                { "PersonId", person.Id.ToString() }
            };
            var pageRef = new Rock.Web.PageReference(Rock.SystemGuid.Page.PERSON_PROFILE_PERSON_PAGES, parameters);

            nbSuccess.Text = string.Format("<a href='{1}'>{0}</a> has been converted to a person.", person.FullName, pageRef.BuildUrl());

            pnlToPerson.Visible = false;
        }
コード例 #29
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            NoteWatch noteWatch;

            var rockContext      = new RockContext();
            var noteWatchService = new NoteWatchService(rockContext);
            var noteWatchId      = hfNoteWatchId.Value.AsInteger();

            if (noteWatchId == 0)
            {
                noteWatch = new NoteWatch();
                noteWatchService.Add(noteWatch);
            }
            else
            {
                noteWatch = noteWatchService.Get(noteWatchId);
            }

            noteWatch.NoteTypeId   = ddlNoteType.SelectedValue.AsIntegerOrNull();
            noteWatch.EntityTypeId = etpEntityType.SelectedEntityTypeId;

            if (noteWatch.EntityTypeId.HasValue)
            {
                if (noteWatch.EntityTypeId.Value == EntityTypeCache.GetId <Rock.Model.Person>())
                {
                    noteWatch.EntityId = ppWatchedPerson.PersonId;
                }
                else if (noteWatch.EntityTypeId.Value == EntityTypeCache.GetId <Rock.Model.Group>())
                {
                    noteWatch.EntityId = gpWatchedGroup.GroupId;
                }
                else
                {
                    noteWatch.EntityId = nbWatchedEntityId.Text.AsIntegerOrNull();
                }
            }

            noteWatch.WatcherPersonAliasId = ppWatcherPerson.PersonAliasId;
            noteWatch.WatcherGroupId       = gpWatcherGroup.GroupId;
            noteWatch.IsWatching           = cbIsWatching.Checked;
            noteWatch.AllowOverride        = cbAllowOverride.Checked;

            // see if the Watcher parameters are valid
            if (!noteWatch.IsValidWatcher)
            {
                nbWatcherMustBeSelectWarning.Visible = true;
                return;
            }

            // see if the Watch filters parameters are valid
            if (!noteWatch.IsValidWatchFilter)
            {
                nbWatchFilterMustBeSeletedWarning.Visible = true;
                return;
            }

            if (!noteWatch.IsValid)
            {
                return;
            }

            // See if there is a matching filter that doesn't allow overrides
            if (noteWatch.IsWatching == false)
            {
                if (!noteWatch.IsAbleToUnWatch(rockContext))
                {
                    var nonOverridableNoteWatch = noteWatch.GetNonOverridableNoteWatches(rockContext).FirstOrDefault();
                    if (nonOverridableNoteWatch != null)
                    {
                        string otherNoteWatchLink;
                        if (nonOverridableNoteWatch.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson))
                        {
                            var otherNoteWatchWatchPageReference = new Rock.Web.PageReference(this.CurrentPageReference);
                            otherNoteWatchWatchPageReference.QueryString = new System.Collections.Specialized.NameValueCollection(otherNoteWatchWatchPageReference.QueryString);
                            otherNoteWatchWatchPageReference.QueryString["NoteWatchId"] = nonOverridableNoteWatch.Id.ToString();
                            otherNoteWatchLink = string.Format("<a href='{0}'>note watch</a>", otherNoteWatchWatchPageReference.BuildUrl());
                        }
                        else
                        {
                            otherNoteWatchLink = "note watch";
                        }

                        nbUnableToOverride.Text = string.Format(
                            "Unable to set Watching to false. This would override another {0} that doesn't allow overrides.",
                            otherNoteWatchLink);

                        nbUnableToOverride.Visible = true;
                        return;
                    }
                }
            }

            // see if the NoteType allows following
            if (noteWatch.NoteTypeId.HasValue)
            {
                var noteTypeCache = NoteTypeCache.Get(noteWatch.NoteTypeId.Value);
                if (noteTypeCache != null)
                {
                    if (noteTypeCache.AllowsWatching == false)
                    {
                        nbNoteTypeWarning.Visible = true;
                        return;
                    }
                }
            }

            rockContext.SaveChanges();
            NavigateToNoteWatchParentPage();
        }
コード例 #30
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtFirstName.Text) ||
                string.IsNullOrWhiteSpace(txtLastName.Text) ||
                string.IsNullOrWhiteSpace(txtEmail.Text))
            {
                ShowError("Missing Information", "Please enter a value for First Name, Last Name, and Email");
            }
            else
            {
                var rockContext = new RockContext();
                var person      = GetPerson(rockContext);
                if (person != null)
                {
                    Guid?groupGuid = GetAttributeValue("Group").AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        var groupService       = new GroupService(rockContext);
                        var groupMemberService = new GroupMemberService(rockContext);

                        var group = groupService.Get(groupGuid.Value);
                        if (group != null && group.GroupType.DefaultGroupRoleId.HasValue)
                        {
                            string linkedPage = GetAttributeValue("ConfirmationPage");
                            if (!string.IsNullOrWhiteSpace(linkedPage))
                            {
                                var member = group.Members.Where(m => m.PersonId == person.Id).FirstOrDefault();

                                // If person has not registered or confirmed their registration
                                if (member == null || member.GroupMemberStatus != GroupMemberStatus.Active)
                                {
                                    Guid confirmationEmailTemplateGuid = Guid.Empty;
                                    if (!Guid.TryParse(GetAttributeValue("ConfirmationEmail"), out confirmationEmailTemplateGuid))
                                    {
                                        confirmationEmailTemplateGuid = Guid.Empty;
                                    }

                                    if (member == null)
                                    {
                                        member             = new GroupMember();
                                        member.GroupId     = group.Id;
                                        member.PersonId    = person.Id;
                                        member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;

                                        // If a confirmation email is configured, set status to Pending otherwise set it to active
                                        member.GroupMemberStatus = confirmationEmailTemplateGuid != Guid.Empty ? GroupMemberStatus.Pending : GroupMemberStatus.Active;

                                        groupMemberService.Add(member);
                                        rockContext.SaveChanges();

                                        member = groupMemberService.Get(member.Id);
                                    }

                                    // Send the confirmation
                                    if (confirmationEmailTemplateGuid != Guid.Empty)
                                    {
                                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                                        mergeFields.Add("Member", member);

                                        var pageParams = new Dictionary <string, string>();
                                        pageParams.Add("gm", member.UrlEncodedKey);
                                        var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                        mergeFields.Add("ConfirmationPage", pageReference.BuildUrl());

                                        var recipients = new List <RecipientData>();
                                        recipients.Add(new RecipientData(person.Email, mergeFields));
                                        Email.Send(confirmationEmailTemplateGuid, recipients, ResolveRockUrl("~/"), ResolveRockUrl("~~/"));
                                    }

                                    ShowSuccess(GetAttributeValue("SuccessMessage"));
                                }
                                else
                                {
                                    var pageParams = new Dictionary <string, string>();
                                    pageParams.Add("gm", member.UrlEncodedKey);
                                    var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                    Response.Redirect(pageReference.BuildUrl(), false);
                                }
                            }
                            else
                            {
                                ShowError("Configuration Error", "Invalid Confirmation Page setting");
                            }
                        }
                        else
                        {
                            ShowError("Configuration Error", "The configured group does not exist, or it's group type does not have a default role configured.");
                        }
                    }
                    else
                    {
                        ShowError("Configuration Error", "Invalid Group setting");
                    }
                }
            }
        }
コード例 #31
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList(int componentId)
        {
            int pageSize = GetAttributeValue("PageSize").AsInteger();

            int skipCount = pageNumber * pageSize;

            using (var rockContext = new RockContext())
            {
                var component = new InteractionComponentService(rockContext).Get(componentId);
                if (component != null && (UserCanEdit || component.IsAuthorized(Authorization.VIEW, CurrentPerson)))
                {
                    var interactions = new InteractionService(rockContext)
                                       .Queryable().AsNoTracking()
                                       .Where(a =>
                                              a.InteractionComponentId == componentId);

                    if (startDate != DateTime.MinValue)
                    {
                        interactions = interactions.Where(s => s.InteractionDateTime > drpDateFilter.LowerValue);
                    }

                    if (endDate != DateTime.MaxValue)
                    {
                        interactions = interactions.Where(s => s.InteractionDateTime < drpDateFilter.UpperValue);
                    }

                    if (_personId.HasValue)
                    {
                        interactions = interactions.Where(s => s.PersonAlias.PersonId == _personId);
                    }

                    interactions = interactions
                                   .OrderByDescending(a => a.InteractionDateTime)
                                   .Skip(skipCount)
                                   .Take(pageSize + 1);

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.AddOrIgnore("CurrentPerson", CurrentPerson);
                    mergeFields.Add("InteractionDetailPage", LinkedPageRoute("InteractionDetailPage"));
                    mergeFields.Add("InteractionChannel", component.Channel);
                    mergeFields.Add("InteractionComponent", component);
                    mergeFields.Add("Interactions", interactions.ToList().Take(pageSize));

                    lContent.Text = component.Channel.InteractionListTemplate.IsNotNullOrWhitespace() ?
                                    component.Channel.InteractionListTemplate.ResolveMergeFields(mergeFields) :
                                    GetAttributeValue("DefaultTemplate").ResolveMergeFields(mergeFields);

                    // set next button
                    if (interactions.Count() > pageSize)
                    {
                        Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                        queryStringNext.Add("ComponentId", componentId.ToString());
                        queryStringNext.Add("Page", (pageNumber + 1).ToString());

                        if (_personId.HasValue)
                        {
                            queryStringNext.Add("PersonId", _personId.Value.ToString());
                        }

                        if (startDate != DateTime.MinValue)
                        {
                            queryStringNext.Add("StartDate", startDate.ToShortDateString());
                        }

                        if (endDate != DateTime.MaxValue)
                        {
                            queryStringNext.Add("EndDate", endDate.ToShortDateString());
                        }

                        var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                        hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                    }
                    else
                    {
                        hlNext.Visible = hlNext.Enabled = false;
                    }

                    // set prev button
                    if (pageNumber == 0)
                    {
                        hlPrev.Visible = hlPrev.Enabled = false;
                    }
                    else
                    {
                        Dictionary <string, string> queryStringPrev = new Dictionary <string, string>();
                        queryStringPrev.Add("ComponentId", componentId.ToString());
                        queryStringPrev.Add("Page", (pageNumber - 1).ToString());

                        if (_personId.HasValue)
                        {
                            queryStringPrev.Add("PersonId", _personId.Value.ToString());
                        }

                        if (startDate != DateTime.MinValue)
                        {
                            queryStringPrev.Add("StartDate", startDate.ToShortDateString());
                        }

                        if (endDate != DateTime.MaxValue)
                        {
                            queryStringPrev.Add("EndDate", endDate.ToShortDateString());
                        }

                        var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                        hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                    }
                }
            }
        }
コード例 #32
0
        void ShowList() 
        {
            var rockContext = new RockContext();

            int sessionCount = Int32.Parse( GetAttributeValue( "SessionCount" ) );

            int skipCount = pageNumber * sessionCount;

            var person = new PersonService( rockContext ).GetByUrlEncodedKey( PageParameter( "Person" ) );
            if (person != null)
            {
                if ( GetAttributeValue( "ShowHeader" ).AsBoolean() )
                {
                    pnlHeader.Visible = true;
                    lPersonName.Text = person.FullName.FormatAsHtmlTitle() + " Page Views";
                }
                else
                {
                    pnlHeader.Visible = false;
                }

                PageViewService pageviewService = new PageViewService( rockContext );

                var pageViews = pageviewService.Queryable();
                
                var sessionInfo = pageviewService.Queryable()
                    .Where( s => s.PersonAlias.PersonId == person.Id )
                    .GroupBy( s => new { s.SessionId, s.SiteId, SiteName = s.Site.Name, s.ClientType, s.IpAddress, s.UserAgent })
                                .Select( s => new WebSession
                                {
                                                SessionId = s.Key.SessionId,
                                                StartDateTime = s.Min(x => x.DateTimeViewed),
                                                EndDateTime = s.Max(x => x.DateTimeViewed),
                                                SiteId = s.Key.SiteId,
                                                Site = s.Key.SiteName,
                                                ClientType = s.Key.ClientType,
                                                IpAddress = s.Key.IpAddress,
                                                UserAgent = s.Key.UserAgent,
                                                PageViews = pageViews.Where(p=> p.SessionId == s.Key.SessionId).ToList()
                                });

                if ( startDate != DateTime.MinValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.StartDateTime > drpDateFilter.LowerValue );
                }

                if ( endDate != DateTime.MaxValue )
                {
                    sessionInfo = sessionInfo.Where( s => s.StartDateTime < drpDateFilter.UpperValue );
                }

                if ( siteId != -1 )
                {
                    sessionInfo = sessionInfo.Where( s => s.SiteId == siteId );
                }

                sessionInfo = sessionInfo.OrderByDescending(p => p.StartDateTime)
                                .Skip( skipCount )
                                .Take( sessionCount + 1);

                rptSessions.DataSource = sessionInfo.ToList().Take(sessionCount);
                rptSessions.DataBind();

                // set next button
                if ( sessionInfo.Count() > sessionCount )
                {
                    hlNext.Visible = hlNext.Enabled = true;
                    Dictionary<string, string> queryStringNext = new Dictionary<string, string>();
                    queryStringNext.Add( "Page", (pageNumber + 1).ToString() );
                    queryStringNext.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringNext.Add( "SiteId", siteId.ToString() );
                    }
                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringNext.Add( "StartDate", startDate.ToShortDateString() );
                    }
                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringNext.Add( "EndDate", endDate.ToShortDateString() );
                    }
                    var pageReferenceNext = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext );
                    hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                }
                else
                {
                    hlNext.Visible = hlNext.Enabled = false;
                }

                // set 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() );
                    queryStringPrev.Add( "Person", person.UrlEncodedKey );
                    if ( siteId != -1 )
                    {
                        queryStringPrev.Add( "SiteId", siteId.ToString() );
                    }
                    if ( startDate != DateTime.MinValue )
                    {
                        queryStringPrev.Add( "StartDate", startDate.ToShortDateString() );
                    }
                    if ( endDate != DateTime.MaxValue )
                    {
                        queryStringPrev.Add( "EndDate", endDate.ToShortDateString() );
                    }
                    var pageReferencePrev = new Rock.Web.PageReference( CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev );
                    hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>";
            }
            
            
        }
コード例 #33
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            mdCategoryTreeConfig.Visible = false;

            bool canEditBlock = IsUserAuthorized(Authorization.EDIT);

            // hide all the actions if user doesn't have EDIT to the block
            divTreeviewActions.Visible = canEditBlock;

            var detailPageReference = new Rock.Web.PageReference(GetAttributeValue("DetailPage"));

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavior)
            if (detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId)
            {
                hfPageRouteTemplate.Value = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url;
                hfDetailPageUrl.Value     = new Rock.Web.PageReference(this.RockPage.PageId).BuildUrl().RemoveLeadingForwardslash();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Read(detailPageReference.PageId);
                if (pageCache != null)
                {
                    var route = pageCache.PageRoutes.FirstOrDefault(a => a.Id == detailPageReference.RouteId);
                    if (route != null)
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl().RemoveLeadingForwardslash();
            }

            // Get EntityTypeName
            Guid?entityTypeGuid = GetAttributeValue("EntityType").AsGuidOrNull();

            nbWarning.Text    = "Please select an entity type in the block settings.";
            nbWarning.Visible = !entityTypeGuid.HasValue;
            if (entityTypeGuid.HasValue)
            {
                int    entityTypeId             = Rock.Web.Cache.EntityTypeCache.Read(entityTypeGuid.Value).Id;
                string entityTypeQualiferColumn = GetAttributeValue("EntityTypeQualifierProperty");
                string entityTypeQualifierValue = GetAttributeValue("EntityTypeQualifierValue");
                bool   showUnnamedEntityItems   = GetAttributeValue("ShowUnnamedEntityItems").AsBooleanOrNull() ?? true;

                string parms = string.Format("?getCategorizedItems=true&showUnnamedEntityItems={0}", showUnnamedEntityItems.ToTrueFalse().ToLower());
                parms += string.Format("&entityTypeId={0}", entityTypeId);

                var rootCategory = CategoryCache.Read(this.GetAttributeValue("RootCategory").AsGuid());

                // make sure the rootCategory matches the EntityTypeId (just in case they changed the EntityType after setting RootCategory
                if (rootCategory != null && rootCategory.EntityTypeId == entityTypeId)
                {
                    parms += string.Format("&rootCategoryId={0}", rootCategory.Id);
                }

                if (!string.IsNullOrEmpty(entityTypeQualiferColumn))
                {
                    parms += string.Format("&entityQualifier={0}", entityTypeQualiferColumn);

                    if (!string.IsNullOrEmpty(entityTypeQualifierValue))
                    {
                        parms += string.Format("&entityQualifierValue={0}", entityTypeQualifierValue);
                    }
                }

                var        excludeCategoriesGuids = this.GetAttributeValue("ExcludeCategories").SplitDelimitedValues().AsGuidList();
                List <int> excludedCategoriesIds  = new List <int>();
                if (excludeCategoriesGuids != null && excludeCategoriesGuids.Any())
                {
                    foreach (var excludeCategoryGuid in excludeCategoriesGuids)
                    {
                        var excludedCategory = CategoryCache.Read(excludeCategoryGuid);
                        if (excludedCategory != null)
                        {
                            excludedCategoriesIds.Add(excludedCategory.Id);
                        }
                    }

                    parms += string.Format("&excludedCategoryIds={0}", excludedCategoriesIds.AsDelimited(","));
                }

                string defaultIconCssClass = GetAttributeValue("DefaultIconCSSClass");
                if (!string.IsNullOrWhiteSpace(defaultIconCssClass))
                {
                    parms += string.Format("&defaultIconCssClass={0}", defaultIconCssClass);
                }

                RestParms = parms;

                var cachedEntityType = Rock.Web.Cache.EntityTypeCache.Read(entityTypeId);
                if (cachedEntityType != null)
                {
                    string entityTypeFriendlyName = GetAttributeValue("EntityTypeFriendlyName");
                    if (string.IsNullOrWhiteSpace(entityTypeFriendlyName))
                    {
                        entityTypeFriendlyName = cachedEntityType.FriendlyName;
                    }

                    lbAddItem.ToolTip = "Add " + entityTypeFriendlyName;
                    lAddItem.Text     = entityTypeFriendlyName;
                }

                // Attempt to retrieve an EntityId from the Page URL parameters.
                PageParameterName = GetAttributeValue("PageParameterKey");

                string selectedNodeId = null;

                int?   itemId = PageParameter(PageParameterName).AsIntegerOrNull();
                string selectedEntityType;
                if (itemId.HasValue)
                {
                    selectedNodeId     = itemId.ToString();
                    selectedEntityType = (cachedEntityType != null) ? cachedEntityType.Name : string.Empty;
                }
                else
                {
                    // If an EntityId was not specified, check for a CategoryId.
                    itemId = PageParameter("CategoryId").AsIntegerOrNull();

                    selectedNodeId     = CategoryNodePrefix + itemId;
                    selectedEntityType = "category";
                }

                lbAddCategoryRoot.Enabled  = true;
                lbAddCategoryChild.Enabled = false;
                lbAddItem.Enabled          = false;

                CategoryCache selectedCategory = null;

                if (!string.IsNullOrEmpty(selectedNodeId))
                {
                    hfSelectedItemId.Value = selectedNodeId;
                    List <string> parentIdList = new List <string>();

                    if (selectedEntityType.Equals("category"))
                    {
                        selectedCategory = CategoryCache.Read(itemId.GetValueOrDefault());
                    }
                    else
                    {
                        if (cachedEntityType != null)
                        {
                            Type entityType = cachedEntityType.GetEntityType();
                            if (entityType != null)
                            {
                                Type         serviceType     = typeof(Rock.Data.Service <>);
                                Type[]       modelType       = { entityType };
                                Type         service         = serviceType.MakeGenericType(modelType);
                                var          serviceInstance = Activator.CreateInstance(service, new object[] { new RockContext() });
                                var          getMethod       = service.GetMethod("Get", new Type[] { typeof(int) });
                                ICategorized entity          = getMethod.Invoke(serviceInstance, new object[] { itemId }) as ICategorized;

                                if (entity != null)
                                {
                                    lbAddCategoryChild.Enabled = false;
                                    if (entity.CategoryId.HasValue)
                                    {
                                        selectedCategory = CategoryCache.Read(entity.CategoryId.Value);
                                        if (selectedCategory != null)
                                        {
                                            string categoryExpandedID = CategoryNodePrefix + selectedCategory.Id.ToString();
                                            parentIdList.Insert(0, CategoryNodePrefix + categoryExpandedID);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // get the parents of the selected item so we can tell the treeview to expand those
                    var category = selectedCategory;
                    while (category != null)
                    {
                        category = category.ParentCategory;
                        if (category != null)
                        {
                            string categoryExpandedID = CategoryNodePrefix + category.Id.ToString();
                            if (!parentIdList.Contains(categoryExpandedID))
                            {
                                parentIdList.Insert(0, categoryExpandedID);
                            }
                            else
                            {
                                // infinite recursion
                                break;
                            }
                        }
                    }
                    // also get any additional expanded nodes that were sent in the Post
                    string postedExpandedIds = this.Request.Params["ExpandedIds"];
                    if (!string.IsNullOrWhiteSpace(postedExpandedIds))
                    {
                        var postedExpandedIdList = postedExpandedIds.Split(',').ToList();
                        foreach (var id in postedExpandedIdList)
                        {
                            if (!parentIdList.Contains(id))
                            {
                                parentIdList.Add(id);
                            }
                        }
                    }

                    hfInitialCategoryParentIds.Value = parentIdList.AsDelimited(",");
                }

                selectedCategory = selectedCategory ?? rootCategory;

                if (selectedCategory != null)
                {
                    lbAddItem.Enabled          = true;
                    lbAddCategoryChild.Enabled = true;
                    this.SelectedCategoryId    = selectedCategory.Id;
                }
                else
                {
                    this.SelectedCategoryId = null;
                }
            }
        }
コード例 #34
0
        /// <summary>
        /// Handles the Click event of the btnSubmit 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 btnSubmit_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid )
            {
                var rockContext = new RockContext();
                var communication = UpdateCommunication( rockContext );

                if ( communication != null )
                {
                    var mediumControl = GetMediumControl();
                    if ( mediumControl != null )
                    {
                        mediumControl.OnCommunicationSave( rockContext );
                    }

                    if ( _editingApproved && communication.Status == CommunicationStatus.PendingApproval )
                    {
                        rockContext.SaveChanges();

                        // Redirect back to same page without the edit param
                        var pageRef = new Rock.Web.PageReference();
                        pageRef.PageId = CurrentPageReference.PageId;
                        pageRef.RouteId = CurrentPageReference.RouteId;
                        pageRef.Parameters = new Dictionary<string, string>();
                        pageRef.Parameters.Add( "CommunicationId", communication.Id.ToString() );
                        Response.Redirect( pageRef.BuildUrl() );
                        Context.ApplicationInstance.CompleteRequest();
                    }
                    else
                    {
                        string message = string.Empty;

                        // Save the communication proir to checking recipients.
                        communication.Status = CommunicationStatus.Draft;
                        rockContext.SaveChanges();

                        if ( CheckApprovalRequired( communication.GetRecipientCount(rockContext) ) && !IsUserAuthorized( "Approve" ) )
                        {
                            communication.Status = CommunicationStatus.PendingApproval;
                            message = "Communication has been submitted for approval.";
                        }
                        else
                        {
                            communication.Status = CommunicationStatus.Approved;
                            communication.ReviewedDateTime = RockDateTime.Now;
                            communication.ReviewerPersonAliasId = CurrentPersonAliasId;

                            if ( communication.FutureSendDateTime.HasValue &&
                                communication.FutureSendDateTime > RockDateTime.Now )
                            {
                                message = string.Format( "Communication will be sent {0}.",
                                    communication.FutureSendDateTime.Value.ToRelativeDateString( 0 ) );
                            }
                            else
                            {
                                message = "Communication has been queued for sending.";
                            }
                        }

                        rockContext.SaveChanges();

                        // send approval email if needed (now that we have a communication id)
                        if ( communication.Status == CommunicationStatus.PendingApproval )
                        {
                            var approvalTransaction = new Rock.Transactions.SendCommunicationApprovalEmail();
                            approvalTransaction.CommunicationId = communication.Id;
                            approvalTransaction.ApprovalPageUrl = HttpContext.Current.Request.Url.AbsoluteUri;
                            Rock.Transactions.RockQueue.TransactionQueue.Enqueue( approvalTransaction );
                        }

                        if ( communication.Status == CommunicationStatus.Approved &&
                            ( !communication.FutureSendDateTime.HasValue || communication.FutureSendDateTime.Value <= RockDateTime.Now ) )
                        {
                            if ( GetAttributeValue( "SendWhenApproved" ).AsBoolean() )
                            {
                                var transaction = new Rock.Transactions.SendCommunicationTransaction();
                                transaction.CommunicationId = communication.Id;
                                transaction.PersonAlias = CurrentPersonAlias;
                                Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction );
                            }
                        }

                        ShowResult( message, communication );
                    }
                }
            }
        }
コード例 #35
0
        /// <summary>
        /// Shows the active users.
        /// </summary>
        private void ShowActiveUsers()
        {
            int? siteId = GetAttributeValue( "Site" ).AsIntegerOrNull();
            if ( !siteId.HasValue )
            {
                lMessages.Text = "<div class='alert alert-warning'>No site is currently configured.</div>";
                return;
            }
            else
            {
                int pageViewCount = GetAttributeValue( "PageViewCount" ).AsIntegerOrNull() ?? 0;

                StringBuilder sbUsers = new StringBuilder();

                var site = SiteCache.Read( siteId.Value );
                lSiteName.Text = "<h4>" + site.Name + "</h4>";
                lSiteName.Visible = GetAttributeValue( "ShowSiteNameAsTitle" ).AsBoolean();

                if ( !site.EnablePageViews )
                {
                    lMessages.Text = "<div class='alert alert-warning'>Active " + site.Name + " users not available because page views are not enabled for site.</div>";
                    return;
                }

                lMessages.Text = string.Empty;

                using ( var rockContext = new RockContext() )
                {
                    var qryPageViews = new PageViewService( rockContext ).Queryable();
                    var qryPersonAlias = new PersonAliasService( rockContext ).Queryable();
                    var pageViewQry = qryPageViews.Join(
                        qryPersonAlias,
                        pv => pv.PersonAliasId,
                        pa => pa.Id,
                        ( pv, pa ) =>
                        new
                        {
                            PersonAliasPersonId = pa.PersonId,
                            pv.DateTimeViewed,
                            pv.SiteId,
                            pv.PageViewSessionId,
                            PagePageTitle = pv.PageTitle
                        } );

                    var last24Hours = RockDateTime.Now.AddDays( -1 );

                    int pageViewTakeCount = pageViewCount;
                    if ( pageViewTakeCount == 0 )
                    {
                        pageViewTakeCount = 1;
                    }

                    // Query to get who is logged in and last visit was to selected site
                    var activeLogins = new UserLoginService( rockContext ).Queryable()
                        .Where( l =>
                            l.PersonId.HasValue &&
                            l.IsOnLine == true )
                        .OrderByDescending( l => l.LastActivityDateTime )
                        .Select( l => new
                        {
                            login = new
                            {
                                l.UserName,
                                l.LastActivityDateTime,
                                l.PersonId,
                                Person = new
                                {
                                    l.Person.NickName,
                                    l.Person.LastName,
                                    l.Person.SuffixValueId
                                }
                            },
                            pageViews = pageViewQry
                                .Where( v => v.PersonAliasPersonId == l.PersonId )
                                .Where( v => v.DateTimeViewed > last24Hours )
                                .OrderByDescending( v => v.DateTimeViewed )
                                .Take( pageViewTakeCount )
                        } )
                        .Select( a => new
                        {
                            a.login,
                            pageViews = a.pageViews.ToList()
                        } );

                    if ( CurrentUser != null )
                    {
                        activeLogins = activeLogins.Where( m => m.login.UserName != CurrentUser.UserName );
                    }

                    foreach ( var activeLogin in activeLogins )
                    {
                        var login = activeLogin.login;

                        if ( !activeLogin.pageViews.Any() || activeLogin.pageViews.FirstOrDefault().SiteId != site.Id )
                        {
                            // only show active logins with PageViews and the most recent pageview is for the specified site
                            continue;
                        }

                        var latestPageViewSessionId = activeLogin.pageViews.FirstOrDefault().PageViewSessionId;

                        TimeSpan tsLastActivity = login.LastActivityDateTime.HasValue ? RockDateTime.Now.Subtract( login.LastActivityDateTime.Value ) : TimeSpan.MaxValue;
                        string className = tsLastActivity.Minutes <= 5 ? "recent" : "not-recent";

                        // create link to the person
                        string personFullName = Person.FormatFullName( login.Person.NickName, login.Person.LastName, login.Person.SuffixValueId );
                        string personLink = personFullName;

                        if ( GetAttributeValue( "PersonProfilePage" ) != null )
                        {
                            string personProfilePage = GetAttributeValue( "PersonProfilePage" );
                            var pageParams = new Dictionary<string, string>();
                            pageParams.Add( "PersonId", login.PersonId.ToString() );
                            var pageReference = new Rock.Web.PageReference( personProfilePage, pageParams );
                            personLink = string.Format( @"<a href='{0}'>{1}</a>", pageReference.BuildUrl(), personFullName );
                        }

                        // determine whether to show last page views
                        if ( GetAttributeValue( "PageViewCount" ).AsInteger() > 0 )
                        {
                            string format = @"
            <li class='active-user {0}' data-toggle='tooltip' data-placement='top' title='{2}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            if ( activeLogin.pageViews != null )
                            {
                                string pageViewsHtml = activeLogin.pageViews
                                                    .Where( v => v.PageViewSessionId == latestPageViewSessionId )
                                                    .Select( v => HttpUtility.HtmlEncode( v.PagePageTitle ) ).ToList().AsDelimited( "<br> " );

                                sbUsers.Append( string.Format( format, className, personLink, pageViewsHtml ) );
                            }
                        }
                        else
                        {
                            string format = @"
            <li class='active-user {0}'>
            <i class='fa-li fa fa-circle'></i> {1}
            </li>";
                            sbUsers.Append( string.Format( format, className, personLink ) );
                        }
                    }
                }

                if ( sbUsers.Length > 0 )
                {
                    lUsers.Text = string.Format( @"<ul class='activeusers fa-ul'>{0}</ul>", sbUsers.ToString() );
                }
                else
                {
                    lMessages.Text = string.Format( "There are no logged in users on the {0} site.", site.Name );
                }
            }
        }
コード例 #36
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            var rockContext = new RockContext();

            int sessionCount = GetAttributeValue("SessionCount").AsInteger();

            int skipCount = pageNumber * sessionCount;

            Person person     = null;
            Guid?  personGuid = PageParameter("PersonGuid").AsGuidOrNull();

            // NOTE: Since this block shows a history of sites a person visited in Rock, require Person.Guid instead of Person.Id to reduce the risk of somebody manually editing the URL to see somebody else pageview history
            if (personGuid.HasValue)
            {
                person = new PersonService(rockContext).Get(personGuid.Value);
            }
            else if (!string.IsNullOrEmpty(PageParameter("Person")))
            {
                // Just in case Person (Person Token) was used, look up by Impersonation Token
                person = new PersonService(rockContext).GetByImpersonationToken(PageParameter("Person"), false, this.PageCache.Id);
            }

            if (person != null)
            {
                lPersonName.Text = person.FullName;

                InteractionService interactionService = new InteractionService(rockContext);

                var pageViews = interactionService.Queryable();

                var sessionInfo = interactionService.Queryable()
                                  .Where(s => s.PersonAlias.PersonId == person.Id);

                if (startDate != DateTime.MinValue)
                {
                    sessionInfo = sessionInfo.Where(s => s.InteractionDateTime > drpDateFilter.LowerValue);
                }

                if (endDate != DateTime.MaxValue)
                {
                    sessionInfo = sessionInfo.Where(s => s.InteractionDateTime < drpDateFilter.UpperValue);
                }

                if (siteId != -1)
                {
                    var site = SiteCache.Get(siteId);

                    string siteName = string.Empty;
                    if (site != null)
                    {
                        siteName = site.Name;
                    }
                    // lookup the interactionDeviceType, and create it if it doesn't exist
                    int channelMediumValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;

                    var interactionChannelId = new InteractionChannelService(rockContext).Queryable()
                                               .Where(a => a.ChannelTypeMediumValueId == channelMediumValueId && a.ChannelEntityId == siteId)
                                               .Select(a => a.Id)
                                               .FirstOrDefault();

                    sessionInfo = sessionInfo.Where(p => p.InteractionComponent.ChannelId == interactionChannelId);
                }

                var pageviewInfo = sessionInfo.GroupBy(s => new
                {
                    s.InteractionSession,
                    s.InteractionComponent.Channel,
                })
                                   .Select(s => new WebSession
                {
                    PageViewSession = s.Key.InteractionSession,
                    StartDateTime   = s.Min(x => x.InteractionDateTime),
                    EndDateTime     = s.Max(x => x.InteractionDateTime),
                    SiteId          = siteId,
                    Site            = s.Key.Channel.Name,
                    PageViews       = pageViews.Where(p => p.InteractionSessionId == s.Key.InteractionSession.Id && p.InteractionComponent.ChannelId == s.Key.Channel.Id).OrderBy(p => p.InteractionDateTime).ToList()
                });

                pageviewInfo = pageviewInfo.OrderByDescending(p => p.StartDateTime)
                               .Skip(skipCount)
                               .Take(sessionCount + 1);

                rptSessions.DataSource = pageviewInfo.ToList().Take(sessionCount);
                rptSessions.DataBind();

                // set next button
                if (pageviewInfo.Count() > sessionCount)
                {
                    hlNext.Visible = hlNext.Enabled = true;
                    Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                    queryStringNext.Add("Page", (pageNumber + 1).ToString());
                    queryStringNext.Add("Person", person.UrlEncodedKey);
                    if (siteId != -1)
                    {
                        queryStringNext.Add("SiteId", siteId.ToString());
                    }

                    if (startDate != DateTime.MinValue)
                    {
                        queryStringNext.Add("StartDate", startDate.ToShortDateString());
                    }

                    if (endDate != DateTime.MaxValue)
                    {
                        queryStringNext.Add("EndDate", endDate.ToShortDateString());
                    }

                    var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                    hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                }
                else
                {
                    hlNext.Visible = hlNext.Enabled = false;
                }

                // set 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());
                    queryStringPrev.Add("Person", person.UrlEncodedKey);
                    if (siteId != -1)
                    {
                        queryStringPrev.Add("SiteId", siteId.ToString());
                    }

                    if (startDate != DateTime.MinValue)
                    {
                        queryStringPrev.Add("StartDate", startDate.ToShortDateString());
                    }

                    if (endDate != DateTime.MaxValue)
                    {
                        queryStringPrev.Add("EndDate", endDate.ToShortDateString());
                    }

                    var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                    hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>";
            }
        }
コード例 #37
0
        /// <summary>
        /// Handles the Click event of the 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 lbToPersonSave_Click(object sender, EventArgs e)
        {
            var context = new RockContext();
            var person  = new PersonService(context).Get(ppSource.PersonId.Value);

            person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON).Id;
            person.ConnectionStatusValueId = dvpPersonConnectionStatus.SelectedValueAsInt();
            person.FirstName            = tbPersonFirstName.Text.Trim();
            person.NickName             = tbPersonFirstName.Text.Trim();
            person.LastName             = tbPersonLastName.Text.Trim();
            person.Gender               = rblGender.SelectedValueAsEnum <Gender>();
            person.MaritalStatusValueId = dvpMaritalStatus.SelectedValueAsId();

            context.SaveChanges();

            ppSource.SetValue(null);

            var parameters = new Dictionary <string, string>
            {
                { "PersonId", person.Id.ToString() }
            };
            var pageRef = new Rock.Web.PageReference(Rock.SystemGuid.Page.PERSON_PROFILE_PERSON_PAGES, parameters);

            nbSuccess.Text = string.Format("The business formerly known as <a href='{1}'>{0}</a> has been converted to a person.", person.FullName, pageRef.BuildUrl());

            pnlToPerson.Visible = false;
        }
コード例 #38
0
        void ShowList()
        {
            var rockContext = new RockContext();

            int sessionCount = Int32.Parse(GetAttributeValue("SessionCount"));

            int skipCount = pageNumber * sessionCount;

            var person = new PersonService(rockContext).GetByUrlEncodedKey(PageParameter("Person"));

            if (person != null)
            {
                lPersonName.Text = person.FullName;

                PageViewService pageviewService = new PageViewService(rockContext);

                var pageViews = pageviewService.Queryable();

                var sessionInfo = pageviewService.Queryable()
                                  .Where(s => s.PersonAlias.PersonId == person.Id);


                if (startDate != DateTime.MinValue)
                {
                    sessionInfo = sessionInfo.Where(s => s.DateTimeViewed > drpDateFilter.LowerValue);
                }

                if (endDate != DateTime.MaxValue)
                {
                    sessionInfo = sessionInfo.Where(s => s.DateTimeViewed < drpDateFilter.UpperValue);
                }

                if (siteId != -1)
                {
                    sessionInfo = sessionInfo.Where(p => p.SiteId == siteId);
                }

                var pageviewInfo = sessionInfo.GroupBy(s => new { s.SessionId, s.SiteId, SiteName = s.Site.Name, s.ClientType, s.IpAddress, s.UserAgent })
                                   .Select(s => new WebSession
                {
                    SessionId     = s.Key.SessionId,
                    StartDateTime = s.Min(x => x.DateTimeViewed),
                    EndDateTime   = s.Max(x => x.DateTimeViewed),
                    SiteId        = s.Key.SiteId,
                    Site          = s.Key.SiteName,
                    ClientType    = s.Key.ClientType,
                    IpAddress     = s.Key.IpAddress,
                    UserAgent     = s.Key.UserAgent,
                    PageViews     = pageViews.Where(p => p.SessionId == s.Key.SessionId && p.SiteId == s.Key.SiteId).ToList()
                });

                pageviewInfo = pageviewInfo.OrderByDescending(p => p.StartDateTime)
                               .Skip(skipCount)
                               .Take(sessionCount + 1);

                rptSessions.DataSource = pageviewInfo.ToList().Take(sessionCount);
                rptSessions.DataBind();

                // set next button
                if (pageviewInfo.Count() > sessionCount)
                {
                    hlNext.Visible = hlNext.Enabled = true;
                    Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                    queryStringNext.Add("Page", (pageNumber + 1).ToString());
                    queryStringNext.Add("Person", person.UrlEncodedKey);
                    if (siteId != -1)
                    {
                        queryStringNext.Add("SiteId", siteId.ToString());
                    }
                    if (startDate != DateTime.MinValue)
                    {
                        queryStringNext.Add("StartDate", startDate.ToShortDateString());
                    }
                    if (endDate != DateTime.MaxValue)
                    {
                        queryStringNext.Add("EndDate", endDate.ToShortDateString());
                    }
                    var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                    hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                }
                else
                {
                    hlNext.Visible = hlNext.Enabled = false;
                }

                // set 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());
                    queryStringPrev.Add("Person", person.UrlEncodedKey);
                    if (siteId != -1)
                    {
                        queryStringPrev.Add("SiteId", siteId.ToString());
                    }
                    if (startDate != DateTime.MinValue)
                    {
                        queryStringPrev.Add("StartDate", startDate.ToShortDateString());
                    }
                    if (endDate != DateTime.MaxValue)
                    {
                        queryStringPrev.Add("EndDate", endDate.ToShortDateString());
                    }
                    var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                    hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                }
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No person provided to show results for.</div>";
            }
        }
コード例 #39
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click( object sender, EventArgs e )
        {
            if ( string.IsNullOrWhiteSpace( txtFirstName.Text ) ||
                string.IsNullOrWhiteSpace( txtLastName.Text ) ||
                string.IsNullOrWhiteSpace( txtEmail.Text ) )
            {
                ShowError( "Missing Information", "Please enter a value for First Name, Last Name, and Email" );
            }
            else
            {
                var rockContext = new RockContext();
                var person = GetPerson( rockContext );
                if ( person != null )
                {
                    Guid? groupGuid = GetAttributeValue( "Group" ).AsGuidOrNull();

                    if ( groupGuid.HasValue )
                    {
                        var groupService = new GroupService( rockContext );
                        var groupMemberService = new GroupMemberService( rockContext );

                        var group = groupService.Get( groupGuid.Value );
                        if ( group != null && group.GroupType.DefaultGroupRoleId.HasValue )
                        {
                            string linkedPage = GetAttributeValue( "ConfirmationPage" );
                            if ( !string.IsNullOrWhiteSpace( linkedPage ) )
                            {
                                var member = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault();

                                // If person has not registered or confirmed their registration
                                if ( member == null || member.GroupMemberStatus != GroupMemberStatus.Active )
                                {
                                    Guid confirmationEmailTemplateGuid = Guid.Empty;
                                    if ( !Guid.TryParse( GetAttributeValue( "ConfirmationEmail" ), out confirmationEmailTemplateGuid ) )
                                    {
                                        confirmationEmailTemplateGuid = Guid.Empty;
                                    }

                                    if ( member == null )
                                    {
                                        member = new GroupMember();
                                        member.GroupId = group.Id;
                                        member.PersonId = person.Id;
                                        member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;

                                        // If a confirmation email is configured, set status to Pending otherwise set it to active
                                        member.GroupMemberStatus = confirmationEmailTemplateGuid != Guid.Empty ? GroupMemberStatus.Pending : GroupMemberStatus.Active;

                                        groupMemberService.Add( member );
                                        rockContext.SaveChanges();

                                        member = groupMemberService.Get( member.Id );
                                    }

                                    // Send the confirmation
                                    if ( confirmationEmailTemplateGuid != Guid.Empty )
                                    {
                                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson );
                                        mergeFields.Add( "Member", member );

                                        var pageParams = new Dictionary<string, string>();
                                        pageParams.Add( "gm", member.UrlEncodedKey );
                                        var pageReference = new Rock.Web.PageReference( linkedPage, pageParams );
                                        mergeFields.Add( "ConfirmationPage", pageReference.BuildUrl() );

                                        var recipients = new List<RecipientData>();
                                        recipients.Add( new RecipientData( person.Email, mergeFields ) );
                                        Email.Send( confirmationEmailTemplateGuid, recipients, ResolveRockUrl( "~/" ), ResolveRockUrl( "~~/" ) );
                                    }

                                    ShowSuccess( GetAttributeValue( "SuccessMessage" ) );
                                }
                                else
                                {
                                    var pageParams = new Dictionary<string, string>();
                                    pageParams.Add( "gm", member.UrlEncodedKey );
                                    var pageReference = new Rock.Web.PageReference( linkedPage, pageParams );
                                    Response.Redirect( pageReference.BuildUrl(), false );
                                }
                            }
                            else
                            {
                                ShowError( "Configuration Error", "Invalid Confirmation Page setting" );
                            }
                        }
                        else
                        {
                            ShowError( "Configuration Error", "The configured group does not exist, or it's group type does not have a default role configured." );
                        }
                    }
                    else
                    {
                        ShowError( "Configuration Error", "Invalid Group setting" );
                    }
                }
            }
        }
コード例 #40
0
        /// <summary>
        /// Adds or updates the given person into the given group.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="group">The group.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddOrUpdatePersonInGroup( Person person, Group group, RockContext rockContext )
        {
            try
            {
                var groupMember = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault();
                if ( groupMember == null )
                {
                    groupMember = new GroupMember();
                    groupMember.GroupId = group.Id;
                    groupMember.PersonId = person.Id;
                    groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId ?? 0;
                    group.Members.Add( groupMember );
                }
                var groupMemberStatus = GetAttributeValue( "GroupMemberStatus" );
                groupMember.GroupMemberStatus = (GroupMemberStatus)groupMemberStatus.AsInteger();
                rockContext.SaveChanges();

                // Now update any member attributes for the person...
                AddOrUpdateGroupMemberAttributes( person, group, rockContext );

                string successPage = GetAttributeValue( "SuccessPage" );
                if ( ! string.IsNullOrWhiteSpace( successPage ) )
                {
                    var pageReference = new Rock.Web.PageReference( successPage );
                    Response.Redirect( pageReference.BuildUrl(), false );
                    // this remaining stuff prevents .NET from quietly throwing ThreadAbortException
                    Context.ApplicationInstance.CompleteRequest();
                    return;
                }
                else
                {
                    lSuccess.Visible = true;
                    lSuccess.Text = GetAttributeValue( "SuccessMessage" );
                }
            }
            catch ( Exception ex )
            {
                LogException( ex );
                nbMessage.Visible = true;
                nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbMessage.Text = "Something went wrong and we could not save your request. If it happens again please contact our office at the number below.";
            }
        }
コード例 #41
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            int sessionCount = GetAttributeValue("SessionCount").AsInteger();

            int skipCount = pageNumber * sessionCount;

            using (var rockContext = new RockContext())
            {
                var interactionChannel = new InteractionChannelService(rockContext).Get(_channelId.Value);
                if (interactionChannel != null)
                {
                    var interactionService = new InteractionService(rockContext);

                    // Start the interaction qry to filter on those that belong to selected channel and have a valid person and session
                    var interactionQry = interactionService
                                         .Queryable().AsNoTracking()
                                         .Where(a =>
                                                a.InteractionComponent.ChannelId == _channelId.Value &&
                                                a.PersonAliasId.HasValue &&
                                                a.InteractionSessionId.HasValue);

                    // Filter by start date
                    if (startDate != DateTime.MinValue)
                    {
                        interactionQry = interactionQry.Where(s => s.InteractionDateTime > drpDateFilter.LowerValue);
                    }

                    // Filter by end date
                    if (endDate != DateTime.MaxValue)
                    {
                        interactionQry = interactionQry.Where(s => s.InteractionDateTime < drpDateFilter.UpperValue);
                    }

                    // Filter by person
                    if (_personId.HasValue)
                    {
                        interactionQry = interactionQry.Where(s => s.PersonAlias.PersonId == _personId.Value);
                    }

                    // Select minimal data to speed up query and group the interactions by the session id
                    var grpInteractions = interactionQry
                                          .Select(i => new
                    {
                        i.Id,
                        i.InteractionDateTime,
                        i.InteractionSessionId
                    })
                                          .GroupBy(s => s.InteractionSessionId.Value)
                                          .Select(s => new WebSession
                    {
                        InteractionSessionId = s.Key,
                        StartDateTime        = s.Min(x => x.InteractionDateTime),
                        EndDateTime          = s.Max(x => x.InteractionDateTime),
                    });

                    // Skip/Take only the sessions for the currently selected page number
                    var webSessions = grpInteractions.OrderByDescending(p => p.EndDateTime)
                                      .Skip(skipCount)
                                      .Take(sessionCount + 1)
                                      .ToList();

                    // Now that we know the sessions, requery for all of the interaction data just for these sessions
                    var pageSessionIds          = webSessions.Select(s => s.InteractionSessionId).ToList();
                    var currentPageInteractions = interactionQry
                                                  .Where(i => pageSessionIds.Contains(i.InteractionSessionId.Value))
                                                  .ToList();
                    foreach (var webSession in webSessions)
                    {
                        var sessionInteractions = currentPageInteractions
                                                  .Where(i =>
                                                         i.InteractionSessionId.Value == webSession.InteractionSessionId)
                                                  .ToList();
                        if (sessionInteractions.Any())
                        {
                            webSession.Interactions = sessionInteractions;

                            var firstInteraction = sessionInteractions.First();
                            if (firstInteraction != null)
                            {
                                webSession.PersonAlias        = firstInteraction.PersonAlias;
                                webSession.InteractionSession = firstInteraction.InteractionSession;
                            }
                        }
                    }

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.Add("ComponentDetailPage", LinkedPageRoute("ComponentDetailPage"));
                    mergeFields.Add("InteractionDetailPage", LinkedPageRoute("InteractionDetailPage"));
                    mergeFields.Add("InteractionChannel", interactionChannel);
                    mergeFields.Add("WebSessions", webSessions.Take(sessionCount));

                    lContent.Text = interactionChannel.SessionListTemplate.IsNotNullOrWhiteSpace() ?
                                    interactionChannel.SessionListTemplate.ResolveMergeFields(mergeFields) :
                                    GetAttributeValue("DefaultTemplate").ResolveMergeFields(mergeFields);

                    // set next button
                    if (webSessions.Count() > sessionCount)
                    {
                        hlNext.Visible = hlNext.Enabled = true;
                        Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                        queryStringNext.Add("ChannelId", _channelId.ToString());
                        queryStringNext.Add("Page", (pageNumber + 1).ToString());

                        if (_personId.HasValue)
                        {
                            queryStringNext.Add("PersonId", _personId.Value.ToString());
                        }

                        if (startDate != DateTime.MinValue)
                        {
                            queryStringNext.Add("StartDate", startDate.ToShortDateString());
                        }

                        if (endDate != DateTime.MaxValue)
                        {
                            queryStringNext.Add("EndDate", endDate.ToShortDateString());
                        }

                        var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                        hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                    }
                    else
                    {
                        hlNext.Visible = hlNext.Enabled = false;
                    }

                    // set 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("ChannelId", _channelId.ToString());
                        queryStringPrev.Add("Page", (pageNumber - 1).ToString());

                        if (_personId.HasValue)
                        {
                            queryStringPrev.Add("PersonId", _personId.Value.ToString());
                        }

                        if (startDate != DateTime.MinValue)
                        {
                            queryStringPrev.Add("StartDate", startDate.ToShortDateString());
                        }

                        if (endDate != DateTime.MaxValue)
                        {
                            queryStringPrev.Add("EndDate", endDate.ToShortDateString());
                        }

                        var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                        hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                    }
                }
            }
        }
コード例 #42
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            _groupId = PageParameter("GroupId");

            var detailPageReference = new Rock.Web.PageReference(GetAttributeValue("DetailPage"));

            // NOTE: if the detail page is the current page, use the current route instead of route specified in the DetailPage (to preserve old behavoir)
            if (detailPageReference == null || detailPageReference.PageId == this.RockPage.PageId)
            {
                hfPageRouteTemplate.Value = (this.RockPage.RouteData.Route as System.Web.Routing.Route).Url;
                hfDetailPageUrl.Value     = new Rock.Web.PageReference(this.RockPage.PageId).BuildUrl();
            }
            else
            {
                hfPageRouteTemplate.Value = string.Empty;
                var pageCache = PageCache.Read(detailPageReference.PageId);
                if (pageCache != null)
                {
                    var route = pageCache.PageRoutes.FirstOrDefault(a => a.Id == detailPageReference.RouteId);
                    if (route != null)
                    {
                        hfPageRouteTemplate.Value = route.Route;
                    }
                }

                hfDetailPageUrl.Value = detailPageReference.BuildUrl();
            }

            hfLimitToSecurityRoleGroups.Value = GetAttributeValue("LimittoSecurityRoleGroups");
            Guid?rootGroupGuid = GetAttributeValue("RootGroup").AsGuidOrNull();

            if (rootGroupGuid.HasValue)
            {
                var group = new GroupService(new RockContext()).Get(rootGroupGuid.Value);
                if (group != null)
                {
                    hfRootGroupId.Value = group.Id.ToString();
                }
            }

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upGroupType);

            pnlConfigPanel.Visible    = this.GetAttributeValue("ShowFilterOption").AsBooleanOrNull() ?? false;
            pnlRolloverConfig.Visible = this.GetAttributeValue("ShowFilterOption").AsBooleanOrNull() ?? false;

            if (pnlConfigPanel.Visible)
            {
                var hideInactiveGroups = this.GetUserPreference("HideInactiveGroups").AsBooleanOrNull();
                if (!hideInactiveGroups.HasValue)
                {
                    hideInactiveGroups = this.GetAttributeValue("InitialActiveSetting") == "1";
                }

                tglHideInactiveGroups.Checked = hideInactiveGroups ?? true;
            }
            else
            {
                // if the filter is hidden, don't show inactive groups
                tglHideInactiveGroups.Checked = true;
            }

            ddlCountsType.Items.Clear();
            ddlCountsType.Items.Add(new ListItem(string.Empty, TreeViewItem.GetCountsType.None.ConvertToInt().ToString()));
            ddlCountsType.Items.Add(new ListItem(TreeViewItem.GetCountsType.ChildGroups.ConvertToString(), TreeViewItem.GetCountsType.ChildGroups.ConvertToInt().ToString()));
            ddlCountsType.Items.Add(new ListItem(TreeViewItem.GetCountsType.GroupMembers.ConvertToString(), TreeViewItem.GetCountsType.GroupMembers.ConvertToInt().ToString()));

            var countsType = this.GetUserPreference("CountsType");

            if (string.IsNullOrEmpty(countsType))
            {
                countsType = this.GetAttributeValue("InitialCountSetting");
            }

            if (pnlConfigPanel.Visible)
            {
                ddlCountsType.SetValue(countsType);
            }
            else
            {
                ddlCountsType.SetValue("");
            }
        }
コード例 #43
0
        /// <summary>
        /// Shows the list.
        /// </summary>
        public void ShowList()
        {
            int sessionCount = GetAttributeValue("SessionCount").AsInteger();

            int skipCount = pageNumber * sessionCount;

            using (var rockContext = new RockContext())
            {
                var interactionChannel = new InteractionChannelService(rockContext).Get(_channelId.Value);
                if (interactionChannel != null)
                {
                    var interactionQry = new InteractionService(rockContext)
                                         .Queryable().AsNoTracking()
                                         .Where(a =>
                                                a.InteractionComponent.ChannelId == _channelId.Value &&
                                                a.PersonAliasId.HasValue &&
                                                a.InteractionSessionId.HasValue);

                    if (startDate != DateTime.MinValue)
                    {
                        interactionQry = interactionQry.Where(s => s.InteractionDateTime > drpDateFilter.LowerValue);
                    }

                    if (endDate != DateTime.MaxValue)
                    {
                        interactionQry = interactionQry.Where(s => s.InteractionDateTime < drpDateFilter.UpperValue);
                    }

                    if (selectedPersonAlias.HasValue)
                    {
                        interactionQry = interactionQry.Where(s => s.PersonAliasId == selectedPersonAlias);
                    }

                    var grpInteractions = interactionQry
                                          .GroupBy(s => new
                    {
                        s.InteractionSession
                    })
                                          .Select(s => new WebSession
                    {
                        PersonAlias        = s.Where(a => a.PersonAliasId != null).Select(a => a.PersonAlias).FirstOrDefault(),
                        InteractionSession = s.Key.InteractionSession,
                        StartDateTime      = s.Min(x => x.InteractionDateTime),
                        EndDateTime        = s.Max(x => x.InteractionDateTime),
                        Interactions       = s.ToList()
                    });

                    var webSessions = grpInteractions.OrderByDescending(p => p.EndDateTime)
                                      .Skip(skipCount)
                                      .Take(sessionCount + 1);

                    var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                    mergeFields.Add("ComponentDetailPage", LinkedPageRoute("ComponentDetailPage"));
                    mergeFields.Add("InteractionDetailPage", LinkedPageRoute("InteractionDetailPage"));
                    mergeFields.Add("InteractionChannel", interactionChannel);
                    mergeFields.Add("WebSessions", webSessions.ToList().Take(sessionCount));

                    lContent.Text = interactionChannel.SessionListTemplate.IsNotNullOrWhitespace() ?
                                    interactionChannel.SessionListTemplate.ResolveMergeFields(mergeFields) :
                                    GetAttributeValue("DefaultTemplate").ResolveMergeFields(mergeFields);

                    // set next button
                    if (webSessions.Count() > sessionCount)
                    {
                        hlNext.Visible = hlNext.Enabled = true;
                        Dictionary <string, string> queryStringNext = new Dictionary <string, string>();
                        queryStringNext.Add("ChannelId", _channelId.ToString());
                        queryStringNext.Add("Page", (pageNumber + 1).ToString());

                        if (selectedPersonAlias.HasValue)
                        {
                            queryStringNext.Add("PersonAlias", selectedPersonAlias.Value.ToString());
                        }

                        if (startDate != DateTime.MinValue)
                        {
                            queryStringNext.Add("StartDate", startDate.ToShortDateString());
                        }

                        if (endDate != DateTime.MaxValue)
                        {
                            queryStringNext.Add("EndDate", endDate.ToShortDateString());
                        }

                        var pageReferenceNext = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringNext);
                        hlNext.NavigateUrl = pageReferenceNext.BuildUrl();
                    }
                    else
                    {
                        hlNext.Visible = hlNext.Enabled = false;
                    }

                    // set 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("ChannelId", _channelId.ToString());
                        queryStringPrev.Add("Page", (pageNumber - 1).ToString());

                        if (selectedPersonAlias.HasValue)
                        {
                            queryStringPrev.Add("PersonAlias", selectedPersonAlias.Value.ToString());
                        }

                        if (startDate != DateTime.MinValue)
                        {
                            queryStringPrev.Add("StartDate", startDate.ToShortDateString());
                        }

                        if (endDate != DateTime.MaxValue)
                        {
                            queryStringPrev.Add("EndDate", endDate.ToShortDateString());
                        }

                        var pageReferencePrev = new Rock.Web.PageReference(CurrentPageReference.PageId, CurrentPageReference.RouteId, queryStringPrev);
                        hlPrev.NavigateUrl = pageReferencePrev.BuildUrl();
                    }
                }
            }
        }
コード例 #44
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // this event gets fired after block settings are updated. it's nice to repaint the screen if these settings would alter it
            this.BlockUpdated += Block_BlockUpdated;
            this.AddConfigurationUpdateTrigger(upnlContent);

            var pageReference = new Rock.Web.PageReference(this.PageCache.Id);

            pageReference.QueryString = new System.Collections.Specialized.NameValueCollection();
            pageReference.QueryString.Add(this.Request.QueryString);
            pageReference.QueryString.Add("GetChartData", "true");
            pageReference.QueryString.Add("GetChartDataBlockId", this.BlockId.ToString());
            pageReference.QueryString.Add("TimeStamp", RockDateTime.Now.ToJavascriptMilliseconds().ToString());
            lcLineChart.DataSourceUrl = pageReference.BuildUrl();
            lcLineChart.ChartHeight   = this.GetAttributeValue("ChartHeight").AsIntegerOrNull() ?? 200;
            lcLineChart.Options.SetChartStyle(this.GetAttributeValue("ChartStyle").AsGuidOrNull());
            lcLineChart.Options.legend          = lcLineChart.Options.legend ?? new Legend();
            lcLineChart.Options.legend.show     = this.GetAttributeValue("ShowLegend").AsBooleanOrNull();
            lcLineChart.Options.legend.position = this.GetAttributeValue("LegendPosition");

            bcBarChart.DataSourceUrl = pageReference.BuildUrl();
            bcBarChart.ChartHeight   = this.GetAttributeValue("ChartHeight").AsIntegerOrNull() ?? 200;
            bcBarChart.Options.SetChartStyle(this.GetAttributeValue("ChartStyle").AsGuidOrNull());
            bcBarChart.Options.xaxis = new AxisOptions {
                mode = AxisMode.categories, tickLength = 0
            };
            bcBarChart.Options.series.bars.barWidth = 0.6;
            bcBarChart.Options.series.bars.align    = "center";

            bcBarChart.Options.legend          = lcLineChart.Options.legend ?? new Legend();
            bcBarChart.Options.legend.show     = this.GetAttributeValue("ShowLegend").AsBooleanOrNull();
            bcBarChart.Options.legend.position = this.GetAttributeValue("LegendPosition");

            pcPieChart.DataSourceUrl = pageReference.BuildUrl();
            pcPieChart.ChartHeight   = this.GetAttributeValue("ChartHeight").AsIntegerOrNull() ?? 200;
            pcPieChart.Options.SetChartStyle(this.GetAttributeValue("ChartStyle").AsGuidOrNull());

            pcPieChart.PieOptions.label = new PieLabel {
                show = this.GetAttributeValue("PieShowLabels").AsBooleanOrNull() ?? true
            };
            pcPieChart.PieOptions.label.formatter = @"
function labelFormatter(label, series) {
	return ""<div style='font-size:8pt; text-align:center; padding:2px; '>"" + label + ""<br/>"" + Math.round(series.percent) + ""%</div>"";
}
".Trim();
            pcPieChart.Legend.show = this.GetAttributeValue("ShowLegend").AsBooleanOrNull();

            pcPieChart.PieOptions.innerRadius = this.GetAttributeValue("PieInnerRadius").AsDoubleOrNull();

            lcLineChart.Visible = false;
            bcBarChart.Visible  = false;
            pcPieChart.Visible  = false;
            var chartType = this.GetAttributeValue("ChartType");

            if (chartType == "Pie")
            {
                pcPieChart.Visible = true;
            }
            else if (chartType == "Bar")
            {
                bcBarChart.Visible = true;
            }
            else
            {
                lcLineChart.Visible = true;
            }

            pnlDashboardTitle.Visible    = !string.IsNullOrEmpty(this.Title);
            pnlDashboardSubtitle.Visible = !string.IsNullOrEmpty(this.Subtitle);
            lDashboardTitle.Text         = this.Title;
            lDashboardSubtitle.Text      = this.Subtitle;

            var sql = this.GetAttributeValue("SQL");

            if (string.IsNullOrWhiteSpace(sql))
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text    = "SQL needs to be configured in block settings";
            }
            else
            {
                nbConfigurationWarning.Visible = false;
            }

            if (PageParameter("GetChartData").AsBoolean() && (PageParameter("GetChartDataBlockId").AsInteger() == this.BlockId))
            {
                GetChartData();
            }
        }
コード例 #45
0
        /// <summary>
        /// Handles the Click event of the 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 lbToBusinessSave_Click(object sender, EventArgs e)
        {
            var context = new RockContext();
            var person  = new PersonService(context).Get(ppSource.PersonId.Value);

            person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS).Id;
            person.ConnectionStatusValueId = null;
            person.TitleValueId            = null;
            person.FirstName     = null;
            person.NickName      = null;
            person.MiddleName    = null;
            person.LastName      = tbBusinessName.Text.Trim();
            person.SuffixValueId = null;
            person.SetBirthDate(null);
            person.Gender = Gender.Unknown;
            person.MaritalStatusValueId = null;
            person.AnniversaryDate      = null;
            person.GraduationYear       = null;

            //
            // Check address(es) and make sure one is of type Work.
            //
            var family = person.GetFamily(context);

            if (family.GroupLocations.Count > 0)
            {
                var workLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;
                var homeLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;

                var workLocation = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == workLocationTypeId).FirstOrDefault();
                if (workLocation == null)
                {
                    var homeLocation = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationTypeId).FirstOrDefault();
                    if (homeLocation != null)
                    {
                        homeLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                }
            }

            //
            // Check phone(es) and make sure one is of type Work.
            //
            if (person.PhoneNumbers.Count > 0)
            {
                var workPhoneTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK).Id;
                var homePhoneTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME).Id;

                var workPhone = person.PhoneNumbers.Where(pn => pn.NumberTypeValueId == workPhoneTypeId).FirstOrDefault();
                if (workPhone == null)
                {
                    var homePhone = person.PhoneNumbers.Where(pn => pn.NumberTypeValueId == homePhoneTypeId).FirstOrDefault();
                    if (homePhone != null)
                    {
                        homePhone.NumberTypeValueId = workPhoneTypeId;
                    }
                }
            }

            //
            // Make sure member status in family is set to Adult.
            //
            var adultRoleId = GroupTypeCache.GetFamilyGroupType().Roles
                              .Where(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid())
                              .Select(a => a.Id).First();

            family.Members.Where(m => m.PersonId == person.Id).First().GroupRoleId = adultRoleId;

            context.SaveChanges();

            ppSource.SetValue(null);

            var parameters = new Dictionary <string, string>
            {
                { "BusinessId", person.Id.ToString() }
            };
            var pageRef = new Rock.Web.PageReference(Rock.SystemGuid.Page.BUSINESS_DETAIL, parameters);

            nbSuccess.Text = string.Format("The person formerly known as <a href='{1}'>{0}</a> has been converted to a business.", person.LastName, pageRef.BuildUrl());

            pnlToBusiness.Visible = false;
        }
コード例 #46
0
ファイル: ShapeResults.ascx.cs プロジェクト: NewPointe/Rockit
        protected void Page_Load(object sender, EventArgs e)
        {
            var shapePageReference = new Rock.Web.PageReference(GetAttributeValue("SHAPEAssessmentPage"));
            var discPageReference = new Rock.Web.PageReference(GetAttributeValue("DISCAssessmentPage"));

            if (!string.IsNullOrWhiteSpace(PageParameter("FormId")))
                {
                    //Load the person based on the FormId
                    var personInUrl = PageParameter("FormId");
                    SelectedPerson = GetPersonFromForm(personInUrl);
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                }

                else if (!string.IsNullOrWhiteSpace(PageParameter("PersonId")))
                {
                    //Load the person based on the PersonId
                    SelectedPerson = GetPersonFromId(PageParameter("PersonId"));
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                 }

                else if (CurrentPerson != null)
                {
                    //Load the person based on the currently logged in person
                    SelectedPerson = CurrentPerson;
                    PersonEncodedKey = SelectedPerson.UrlEncodedKey;
                }

                else
                {
                    //Show Error Message
                    nbNoPerson.Visible = true;
                    Response.Redirect(shapePageReference.BuildUrl(), true);
                    return;
                }

            // Load the attributes

            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            DefinedValueService definedValueService = new DefinedValueService(rockContext);

            string spiritualGift1 = "";
            string spiritualGift2 = "";
            string spiritualGift3 = "";
            string spiritualGift4 = "";
            string heartCategories = "";
            string heartCauses = "";
            string heartPassion = "";
            string ability1 = "";
            string ability2 = "";
            string people = "";
            string places = "";
            string events = "";

            var spiritualGift1AttributeValue =
                attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift1" && a.EntityId == SelectedPerson.Id);

            // Redirect if they haven't taken the Assessment
            if (spiritualGift1AttributeValue == null)
            {
                Response.Redirect(shapePageReference.BuildUrl(), true);
            }

            else
            {
                var spiritualGift2AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift2" && a.EntityId == SelectedPerson.Id);

                var spiritualGift3AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift3" && a.EntityId == SelectedPerson.Id);

                var spiritualGift4AttributeValue =
              attributeValueService
                  .Queryable()
                  .FirstOrDefault(a => a.Attribute.Key == "SpiritualGift4" && a.EntityId == SelectedPerson.Id);

                var ability1AttributeValue =
                    attributeValueService
                        .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability1" && a.EntityId == SelectedPerson.Id);

                var ability2AttributeValue =
                    attributeValueService
                        .Queryable().FirstOrDefault(a => a.Attribute.Key == "Ability2" && a.EntityId == SelectedPerson.Id);

                var peopleAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEPeople" && a.EntityId == SelectedPerson.Id);

                var placesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEPlaces" && a.EntityId == SelectedPerson.Id);

                var eventsAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "SHAPEEvents" && a.EntityId == SelectedPerson.Id);

                var heartCategoriesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartCategories" && a.EntityId == SelectedPerson.Id);

                var heartCausesAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartCauses" && a.EntityId == SelectedPerson.Id);

                var heartPassionAttributeValue = attributeValueService
                    .Queryable()
                    .FirstOrDefault(a => a.Attribute.Key == "HeartPassion" && a.EntityId == SelectedPerson.Id);

                if (spiritualGift1AttributeValue.Value != null) spiritualGift1 = spiritualGift1AttributeValue.Value;
                if (spiritualGift2AttributeValue.Value != null) spiritualGift2 = spiritualGift2AttributeValue.Value;
                if (spiritualGift3AttributeValue.Value != null) spiritualGift3 = spiritualGift3AttributeValue.Value;
                if (spiritualGift4AttributeValue.Value != null) spiritualGift4 = spiritualGift4AttributeValue.Value;
                if (heartCategoriesAttributeValue.Value != null) heartCategories = heartCategoriesAttributeValue.Value;
                if (heartCausesAttributeValue.Value != null) heartCauses = heartCausesAttributeValue.Value;
                if (heartPassionAttributeValue.Value != null) heartPassion = heartPassionAttributeValue.Value;
                if (ability1AttributeValue.Value != null) ability1 = ability1AttributeValue.Value;
                if (ability2AttributeValue.Value != null) ability2 = ability2AttributeValue.Value;
                if (peopleAttributeValue.Value != null) people = peopleAttributeValue.Value;
                if (placesAttributeValue.Value != null) places = placesAttributeValue.Value;
                if (eventsAttributeValue.Value != null) events = eventsAttributeValue.Value;

                string spiritualGift1Guid;
                string spiritualGift2Guid;
                string spiritualGift3Guid;
                string spiritualGift4Guid;
                string ability1Guid;
                string ability2Guid;

                // Check to see if there are already values saved as an ID.  If so, convert them to GUID
                if (spiritualGift1.ToString().Length < 5)
                {
                    if (spiritualGift1 != null) SpiritualGift1 = Int32.Parse(spiritualGift1);
                    if (spiritualGift2 != null) SpiritualGift2 = Int32.Parse(spiritualGift2);
                    if (spiritualGift3 != null) SpiritualGift3 = Int32.Parse(spiritualGift3);
                    if (spiritualGift4 != null) SpiritualGift4 = Int32.Parse(spiritualGift4);
                    if (ability1 != null) Ability1 = Int32.Parse(ability1);
                    if (ability2 != null) Ability2 = Int32.Parse(ability2);

                    var intsOfGifts =
                        definedValueService.GetByIds(new List<int>
                        {
                            SpiritualGift1,
                            SpiritualGift2,
                            SpiritualGift3,
                            SpiritualGift4,
                            Ability1,
                            Ability2
                        });

                    spiritualGift1Guid = intsOfGifts.ToList()[SpiritualGift1].Guid.ToString();
                    spiritualGift2Guid = intsOfGifts.ToList()[SpiritualGift2].Guid.ToString();
                    spiritualGift3Guid = intsOfGifts.ToList()[SpiritualGift3].Guid.ToString();
                    spiritualGift4Guid = intsOfGifts.ToList()[SpiritualGift4].Guid.ToString();
                    ability1Guid = intsOfGifts.ToList()[Ability1].Guid.ToString();
                    ability2Guid = intsOfGifts.ToList()[Ability2].Guid.ToString();
                }
                else
                {
                    spiritualGift1Guid = spiritualGift1;
                    spiritualGift2Guid = spiritualGift2;
                    spiritualGift3Guid = spiritualGift3;
                    spiritualGift4Guid = spiritualGift4;
                    ability1Guid = ability1;
                    ability2Guid = ability2;
                }

                // Get all of the data about the assiciated gifts and ability categories
                var shapeGift1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift1Guid) }).FirstOrDefault();
                var shapeGift2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift2Guid) }).FirstOrDefault();
                var shapeGift3Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift3Guid) }).FirstOrDefault();
                var shapeGift4Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(spiritualGift4Guid) }).FirstOrDefault();
                var ability1Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability1Guid) }).FirstOrDefault();
                var ability2Object = definedValueService.GetListByGuids(new List<Guid> { new Guid(ability2Guid) }).FirstOrDefault();

                shapeGift1Object.LoadAttributes();
                shapeGift2Object.LoadAttributes();
                shapeGift3Object.LoadAttributes();
                shapeGift4Object.LoadAttributes();
                ability1Object.LoadAttributes();
                ability2Object.LoadAttributes();

                // Get heart choices Values from Guids
                string heartCategoriesString = "";
                if (!heartCategories.IsNullOrWhiteSpace())
                {
                    string[] heartCategoryArray = heartCategories.Split(',');
                    foreach (string category in heartCategoryArray)
                    {
                        var definedValueObject =
                            definedValueService.Queryable().FirstOrDefault(a => a.Guid == new Guid(category));

                        if (category.Equals(heartCategoryArray.Last()))
                        {
                            heartCategoriesString += definedValueObject.Value;
                        }
                        else
                        {
                            heartCategoriesString += definedValueObject.Value + ", ";
                        }
                    }

                }

                // Get Volunteer Opportunities

                string gift1AssociatedVolunteerOpportunities =
                    shapeGift1Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift2AssociatedVolunteerOpportunities =
                    shapeGift2Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift3AssociatedVolunteerOpportunities =
                    shapeGift3Object.GetAttributeValue("AssociatedVolunteerOpportunities");
                string gift4AssociatedVolunteerOpportunities =
                    shapeGift4Object.GetAttributeValue("AssociatedVolunteerOpportunities");

                string allAssociatedVolunteerOpportunities = gift1AssociatedVolunteerOpportunities + "," +
                                                             gift2AssociatedVolunteerOpportunities + "," +
                                                             gift3AssociatedVolunteerOpportunities + "," +
                                                             gift4AssociatedVolunteerOpportunities;

                if (allAssociatedVolunteerOpportunities != ",,,")
                {
                    List<int> associatedVolunteerOpportunitiesList =
                        allAssociatedVolunteerOpportunities.Split(',').Select(t => int.Parse(t)).ToList();
                    Dictionary<int, int> VolunteerOpportunities = new Dictionary<int, int>();

                    var i = 0;
                    var q = from x in associatedVolunteerOpportunitiesList
                            group x by x
                        into g
                            let count = g.Count()
                            orderby count descending
                            select new { Value = g.Key, Count = count };
                    foreach (var x in q)
                    {
                        VolunteerOpportunities.Add(i, x.Value);
                        i++;
                    }

                    ConnectionOpportunityService connectionOpportunityService = new ConnectionOpportunityService(rockContext);
                    List<ConnectionOpportunity> connectionOpportunityList = new List<ConnectionOpportunity>();

                    foreach (KeyValuePair<int, int> entry in VolunteerOpportunities.Take(4))
                    {
                        var connection = connectionOpportunityService.GetByIds(new List<int> { entry.Value }).FirstOrDefault();

                        // Only display connection if it is marked Active
                        if (connection.IsActive == true)
                        {
                            connectionOpportunityList.Add(connection);
                        }

                    }

                    rpVolunteerOpportunities.DataSource = connectionOpportunityList;
                    rpVolunteerOpportunities.DataBind();
                }

                //Get DISC Info

                DiscService.AssessmentResults savedScores = DiscService.LoadSavedAssessmentResults(SelectedPerson);

                if (!string.IsNullOrWhiteSpace(savedScores.PersonalityType))
                {
                    ShowResults(savedScores);
                    DISCResults.Visible = true;
                    NoDISCResults.Visible = false;

                }
                else
                {
                    discPageReference.Parameters = new System.Collections.Generic.Dictionary<string, string>();
                    discPageReference.Parameters.Add("rckipid", SelectedPerson.UrlEncodedKey);
                    Response.Redirect(discPageReference.BuildUrl(), true);
                }

                // Build the UI

                lbPersonName.Text = SelectedPerson.FullName;

                lbGift1Title.Text = shapeGift1Object.Value;
                lbGift1BodyHTML.Text = shapeGift1Object.GetAttributeValue("HTMLDescription");

                lbGift2Title.Text = shapeGift2Object.Value;
                lbGift2BodyHTML.Text = shapeGift2Object.GetAttributeValue("HTMLDescription");

                lbGift3Title.Text = shapeGift3Object.Value;
                lbGift3BodyHTML.Text = shapeGift3Object.GetAttributeValue("HTMLDescription");

                lbGift4Title.Text = shapeGift4Object.Value;
                lbGift4BodyHTML.Text = shapeGift4Object.GetAttributeValue("HTMLDescription");

                lbAbility1Title.Text = ability1Object.Value;
                lbAbility1BodyHTML.Text = ability1Object.GetAttributeValue("HTMLDescription");

                lbAbility2Title.Text = ability2Object.Value;
                lbAbility2BodyHTML.Text = ability2Object.GetAttributeValue("HTMLDescription");

                lbPeople.Text = people;
                lbPlaces.Text = places;
                lbEvents.Text = events;

                lbHeartCategories.Text = heartCategoriesString;
                lbHeartCauses.Text = heartCauses;
                lbHeartPassion.Text = heartPassion;

                if (spiritualGift1AttributeValue.ModifiedDateTime != null)
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.ModifiedDateTime.Value.ToShortDateString();
                }
                else
                {
                    lbAssessmentDate.Text = spiritualGift1AttributeValue.CreatedDateTime.Value.ToShortDateString();
                }

                // Show create account panel if this person doesn't have an account
                if (SelectedPerson.Users.Count == 0)
                {
                    pnlAccount.Visible = true;
                }

            }
        }
コード例 #47
0
        protected void btnSave_Click( object sender, EventArgs e )
        {
            if ( string.IsNullOrWhiteSpace( txtFirstName.Text ) ||
                string.IsNullOrWhiteSpace( txtLastName.Text ) ||
                string.IsNullOrWhiteSpace( txtEmail.Text ) )
            {
                ShowError( "Missing Information", "Please enter a value for First Name, Last Name, and Email" );
            }
            else
            {
                var person = GetPerson();
                if ( person != null )
                {
                    int groupId = int.MinValue;
                    if ( int.TryParse( GetAttributeValue( "Group" ), out groupId ) )
                    {
                        using ( new UnitOfWorkScope() )
                        {
                            var groupService = new GroupService();
                            var groupMemberService = new GroupMemberService();

                            var group = groupService.Get( groupId );
                            if ( group != null && group.GroupType.DefaultGroupRoleId.HasValue )
                            {
                                string linkedPage = GetAttributeValue( "ConfirmationPage" );
                                if ( !string.IsNullOrWhiteSpace( linkedPage ) )
                                {
                                    var member = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault();

                                    // If person has not registered or confirmed their registration
                                    if ( member == null || member.GroupMemberStatus != GroupMemberStatus.Active )
                                    {
                                        Email email = null;

                                        Guid guid = Guid.Empty;
                                        if ( Guid.TryParse( GetAttributeValue( "ConfirmationEmail" ), out guid ) )
                                        {
                                            email = new Email( guid );
                                        }

                                        if ( member == null )
                                        {
                                            member = new GroupMember();
                                            member.GroupId = group.Id;
                                            member.PersonId = person.Id;
                                            member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;

                                            // If a confirmation email is configured, set status to Pending otherwise set it to active
                                            member.GroupMemberStatus = email != null ? GroupMemberStatus.Pending : GroupMemberStatus.Active;

                                            groupMemberService.Add( member, CurrentPersonId );
                                            groupMemberService.Save( member, CurrentPersonId );
                                            member = groupMemberService.Get( member.Id );
                                        }

                                        // Send the confirmation
                                        if ( email != null )
                                        {
                                            var mergeObjects = new Dictionary<string, object>();
                                            mergeObjects.Add( "Member", member );

                                            var pageParams = new Dictionary<string, string>();
                                            pageParams.Add( "gm", member.UrlEncodedKey );
                                            var pageReference = new Rock.Web.PageReference( linkedPage, pageParams );
                                            mergeObjects.Add( "ConfirmationPage", pageReference.BuildUrl() );

                                            var recipients = new Dictionary<string, Dictionary<string, object>>();
                                            recipients.Add( person.Email, mergeObjects );
                                            email.Send( recipients );
                                        }

                                        ShowSuccess( GetAttributeValue( "SuccessMessage" ) );

                                    }
                                    else
                                    {
                                        var pageParams = new Dictionary<string, string>();
                                        pageParams.Add( "gm", member.UrlEncodedKey );
                                        var pageReference = new Rock.Web.PageReference( linkedPage, pageParams );
                                        Response.Redirect( pageReference.BuildUrl(), false );
                                    }
                                }
                                else
                                {
                                    ShowError( "Configuration Error", "Invalid Confirmation Page setting" );
                                }
                            }
                            else
                            {
                                ShowError( "Configuration Error",
                                    "The configured group does not exist, or it's group type does not have a default role configured." );
                            }
                        }
                    }
                    else
                    {
                        ShowError( "Configuration Error", "Invalid Group setting" );
                    }
                }
            }
        }