/// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <Rock.Web.UI.BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            string pageTitle = "New " + SystemCommunication.FriendlyTypeName;

            // Get the CommunicationId if it is specified as a parameter.
            // If not found, check for the legacy parameter "EmailId".
            var communicationIdentifier = PageParameter(PageParameterKey.CommunicationId);

            if (string.IsNullOrEmpty(communicationIdentifier))
            {
                communicationIdentifier = PageParameter("emailId");
            }

            int?communicationId = communicationIdentifier.AsIntegerOrNull();

            if (communicationId.HasValue)
            {
                var communication = new SystemCommunicationService(new RockContext()).Get(communicationId.Value);

                if (communication != null)
                {
                    pageTitle = communication.Title;
                    breadCrumbs.Add(new BreadCrumb(communication.Title, pageReference));
                }
            }

            RockPage.Title = pageTitle;

            return(breadCrumbs);
        }
Example #2
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);

            _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);
        }
Example #3
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;
        }
        //  overrides of the base RockBlock methods (i.e. OnInit, OnLoad)
        /// <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 );

            // Notify the Rock Administrators that an obsolete block is being used
            try
            {
                var pageReference = new Rock.Web.PageReference( GetAttributeValue( "WorkflowEntryPage" ) );
                string subject = string.Format( "Your '{0}' site is using an obsolete block!", RockPage.Site.Name );
                string message = string.Format( @"Your '{0}' site is still using the 'Activate Workflow' block on page:
            {1}!<br/><br/>The Activate Workflow block has been deprecated and will be removed during a future update.
            This block was previously used to activate a workflow, set attribute values from any existing query string parameters,
            and then redirect the user to a page with the Workflow Entry block. Because the Workflow Entry block now also
            supports setting attribute values from query string parameters, the Activate Workflow block is no
            longer needed.<br/><br/>Please update any place that links to page ID: {1}, to instead link directly to the Workflow
            Entry page (Page ID: {2}).", RockPage.Site.Name, RockPage.PageId, pageReference.PageId );
                Rock.Communication.Email.NotifyAdmins( subject, message, string.Empty, string.Empty, false );
            }
            catch ( Exception ex )
            {
                ExceptionLogService.LogException( ex, System.Web.HttpContext.Current );
            }

            // Pass all the query string parameters to the entry page
            var pageParams = new Dictionary<string, string>();
            foreach( var param in PageParameters())
            {
                pageParams.Add( param.Key, param.Value.ToString() );
            }
            NavigateToLinkedPage( "WorkflowEntryPage", pageParams );
        }
        /// <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());
                }
            }
        }
Example #6
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);
        }
        //  overrides of the base RockBlock methods (i.e. OnInit, OnLoad)

        /// <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);

            // Notify the Rock Administrators that an obsolete block is being used
            try
            {
                var    pageReference = new Rock.Web.PageReference(GetAttributeValue("WorkflowEntryPage"));
                string subject       = string.Format("Your '{0}' site is using an obsolete block!", RockPage.Site.Name);
                string message       = string.Format(@"Your '{0}' site is still using the 'Activate Workflow' block on page:
{1}!<br/><br/>The Activate Workflow block has been deprecated and will be removed during a future update. 
This block was previously used to activate a workflow, set attribute values from any existing query string parameters, 
and then redirect the user to a page with the Workflow Entry block. Because the Workflow Entry block now also 
supports setting attribute values from query string parameters, the Activate Workflow block is no 
longer needed.<br/><br/>Please update any place that links to page ID: {1}, to instead link directly to the Workflow 
Entry page (Page ID: {2}).", RockPage.Site.Name, RockPage.PageId, pageReference.PageId);
                Rock.Communication.Email.NotifyAdmins(subject, message, string.Empty, string.Empty, false);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
            }

            // Pass all the query string parameters to the entry page
            var pageParams = new Dictionary <string, string>();

            foreach (var param in PageParameters())
            {
                pageParams.Add(param.Key, param.Value.ToString());
            }
            NavigateToLinkedPage("WorkflowEntryPage", pageParams);
        }
        /// <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;
            }
        }
Example #9
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);
                }
            }
        }
Example #10
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("AddTransactionPage"));

            if (addTransactionPage != null)
            {
                // create a limited-use personkey that will last long enough for them to go thru all the 'postbacks' while posting a transaction
                var personKey = this.Person.GetImpersonationToken(DateTime.Now.AddMinutes(this.GetAttributeValue("PersonTokenExpireMinutes").AsIntegerOrNull() ?? 60), this.GetAttributeValue("PersonTokenUsageLimit").AsIntegerOrNull(), addTransactionPage.PageId);
                Response.Redirect(string.Format("~/AddTransaction?Person={0}", personKey));
            }
        }
Example #11
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;
            }
        }
        /// <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);
                }
            }
        }
Example #13
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);
            }
        }
