Beispiel #1
0
        /// <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)
        {
            int        blockId = Convert.ToInt32(PageParameter("BlockId"));
            BlockCache _block  = BlockCache.Read(blockId);

            if (!Page.IsPostBack && _block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
            {
                rptProperties.DataSource = GetTabs(_block.BlockType);
                rptProperties.DataBind();

                tbBlockName.Text = _block.Name;
                tbCssClass.Text  = _block.CssClass;
                cePreHtml.Text   = _block.PreHtml;
                cePostHtml.Text  = _block.PostHtml;

                // Hide the Cache duration block for now;
                tbCacheDuration.Visible = false;
                //tbCacheDuration.Text = _block.OutputCacheDuration.ToString();

                CustomGridColumnsConfigState = _block.GetAttributeValue(CustomGridColumnsConfig.AttributeKey).FromJsonOrNull <CustomGridColumnsConfig>() ?? new CustomGridColumnsConfig();

                BindCustomColumnsConfig();
            }

            base.OnLoad(e);
        }
        //private BlockCache _block = null;
        //private string _zoneName = string.Empty;

        /// <summary>
        /// Raises the <see cref="E:Init" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            Rock.Web.UI.DialogMasterPage masterPage = this.Page.Master as Rock.Web.UI.DialogMasterPage;
            if (masterPage != null)
            {
                masterPage.OnSave += new EventHandler <EventArgs>(masterPage_OnSave);
            }

            try
            {
                int        blockId = Convert.ToInt32(PageParameter("BlockId"));
                BlockCache _block  = BlockCache.Read(blockId);

                if (_block.IsAuthorized("Administrate", CurrentPerson))
                {
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls(_block, phAttributes, !Page.IsPostBack);
                }
                else
                {
                    DisplayError("You are not authorized to edit this block");
                }
            }
            catch (SystemException ex)
            {
                DisplayError(ex.Message);
            }

            base.OnInit(e);
        }
Beispiel #3
0
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        /// <param name="answer">The answer text.</param>
        /// <returns>
        /// The response to send back to the client.
        /// </returns>
        private CallbackResponse SaveRequest(string answer)
        {
            using (var rockContext = new RockContext())
            {
                var           prayerRequestService = new PrayerRequestService(rockContext);
                PrayerRequest prayerRequest        = null;
                var           requestGuid          = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();

                if (requestGuid.HasValue)
                {
                    prayerRequest = new PrayerRequestService(rockContext).Get(requestGuid.Value);
                }

                if (prayerRequest == null)
                {
                    return(new CallbackResponse
                    {
                        Error = "We couldn't find that prayer request."
                    });
                }

                var canEdit = prayerRequest.RequestedByPersonAlias != null && prayerRequest.RequestedByPersonAlias.PersonId == RequestContext.CurrentPerson?.Id;

                if (!BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !canEdit)
                {
                    return(new CallbackResponse
                    {
                        Error = "You are not authorized to edit prayer requests."
                    });
                }

                prayerRequest.Answer = answer;

                //
                // Save all changes to database.
                //
                rockContext.SaveChanges();
            }

            if (ReturnPageGuid.HasValue)
            {
                return(new CallbackResponse
                {
                    Command = "ReplacePage",
                    CommandParameter = ReturnPageGuid.Value.ToString()
                });
            }
            else
            {
                return(new CallbackResponse
                {
                    Command = "PopPage",
                    CommandParameter = "true"
                });
            }
        }