Example #14
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            LoadWorkflowType();

            if (_workflowType != null && !ConfiguredType)
            {
                breadCrumbs.Add(new BreadCrumb(_workflowType.Name, pageReference));
            }

            return(breadCrumbs);
        }
Example #15
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);
            }
        }
Example #16
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            var workflowTypeId = PageParameter("WorkflowTypeId").AsInteger();

            _workflowType = new WorkflowTypeService(new RockContext()).Get(workflowTypeId);
            if (_workflowType != null)
            {
                breadCrumbs.Add(new BreadCrumb(_workflowType.Name, pageReference));
            }

            return(breadCrumbs);
        }
        /// <summary>
        /// Handles the Add event of the gList 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 gList_Add(object sender, EventArgs e)
        {
            var parms = new Dictionary <string, string>();
            var addScheduledTransactionPage = new Rock.Web.PageReference(GetAttributeValue("AddPage"));

            if (addScheduledTransactionPage != null)
            {
                // create a limited-use personkey that will last long enough for them to go thru all the 'postbacks' while posting a transaction
                if (this.TargetPerson != null)
                {
                    var impersonationToken = this.TargetPerson.GetImpersonationToken(DateTime.Now.AddMinutes(this.GetAttributeValue("PersonTokenExpireMinutes").AsIntegerOrNull() ?? 60), this.GetAttributeValue("PersonTokenUsageLimit").AsIntegerOrNull(), addScheduledTransactionPage.PageId);
                    parms.Add("Person", impersonationToken);
                }
            }

            NavigateToLinkedPage("AddPage", parms);
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);


            if (Settings.Entity() == null)
            {
                nbConfigurationWarning.Visible = true;
                nbConfigurationWarning.Text    = "The connection opportunities, partitions, and display settings need to be configured in block settings.";
            }

            if (!IsPostBack)
            {
                ceLava.Text = GetAttributeValue("Lava");
            }

            if (Settings.Partitions.Count > 0)
            {
                ConnectionOpportunity connection = ( ConnectionOpportunity )Settings.Entity();
                if (connection != null && connectionRequests == null)
                {
                    connectionRequests = connection.ConnectionRequests;
                }

                var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                mergeFields.Add("Settings", Rock.Lava.RockFilters.FromJSON(GetAttributeValue("Settings")));
                string url = "";
                if (Settings.SignupPage() != null)
                {
                    url = new Rock.Web.PageReference(Settings.SignupPage().Id).BuildUrl();
                    if (Settings.EntityTypeGuid == Rock.SystemGuid.EntityType.CONNECTION_OPPORTUNITY.AsGuid())
                    {
                        url += "?OpportunityId=" + Settings.Entity().Id;
                    }
                }
                mergeFields.Add("Tree", GetTree(Settings.Partitions.FirstOrDefault(), connectionRequests, parentUrl: url));
                mergeFields.Add("ConnectionRequests", connectionRequests);
                lBody.Text = GetAttributeValue("Lava").ResolveMergeFields(mergeFields);

                if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
                {
                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo();
                }
            }
        }
Example #19
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;
        }
        /// <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.";
            }
        }
Example #21
0
        /// <summary>
        /// Handles the ItemDataBound event of the rptrMembers control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void rptrMembers_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                var groupMember = e.Item.DataItem as GroupMember;
                if (groupMember != null && groupMember.Person != null)
                {
                    Person gm = groupMember.Person;

                    HtmlControl imgPersonImage = e.Item.FindControl("imgPersonImage") as HtmlControl;
                    if (imgPersonImage != null)
                    {
                        imgPersonImage.Attributes.Add("src", Person.GetPersonPhotoUrl(gm));
                    }

                    HtmlControl personLink = e.Item.FindControl("personLink") as HtmlControl;
                    if (personLink != null)
                    {
                        string linkedPage = GetAttributeValue("PersonDetailPage");
                        if (!string.IsNullOrWhiteSpace(linkedPage))
                        {
                            var pageReference = new Rock.Web.PageReference();
                            if (personId != null)
                            {
                                var pageParams = new Dictionary <string, string>();
                                pageParams.Add("PersonId", gm.Id.ToString());

                                pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                            }
                            else if (personGuid != null)
                            {
                                var pageParams = new Dictionary <string, string>();
                                pageParams.Add("Person", gm.Guid.ToString());

                                pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                            }
                            personLink.Attributes.Add("href", pageReference.BuildUrl());
                        }
                    }
                }
            }
        }
        public override List <BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            string crumbName = ActionTitle.Add(ReferralAgency.FriendlyTypeName);

            int?referralAgencyId = PageParameter("referralAgencyId").AsInteger(false);

            if (referralAgencyId.HasValue)
            {
                _referralAgency = new ReferralAgencyService(new SampleProjectContext()).Get(referralAgencyId.Value);
                if (_referralAgency != null)
                {
                    crumbName = _referralAgency.Name;
                }
            }

            breadCrumbs.Add(new BreadCrumb(crumbName, pageReference));

            return(breadCrumbs);
        }