Beispiel #4
0
        /// <summary>
        /// Builds the content to be displayed on the block.
        /// </summary>
        /// <returns>A string containing the XAML content to be displayed.</returns>
        private string BuildContent()
        {
            using (var rockContext = new RockContext())
            {
                Guid?         requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();
                PrayerRequest request     = null;

                if (requestGuid.HasValue)
                {
                    request = new PrayerRequestService(rockContext).Get(requestGuid.Value);
                }

                if (request == null)
                {
                    return("<Rock:NotificationBox HeaderText=\"Not Found\" Text=\"We couldn't find that prayer request.\" NotificationType=\"Error\" />");
                }

                var canEdit = request.RequestedByPersonAlias != null && request.RequestedByPersonAlias.PersonId == RequestContext.CurrentPerson?.Id;

                if (!BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !canEdit)
                {
                    return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"You are not authorized to edit prayer requests.\" NotificationType=\"Error\" />");
                }

                var mergeFields = RequestContext.GetCommonMergeFields();
                mergeFields.AddOrReplace("PrayerRequest", request);
                var prayerRequestXaml = Template.ResolveMergeFields(mergeFields, RequestContext.CurrentPerson);

                return($@"
<StackLayout StyleClass=""prayerdetail"">
    {prayerRequestXaml}

    <Rock:FieldContainer>
        <Rock:TextEditor x:Name=""tbAnswer"" IsRequired=""True"" MinimumHeightRequest=""80"" AutoSize=""TextChanges"" Placeholder=""My answer to prayer is...""
            Text=""{request.Answer.ToStringSafe().EncodeXml( true )}"" />
    </Rock:FieldContainer>

    <Rock:Validator x:Name=""vForm"">
        <x:Reference>tbAnswer</x:Reference>
    </Rock:Validator>
    
    <Rock:NotificationBox x:Name=""nbError"" NotificationType=""Warning"" />
    
    <Button StyleClass=""btn,btn-primary,save-button"" Text=""Save"" Command=""{{Binding Callback}}"">
        <Button.CommandParameter>
            <Rock:CallbackParameters Name="":SaveAnswer"" Validator=""{{x:Reference vForm}}"" Notification=""{{x:Reference nbError}}"">
                <Rock:Parameter Name=""answer"" Value=""{{Binding Text, Source={{x:Reference tbAnswer}}}}"" />
            </Rock:CallbackParameters>
        </Button.CommandParameter>
    </Button>

    <Button StyleClass=""btn,btn-link,cancel-button"" Text=""Cancel"" Command=""{{Binding PopPage}}"" />
</StackLayout>");
            }
        }
Beispiel #5
0
        /// <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)
        {
            int        blockId = Convert.ToInt32(PageParameter("BlockId"));
            BlockCache _block  = BlockCache.Get(blockId);

            var blockControlType = System.Web.Compilation.BuildManager.GetCompiledType(_block.BlockType.Path);

            this.ShowCustomGridColumns = typeof(Rock.Web.UI.ICustomGridColumns).IsAssignableFrom(blockControlType);
            this.ShowCustomGridOptions = typeof(Rock.Web.UI.ICustomGridOptions).IsAssignableFrom(blockControlType);

            if (!Page.IsPostBack && _block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
            {
                if (_block.Attributes != null)
                {
                    avcAdvancedAttributes.IncludedCategoryNames = new string[] { "advanced" };
                    avcAdvancedAttributes.AddEditControls(_block);

                    avcAttributes.ExcludedCategoryNames = new string[] { "advanced", "customsetting" };
                    avcAttributes.AddEditControls(_block);
                }

                rptProperties.DataSource = GetTabs(_block.BlockType);
                rptProperties.DataBind();

                tbBlockName.Text = _block.Name;
                tbCssClass.Text  = _block.CssClass;
                cePreHtml.Text   = _block.PreHtml;
                cePostHtml.Text  = _block.PostHtml;

                // Hide the Cache duration block for now;
                tbCacheDuration.Visible = false;
                //tbCacheDuration.Text = _block.OutputCacheDuration.ToString();

                rcwCustomGridColumns.Visible  = this.ShowCustomGridColumns;
                tglEnableStickyHeader.Visible = this.ShowCustomGridOptions;

                if (this.ShowCustomGridColumns)
                {
                    CustomGridColumnsConfigState = _block.GetAttributeValue(CustomGridColumnsConfig.AttributeKey).FromJsonOrNull <CustomGridColumnsConfig>() ?? new CustomGridColumnsConfig();
                    BindCustomColumnsConfig();
                }
                else
                {
                    CustomGridColumnsConfigState = null;
                }

                if (this.ShowCustomGridOptions)
                {
                    tglEnableStickyHeader.Checked = _block.GetAttributeValue(CustomGridOptionsConfig.EnableStickyHeadersAttributeKey).AsBoolean();
                }
            }

            base.OnLoad(e);
        }
        /// <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)
        {
            int        blockId = Convert.ToInt32(PageParameter("BlockId"));
            BlockCache _block  = BlockCache.Read(blockId);

            if (!Page.IsPostBack && _block.IsAuthorized("Administrate", CurrentPerson))
            {
                tbBlockName.Text     = _block.Name;
                tbCacheDuration.Text = _block.OutputCacheDuration.ToString();
            }

            base.OnLoad(e);
        }
        /// <summary>
        /// Raises the <see cref="E:Init" /> event.
        /// </summary>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            Rock.Web.UI.DialogMasterPage masterPage = this.Page.Master as Rock.Web.UI.DialogMasterPage;
            if (masterPage != null)
            {
                masterPage.OnSave += new EventHandler <EventArgs>(masterPage_OnSave);
            }

            try
            {
                int        blockId = Convert.ToInt32(PageParameter("BlockId"));
                BlockCache _block  = BlockCache.Read(blockId);

                if (_block.IsAuthorized("Administrate", CurrentPerson))
                {
                    phAttributes.Controls.Clear();
                    phAdvancedAttributes.Controls.Clear();

                    if (_block.Attributes != null)
                    {
                        foreach (var attributeCategory in Rock.Attribute.Helper.GetAttributeCategories(_block))
                        {
                            if (attributeCategory.Category != null && attributeCategory.Category.Name.Equals("advanced", StringComparison.OrdinalIgnoreCase))
                            {
                                Rock.Attribute.Helper.AddEditControls(
                                    string.Empty, attributeCategory.Attributes.Select(a => a.Key).ToList(),
                                    _block, phAdvancedAttributes, string.Empty, !Page.IsPostBack, new List <string>());
                            }
                            else
                            {
                                Rock.Attribute.Helper.AddEditControls(
                                    attributeCategory.Category != null ? attributeCategory.Category.Name : string.Empty,
                                    attributeCategory.Attributes.Select(a => a.Key).ToList(),
                                    _block, phAttributes, string.Empty, !Page.IsPostBack, new List <string>());
                            }
                        }
                    }
                }
                else
                {
                    DisplayError("You are not authorized to edit this block");
                }
            }
            catch (SystemException ex)
            {
                DisplayError(ex.Message);
            }

            base.OnInit(e);
        }