Example #23
0
        public override List<Rock.Web.UI.BreadCrumb> GetBreadCrumbs( Rock.Web.PageReference pageReference )
        {
            var breadCrumbs = new List<BreadCrumb>();
            
            string pageTitle = "New Tag";
            
            int? tagId = PageParameter( "tagId" ).AsIntegerOrNull();
            if (tagId.HasValue)
            {
                Tag tag = new TagService( new RockContext() ).Get( tagId.Value );
                if (tag != null)
                {
                    pageTitle = tag.Name;
                    breadCrumbs.Add( new BreadCrumb( tag.Name, pageReference ) );
                }
            }

            RockPage.Title = pageTitle;

            return breadCrumbs;
        }
Example #24
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <Rock.Web.UI.BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            string pageTitle = "New System Email";

            int?emailId = PageParameter("EmailId").AsIntegerOrNull();

            if (emailId.HasValue)
            {
                SystemEmail email = new SystemEmailService(new RockContext()).Get(emailId.Value);
                if (email != null)
                {
                    pageTitle = email.Title;
                    breadCrumbs.Add(new BreadCrumb(email.Title, pageReference));
                }
            }

            RockPage.Title = pageTitle;

            return(breadCrumbs);
        }
Example #25
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <Rock.Web.UI.BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            string pageTitle = "New Communication";

            int?commId = PageParameter("CommunicationId").AsIntegerOrNull();

            if (commId.HasValue)
            {
                var communication = new CommunicationService(new RockContext()).Get(commId.Value);
                if (communication != null)
                {
                    RockPage.SaveSharedItem("communication", communication);

                    switch (communication.Status)
                    {
                    case CommunicationStatus.Approved:
                    case CommunicationStatus.Denied:
                    case CommunicationStatus.PendingApproval:
                    {
                        pageTitle = communication.Name ?? string.Format("Communication #{0}", communication.Id);
                        break;
                    }

                    default:
                    {
                        pageTitle = "New Communication";
                        break;
                    }
                    }
                }
            }

            breadCrumbs.Add(new BreadCrumb(pageTitle, pageReference));
            RockPage.Title = pageTitle;

            return(breadCrumbs);
        }
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <Rock.Web.UI.BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            string pageTitle = "New Template";

            int?templateId = PageParameter("TemplateId").AsInteger(false);

            if (templateId.HasValue)
            {
                var template = new CommunicationTemplateService(new RockContext()).Get(templateId.Value);
                if (template != null)
                {
                    pageTitle = template.Name;
                }
            }

            breadCrumbs.Add(new BreadCrumb(pageTitle, pageReference));
            RockPage.Title = pageTitle;

            return(breadCrumbs);
        }
Example #27
0
        /// <summary>
        /// Returns breadcrumbs specific to the block that should be added to navigation
        /// based on the current page reference.  This function is called during the page's
        /// oninit to load any initial breadcrumbs.
        /// </summary>
        /// <param name="pageReference">The <see cref="Rock.Web.PageReference" />.</param>
        /// <returns>
        /// A <see cref="System.Collections.Generic.List{BreadCrumb}" /> of block related <see cref="Rock.Web.UI.BreadCrumb">BreadCrumbs</see>.
        /// </returns>
        public override List <BreadCrumb> GetBreadCrumbs(Rock.Web.PageReference pageReference)
        {
            var breadCrumbs = new List <BreadCrumb>();

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("DefaultWorkflowType")))
            {
                Guid workflowTypeGuid = Guid.Empty;
                Guid.TryParse(GetAttributeValue("DefaultWorkflowType"), out workflowTypeGuid);
                _workflowType = new WorkflowTypeService(new RockContext()).Get(workflowTypeGuid);
            }
            else
            {
                int workflowTypeId = 0;
                workflowTypeId = PageParameter("WorkflowTypeId").AsInteger();
                _workflowType  = new WorkflowTypeService(new RockContext()).Get(workflowTypeId);
            }

            if (_workflowType != null)
            {
                breadCrumbs.Add(new BreadCrumb(_workflowType.Name, pageReference));
            }

            return(breadCrumbs);
        }
Example #28
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;
                }
            }
        }
        /// <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;
        }
Example #30
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;
                }
            }
        }
Example #31
0
        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;
                }
            }
        }
Example #32
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();
        }
        /// <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 );
                }
            }
        }
Example #34
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>";
            }
        }
        /// <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" );
                    }
                }
            }
        }
Example #36
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 );
                }
            }
        }
        /// <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;
                }
            }
        }
Example #38
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();
            }
        }
Example #39
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( "" );
            }
        }
Example #40
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>";
            }
            
            
        }
        /// <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.";
            }
        }
 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();
         }
     }
 }
Example #43
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("");
            }
        }
        /// <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 );
                    }
                }
            }
        }
Example #45
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();
            }
        }
        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();
        }
Example #47
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;
                }

            }
        }
Example #48
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" );
                    }
                }
            }
        }