Beispiel #8
0
        /// <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)
        {
            int        blockId = Convert.ToInt32(PageParameter("BlockId"));
            BlockCache _block  = BlockCache.Read(blockId);

            if (!Page.IsPostBack && _block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
            {
                rptProperties.DataSource = _tabs;
                rptProperties.DataBind();

                tbBlockName.Text     = _block.Name;
                tbCssClass.Text      = _block.CssClass;
                cePreHtml.Text       = _block.PreHtml;
                cePostHtml.Text      = _block.PostHtml;
                tbCacheDuration.Text = _block.OutputCacheDuration.ToString();
            }

            base.OnLoad(e);
        }
Beispiel #9
0
        /// <summary>
        /// Gets the next action with a Form attached.
        /// </summary>
        /// <param name="workflow">The workflow.</param>
        /// <param name="currentPerson">The current person.</param>
        /// <returns></returns>
        private WorkflowAction GetNextAction(Model.Workflow workflow, Person currentPerson)
        {
            int  personId = currentPerson?.Id ?? 0;
            bool canEdit  = BlockCache.IsAuthorized(Authorization.EDIT, currentPerson);

            //
            // Find all the activities that this person can see.
            //
            var activities = workflow.Activities
                             .Where(a =>
                                    a.IsActive &&
                                    (
                                        canEdit ||
                                        (!a.AssignedGroupId.HasValue && !a.AssignedPersonAliasId.HasValue) ||
                                        (a.AssignedPersonAlias != null && a.AssignedPersonAlias.PersonId == personId) ||
                                        (a.AssignedGroup != null && a.AssignedGroup.Members.Any(m => m.PersonId == personId))
                                    )
                                    )
                             .OrderBy(a => a.ActivityTypeCache.Order)
                             .ToList();

            //
            // Find the first action that the user is authorized to work with that has a Form
            // attached to it.
            //
            foreach (var activity in activities)
            {
                if (canEdit || activity.ActivityTypeCache.IsAuthorized(Authorization.VIEW, currentPerson))
                {
                    foreach (var action in activity.ActiveActions)
                    {
                        if (action.ActionTypeCache.WorkflowForm != null && action.IsCriteriaValid)
                        {
                            return(action);
                        }
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// Processes the action.
        /// </summary>
        /// <param name="controller">The API controller that initiated this action.</param>
        /// <param name="pageGuid">The page unique identifier.</param>
        /// <param name="blockGuid">The block unique identifier.</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        internal static IHttpActionResult ProcessAction(ApiControllerBase controller, Guid?pageGuid, Guid?blockGuid, string actionName, JToken parameters)
        {
            try
            {
                BlockCache blockCache = null;
                PageCache  pageCache  = null;

                //
                // Find the block.
                //
                if (blockGuid.HasValue)
                {
                    blockCache = BlockCache.Get(blockGuid.Value);
                }

                if (blockCache == null)
                {
                    return(new NotFoundResult(controller));
                }

                // Find the page.
                if (pageGuid.HasValue)
                {
                    pageCache = PageCache.Get(pageGuid.Value);
                }
                else
                {
                    // This can be removed once the obsolete API endpoints
                    // that allowed for sending an action to a block identifier
                    // without a page identifier are removed.
                    pageCache = blockCache.Page;
                }

                if (blockCache == null || pageCache == null)
                {
                    return(new NotFoundResult(controller));
                }

                //
                // Get the authenticated person and make sure it's cached.
                //
                var person = GetPerson(controller, null);
                HttpContext.Current.AddOrReplaceItem("CurrentPerson", person);

                //
                // Ensure the user has access to both the page and block.
                //
                if (!pageCache.IsAuthorized(Security.Authorization.VIEW, person) || !blockCache.IsAuthorized(Security.Authorization.VIEW, person))
                {
                    return(new StatusCodeResult(HttpStatusCode.Unauthorized, controller));
                }

                //
                // Get the class that handles the logic for the block.
                //
                var blockCompiledType = blockCache.BlockType.GetCompiledType();
                var block             = Activator.CreateInstance(blockCompiledType);

                if (!(block is Blocks.IRockBlockType rockBlock))
                {
                    return(new NotFoundResult(controller));
                }

                var requestContext = controller.RockRequestContext;

                //
                // Set the basic block parameters.
                //
                rockBlock.BlockCache     = blockCache;
                rockBlock.PageCache      = pageCache;
                rockBlock.RequestContext = requestContext;

                var actionParameters = new Dictionary <string, JToken>(StringComparer.InvariantCultureIgnoreCase);

                //
                // Parse any posted parameter data.
                //
                if (parameters != null)
                {
                    try
                    {
                        foreach (var kvp in parameters.ToObject <Dictionary <string, JToken> >())
                        {
                            if (kvp.Key == "__context")
                            {
                                // If we are given any page parameters then
                                // override the query string parameters. This
                                // is what allows mobile and obsidian blocks to
                                // pass in the original page parameters.
                                if (kvp.Value["pageParameters"] != null)
                                {
                                    var pageParameters = kvp.Value["pageParameters"].ToObject <Dictionary <string, string> >();

                                    rockBlock.RequestContext.SetPageParameters(pageParameters);
                                }
                            }
                            else
                            {
                                actionParameters.AddOrReplace(kvp.Key, kvp.Value);
                            }
                        }
                    }
                    catch
                    {
                        return(new BadRequestErrorMessageResult("Invalid parameter data.", controller));
                    }
                }

                //
                // Parse any query string parameter data.
                //
                foreach (var q in controller.Request.GetQueryNameValuePairs())
                {
                    actionParameters.AddOrReplace(q.Key, JToken.FromObject(q.Value.ToString()));
                }

                requestContext.AddContextEntitiesForPage(pageCache);

                return(InvokeAction(controller, rockBlock, actionName, actionParameters, parameters));
            }
            catch (Exception ex)
            {
                return(new BadRequestErrorMessageResult(ex.Message, controller));
            }
        }
Beispiel #11
0
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>The response to send back to the client.</returns>
        private CallbackResponse SaveRequest(Dictionary <string, object> parameters)
        {
            using (var rockContext = new RockContext())
            {
                var           prayerRequestService = new PrayerRequestService(rockContext);
                PrayerRequest prayerRequest;
                var           requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();

                if (requestGuid.HasValue)
                {
                    prayerRequest = prayerRequestService.Get(requestGuid.Value);

                    if (prayerRequest == null || !BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson))
                    {
                        return(new CallbackResponse
                        {
                            Error = "You are not authorized to edit prayer requests."
                        });
                    }
                }
                else
                {
                    int?categoryId = null;

                    if (DefaultCategory.HasValue)
                    {
                        categoryId = CategoryCache.Get(DefaultCategory.Value).Id;
                    }

                    prayerRequest = new PrayerRequest
                    {
                        Id              = 0,
                        IsActive        = true,
                        IsApproved      = EnableAutoApprove,
                        AllowComments   = false,
                        EnteredDateTime = RockDateTime.Now,
                        CategoryId      = categoryId
                    };
                    prayerRequestService.Add(prayerRequest);

                    if (EnableAutoApprove)
                    {
                        prayerRequest.ApprovedByPersonAliasId = RequestContext.CurrentPerson?.PrimaryAliasId;
                        prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                        prayerRequest.ExpirationDate          = RockDateTime.Now.AddDays(ExpiresAfterDays);
                    }
                }

                prayerRequest.FirstName = ( string )parameters["firstName"];
                prayerRequest.LastName  = ( string )parameters["lastName"];
                prayerRequest.Email     = ( string )parameters["email"];
                prayerRequest.Text      = ( string )parameters["request"];

                if (ShowCampus)
                {
                    if (parameters.ContainsKey("campus"))
                    {
                        var campusGuid = (( string )parameters["campus"]).AsGuidOrNull();

                        if (campusGuid.HasValue)
                        {
                            prayerRequest.CampusId = CampusCache.Get(campusGuid.Value).Id;
                        }
                    }
                    else
                    {
                        prayerRequest.CampusId = CampusCache.All().FirstOrDefault(a => a.IsActive ?? false)?.Id;
                    }
                }

                if (ShowCategory && parameters.ContainsKey("category"))
                {
                    var categoryGuid = (( string )parameters["category"]).AsGuidOrNull();

                    if (categoryGuid.HasValue)
                    {
                        prayerRequest.CategoryId = CategoryCache.Get(categoryGuid.Value).Id;
                    }
                    else if (prayerRequest.Id > 0)
                    {
                        prayerRequest.CategoryId = null;
                    }
                }

                if (ShowPublicDisplayFlag)
                {
                    prayerRequest.IsPublic = ( bool )parameters["allowPublication"];
                }

                if (ShowUrgentFlag)
                {
                    prayerRequest.IsUrgent = ( bool )parameters["urgent"];
                }

                if (RequestContext.CurrentPerson != null)
                {
                    //
                    // If there is a logged in person and the names still match, meaning they are not
                    // entering a prayer request for somebody else, then set the requested by property.
                    //
                    var person = RequestContext.CurrentPerson;
                    if (prayerRequest.FirstName == person.FirstName && prayerRequest.LastName == person.LastName)
                    {
                        prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                    }
                }
                else
                {
                    //
                    // If there is not a logged in person, try to match to an existing person.
                    //
                    var person = MatchPerson(prayerRequest, rockContext);

                    if (person != null)
                    {
                        prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                    }
                }

                //
                // Save all changes to database.
                //
                rockContext.SaveChanges();

                StartWorkflow(prayerRequest, rockContext);
            }

            if (CompletionAction == 0)
            {
                return(new CallbackResponse
                {
                    Content = CompletionXaml ?? string.Empty
                });
            }
            else if (CompletionAction == 1)
            {
                return(new CallbackResponse
                {
                    Command = "PopPage",
                    CommandParameter = "true"
                });
            }
            else
            {
                return(new CallbackResponse
                {
                    Content = AttributeDefaults.CompletionXaml
                });
            }
        }
Beispiel #12
0
        /// <summary>
        /// Builds the content to be displayed on the block.
        /// </summary>
        /// <returns>A string containing the XAML content to be displayed.</returns>
        private string BuildContent()
        {
            string content;
            string fieldsContent;
            var    parameters = new Dictionary <string, string>();

            using (var rockContext = new RockContext())
            {
                Guid?         requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();
                PrayerRequest request     = null;

                if (requestGuid.HasValue)
                {
                    if (!BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson))
                    {
                        return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"You are not authorized to edit prayer requests.\" NotificationType=\"Error\" />");
                    }

                    request = new PrayerRequestService(rockContext).Get(requestGuid.Value);

                    if (request == null)
                    {
                        return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"We couldn't find that prayer request.\" NotificationType=\"Error\" />");
                    }
                }

                content = $@"
<StackLayout StyleClass=""prayerdetail"">
    ##HEADER##

    ##FIELDS##
    
    <Rock:Validator x:Name=""vForm"">
        ##VALIDATORS##
    </Rock:Validator>
    
    <Rock:NotificationBox x:Name=""nbError"" NotificationType=""Error"" />
    
    <Button StyleClass=""btn,btn-primary"" Text=""Save"" Margin=""24 0 0 0"" Command=""{{Binding Callback}}"">
        <Button.CommandParameter>
            <Rock:CallbackParameters Name=""Save"" Validator=""{{x:Reference vForm}}"" Notification=""{{x:Reference nbError}}"">
                ##PARAMETERS##
            </Rock:CallbackParameters>
        </Button.CommandParameter>
    </Button>

    <Button StyleClass=""btn,btn-link"" Text=""Cancel"" ##CANCEL## />
</StackLayout>";

                if (ShowHeader)
                {
                    content = content.Replace("##HEADER##", $@"<Label StyleClass=""h2"" Text=""{( request == null ? "Add" : "Edit" )} Prayer Request"" />
    <Rock:Divider />");
                }
                else
                {
                    content = content.Replace("##HEADER##", "");
                }

                fieldsContent = BuildCommonFields(request, parameters);
            }

            var validatorsContent = parameters.Keys.Select(a => $"<x:Reference>{a}</x:Reference>");
            var parametersContent = parameters.Select(a => $"<Rock:Parameter Name=\"{a.Key}\" Value=\"{{Binding {a.Value}, Source={{x:Reference {a.Key}}}}}\" />");

            //
            // On cancel, pop to the parent page.
            //
            content = content.Replace("##CANCEL##", "Command=\"{Binding PopPage}\"");

            return(content.Replace("##FIELDS##", fieldsContent)
                   .Replace("##VALIDATORS##", string.Join(string.Empty, validatorsContent))
                   .Replace("##PARAMETERS##", string.Join(string.Empty, parametersContent)));
        }
Beispiel #13
0
        /// <summary>
        /// Builds the common fields.
        /// </summary>
        /// <param name="request">The prayer request.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns>A string containing the XAML that represents the common Group fields.</returns>
        private string BuildCommonFields(PrayerRequest request, Dictionary <string, string> parameters)
        {
            var    sb = new StringBuilder();
            string field;

            // Allow editing primary fields if this is a new request or
            // if they have Edit access to the block.
            var allowFullEditing = request == null || request.Id == 0 || BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson);

            if (allowFullEditing)
            {
                string firstName = request != null ? request.FirstName : RequestContext.CurrentPerson?.FirstName;
                string lastName  = request != null ? request.LastName : RequestContext.CurrentPerson?.LastName;
                string email     = request != null ? request.Email : RequestContext.CurrentPerson?.Email;

                field = MobileHelper.GetTextEditFieldXaml("firstName", "First Name", firstName, true);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("firstName", "Text");

                field = MobileHelper.GetTextEditFieldXaml("lastName", "Last Name", lastName, RequireLastName);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("lastName", "Text");

                field = MobileHelper.GetEmailEditFieldXaml("email", "Email", email, false);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("email", "Text");

                if (ShowCampus && CampusCache.All().Where(a => a.IsActive ?? false).Count() > 1)
                {
                    field = $"<Rock:CampusPicker x:Name=\"campus\" Label=\"Campus\" IsRequired=\"{RequireCampus}\" SelectedValue=\"{request?.Campus?.Guid.ToStringSafe()}\" />";
                    sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                    parameters.Add("campus", "SelectedValue");
                }
            }

            if (ShowCategory && ParentCategory.HasValue)
            {
                var items = CategoryCache.Get(ParentCategory.Value)
                            .Categories
                            .Select(a => new KeyValuePair <string, string>(a.Guid.ToString(), a.Name));

                var categoryGuid = request?.Category?.Guid;
                if (!categoryGuid.HasValue && DefaultCategory.HasValue)
                {
                    categoryGuid = CategoryCache.Get(DefaultCategory.Value).Guid;
                }

                field = MobileHelper.GetDropDownFieldXaml("category", "Category", categoryGuid.ToStringSafe(), true, items);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("category", "SelectedValue");
            }

            field = MobileHelper.GetTextEditFieldXaml("request", "Request", request?.Text, true, true, CharacterLimit);
            sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
            parameters.Add("request", "Text");

            if (ShowPublicDisplayFlag)
            {
                field = MobileHelper.GetCheckBoxFieldXaml("allowPublication", "Allow Publication", request?.IsPublic ?? DefaultToPublic);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("allowPublication", "IsChecked");
            }

            if (ShowUrgentFlag)
            {
                field = MobileHelper.GetCheckBoxFieldXaml("urgent", "Urgent", request?.IsUrgent ?? false);
                sb.AppendLine(MobileHelper.GetSingleFieldXaml(field));
                parameters.Add("urgent", "IsChecked");
            }

            return(sb.ToString());
        }
        /// <summary>
        /// Processes the action.
        /// </summary>
        /// <param name="verb">The HTTP Method Verb that was used for the request.</param>
        /// <param name="pageIdentifier">The page identifier (either Guid or int).</param>
        /// <param name="blockIdentifier">The block identifier (either Guid or int).</param>
        /// <param name="actionName">Name of the action.</param>
        /// <param name="parameters">The parameters.</param>
        /// <returns></returns>
        private IHttpActionResult ProcessAction(string verb, string pageIdentifier, string blockIdentifier, string actionName, JToken parameters)
        {
            try
            {
                PageCache  pageCache  = null;
                BlockCache blockCache = null;

                var pageGuid  = pageIdentifier.AsGuidOrNull();
                var pageId    = pageIdentifier.AsIntegerOrNull();
                var blockGuid = blockIdentifier.AsGuidOrNull();
                var blockId   = blockIdentifier.AsIntegerOrNull();

                //
                // Find the page.
                //
                if (pageGuid.HasValue)
                {
                    pageCache = PageCache.Get(pageGuid.Value);
                }
                else if (pageId.HasValue)
                {
                    pageCache = PageCache.Get(pageId.Value);
                }

                //
                // Find the block.
                //
                if (blockGuid.HasValue)
                {
                    blockCache = BlockCache.Get(blockGuid.Value);
                }
                else if (blockId.HasValue)
                {
                    blockCache = BlockCache.Get(blockId.Value);
                }

                if (pageCache == null || blockCache == null)
                {
                    return(NotFound());
                }

                //
                // Get the authenticated person and make sure it's cached.
                //
                var person = GetPerson();
                HttpContext.Current.AddOrReplaceItem("CurrentPerson", person);

                //
                // Ensure the user has access to both the page and block.
                //
                if (!pageCache.IsAuthorized(Security.Authorization.VIEW, person) || !blockCache.IsAuthorized(Security.Authorization.VIEW, person))
                {
                    return(StatusCode(HttpStatusCode.Unauthorized));
                }

                //
                // Get the class that handles the logic for the block.
                //
                var blockCompiledType = blockCache.BlockType.GetCompiledType();
                var block             = Activator.CreateInstance(blockCompiledType);

                if (!(block is Blocks.IRockBlockType rockBlock))
                {
                    return(NotFound());
                }

                //
                // Set the basic block parameters.
                //
                rockBlock.BlockCache     = blockCache;
                rockBlock.PageCache      = pageCache;
                rockBlock.RequestContext = new Net.RockRequestContext(Request);

                var actionParameters = new Dictionary <string, JToken>();

                //
                // Parse any posted parameter data.
                //
                if (parameters != null)
                {
                    try
                    {
                        foreach (var kvp in parameters.ToObject <Dictionary <string, JToken> >())
                        {
                            actionParameters.AddOrReplace(kvp.Key, kvp.Value);
                        }
                    }
                    catch
                    {
                        return(BadRequest("Invalid parameter data."));
                    }
                }

                //
                // Parse any query string parameter data.
                //
                foreach (var q in Request.GetQueryNameValuePairs())
                {
                    actionParameters.AddOrReplace(q.Key, JToken.FromObject(q.Value.ToString()));
                }

                return(InvokeAction(rockBlock, verb, actionName, actionParameters));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Beispiel #15
0
        /// <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)
        {
            Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage;
            if (dialogPage != null)
            {
                dialogPage.ValidationGroup = this.BlockValidationGroup;
            }

            valSummaryTop.ValidationGroup = this.BlockValidationGroup;

            int?blockId = PageParameter("BlockId").AsIntegerOrNull();

            if (!blockId.HasValue)
            {
                return;
            }

            BlockCache _block = BlockCache.Get(blockId.Value);

            var blockControlType = _block.BlockType.GetCompiledType();

            this.ShowCustomGridColumns = typeof(Rock.Web.UI.ICustomGridColumns).IsAssignableFrom(blockControlType);
            this.ShowCustomGridOptions = typeof(Rock.Web.UI.ICustomGridOptions).IsAssignableFrom(blockControlType);
            this.ShowMobileOptions     = _block.Attributes.Any(a => a.Value.Categories.Any(c => c.Name == "custommobile"));

            if (!Page.IsPostBack && _block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
            {
                if (_block.Attributes != null)
                {
                    avcAdvancedAttributes.IncludedCategoryNames = new string[] { "advanced" };
                    avcAdvancedAttributes.AddEditControls(_block);

                    avcMobileAttributes.IncludedCategoryNames = new string[] { "custommobile" };
                    avcMobileAttributes.AddEditControls(_block);

                    avcAttributes.ExcludedCategoryNames = new string[] { "advanced", "customsetting", "custommobile" };
                    avcAttributes.AddEditControls(_block);
                }

                foreach (var kvp in CustomSettingsProviders)
                {
                    kvp.Key.ReadSettingsFromEntity(_block, kvp.Value);
                }

                rptProperties.DataSource = GetTabs(_block.BlockType);
                rptProperties.DataBind();

                tbBlockName.Text = _block.Name;
                tbCssClass.Text  = _block.CssClass;
                cePreHtml.Text   = _block.PreHtml;
                cePostHtml.Text  = _block.PostHtml;

                // Hide the Cache duration block for now;
                tbCacheDuration.Visible = false;
                //tbCacheDuration.Text = _block.OutputCacheDuration.ToString();

                pwCustomGridColumns.Visible   = this.ShowCustomGridColumns;
                tglEnableStickyHeader.Visible = this.ShowCustomGridOptions;

                if (this.ShowCustomGridColumns)
                {
                    CustomGridColumnsConfigState = _block.GetAttributeValue(CustomGridColumnsConfig.AttributeKey).FromJsonOrNull <CustomGridColumnsConfig>() ?? new CustomGridColumnsConfig();
                    BindCustomColumnsConfig();
                }
                else
                {
                    CustomGridColumnsConfigState = null;
                }

                if (this.ShowCustomGridOptions)
                {
                    tglEnableStickyHeader.Checked            = _block.GetAttributeValue(CustomGridOptionsConfig.EnableStickyHeadersAttributeKey).AsBoolean();
                    tglEnableDefaultWorkflowLauncher.Checked = _block.GetAttributeValue(CustomGridOptionsConfig.EnableDefaultWorkflowLauncherAttributeKey).AsBoolean();

                    CustomActionsConfigState = _block.GetAttributeValue(CustomGridOptionsConfig.CustomActionsConfigsAttributeKey).FromJsonOrNull <List <CustomActionConfig> >();
                    BindCustomActionsConfig();
                }
                else
                {
                    CustomActionsConfigState = null;
                }

                ShowSelectedPane();
            }

            base.OnLoad(e);
        }
Beispiel #16
0
 /// <summary>
 /// Evaluates if the CurrentPerson is authorized to perform the requested action.
 /// </summary>
 /// <param name="action">A <see cref="System.String" /> representing the action that the <see cref="Rock.Model.UserLogin"/>/<see cref="CurrentPerson"/>
 /// is requesting to perform.</param>
 /// <returns>A <see cref="System.Boolean"/> that is <c>true</c> if the CurrentPerson is authorized to perform the requested action; otherwise <c>false</c>.</returns>
 public bool IsUserAuthorized(string action)
 {
     return(_blockCache.IsAuthorized(action, CurrentPerson));
 }