public async Task <IActionResult> Get(int blockId, string actionName)
        {
            try
            {
                var block = BlockCache.Get(blockId).GetMappedBlockType(HttpContext.RequestServices);

                if (!(block is IAsyncActionBlock actionBlock))
                {
                    return(new BadRequestObjectResult("Block does not support actions."));
                }

                ActionData actionData = new ActionData();

                foreach (var q in Request.Query)
                {
                    actionData.Parameters.AddOrReplace(q.Key, JToken.FromObject(q.Value.ToString()));
                }

                return(await actionBlock.ProcessActionAsync(actionName, actionData));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
        public MobileBlockResponse BlockGetRequest(int id, string request = "")
        {
            var person = GetPerson();

            HttpContext.Current.Items.Add("CurrentPerson", person);
            var blockCache = BlockCache.Get(id);

            if (blockCache == null)
            {
                return(new MobileBlockResponse());
            }
            var    pageCache  = PageCache.Get(blockCache.PageId ?? 0);
            string theme      = pageCache.Layout.Site.Theme;
            string layout     = pageCache.Layout.FileName;
            string layoutPath = PageCache.FormatPath(theme, layout);

            Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));

            if (blockCache.IsAuthorized(Authorization.VIEW, person))
            {
                var control = ( RockBlock )cmsPage.TemplateControl.LoadControl(blockCache.BlockType.Path);

                if (control is RockBlock && control is IMobileResource)
                {
                    control.SetBlock(pageCache, blockCache);
                    var mobileResource      = control as IMobileResource;
                    var mobileBlockResponse = mobileResource.HandleRequest(request, new Dictionary <string, string>());
                    HttpContext.Current.Response.Headers.Set("TTL", mobileBlockResponse.TTL.ToString());
                    return(mobileBlockResponse);
                }
            }
            HttpContext.Current.Response.Headers.Set("TTL", "0");
            return(new MobileBlockResponse());
        }
        public MobileBlockResponse BlockPostRequest(int id, string arg = "")
        {
            HttpContent requestContent = Request.Content;
            string      content        = requestContent.ReadAsStringAsync().Result;
            var         body           = JsonConvert.DeserializeObject <Dictionary <string, string> >(content);
            var         person         = GetPerson();

            HttpContext.Current.Items.Add("CurrentPerson", person);
            var    blockCache = BlockCache.Get(id);
            var    pageCache  = PageCache.Get(blockCache.PageId ?? 0);
            string theme      = pageCache.Layout.Site.Theme;
            string layout     = pageCache.Layout.FileName;
            string layoutPath = PageCache.FormatPath(theme, layout);

            Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));

            if (blockCache.IsAuthorized(Authorization.VIEW, person))
            {
                var control = ( RockBlock )cmsPage.TemplateControl.LoadControl(blockCache.BlockType.Path);

                if (control is RockBlock && control is IMobileResource)
                {
                    control.SetBlock(pageCache, blockCache);
                    var mobileResource      = control as IMobileResource;
                    var mobileBlockResponse = mobileResource.HandleRequest(arg, body);
                    mobileBlockResponse.TTL = 0;
                    return(mobileBlockResponse);
                }
            }
            return(new MobileBlockResponse());
        }
Beispiel #4
0
        /// <summary>
        /// Renders a label and <see cref="T:System.Web.UI.WebControls.TextBox"/> control to the specified <see cref="T:System.Web.UI.HtmlTextWriter"/> object.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Web.UI.HtmlTextWriter"/> that receives the rendered output.</param>
        public override void RenderControl(HtmlTextWriter writer)
        {
            if (this.Visible)
            {
                string cssClass = "";
                foreach (Control childControl in this.Controls)
                {
                    if (childControl.GetType().ToString().Contains("RockBlockWrapper"))
                    {
                        foreach (Control grandChildControl in childControl.Controls)
                        {
                            if (grandChildControl.GetType().ToString().Contains("org_secc_cms_sectionheader"))
                            {
                                var block        = BlockCache.Get((( RockBlock )grandChildControl).BlockId);
                                var definedValue = DefinedValueCache.Get(block.GetAttributeValue("SectionType"));
                                if (definedValue != null && definedValue.AttributeValues.ContainsKey("ClassName"))
                                {
                                    cssClass = definedValue.AttributeValues["ClassName"].ToString();
                                }
                                break;
                            }
                        }
                        if (cssClass != "")
                        {
                            break;
                        }
                    }
                }
                writer.AddAttribute(HtmlTextWriterAttribute.Class, cssClass);
                writer.RenderBeginTag("section");

                base.RenderControl(writer);
                writer.RenderEndTag();
            }
        }
Beispiel #5
0
        public void TestSSTableAndBuilder()
        {
            using var cache  = new BlockCache(100);
            using var scache = cache.Get(0);

            using var ms = new KeepOpenMemoryStream();
            using (var builder = new SSTableBuilder(ms, new PlaneDBOptions())) {
                for (var i = 0; i < COUNT; ++i)
                {
                    var v = i.ToString();
                    if (i % 16 != 0)
                    {
                        builder.Put(v, v + v + v);
                    }

                    if (i % 10 == 0)
                    {
                        builder.Put("o" + v, v + v + v);
                    }

                    if (i % 20 == 0)
                    {
                        builder.Remove("o" + v);
                    }
                }
            }

            using var table = new SSTable(ms, scache, new PlaneDBOptions());
            for (var i = 0; i < COUNT; ++i)
            {
                var v = i.ToString();
                if (i % 16 != 0)
                {
                    Assert.IsTrue(table.ContainsKey(v, out _));
                    Assert.IsFalse(table.ContainsKey($"nope{v}", out _));
                    Assert.IsTrue(table.TryGet(v, out var s));
                    Assert.AreEqual(v + v + v, s);
                }
                else
                {
                    Assert.IsFalse(table.ContainsKey(v, out _));
                    Assert.IsFalse(table.ContainsKey($"nope{v}", out _));
                    Assert.IsFalse(table.TryGet(v, out var s));
                    Assert.AreEqual(null, s);
                }

                if (i % 20 == 0)
                {
                    Assert.IsTrue(table.ContainsKey("o" + v, out _));
                    Assert.IsTrue(table.TryGet("o" + v, out var val));
                    Assert.IsNull(val);
                }
                else if (i % 10 == 0)
                {
                    Assert.IsTrue(table.ContainsKey("o" + v, out _));
                    Assert.IsTrue(table.TryGet("o" + v, out var val));
                    Assert.AreEqual(v + v + v, val);
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// Handles the Click event of the _btnSelectCurrentPage control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        public void _btnSelectCurrentPage_Click(object sender, EventArgs e)
        {
            int?pageId    = null;
            var rockBlock = this.RockBlock();

            if (rockBlock.PageCache.Guid == Rock.SystemGuid.Page.BLOCK_PROPERTIES.AsGuid())
            {
                // if the BlockProperties block is the current block, we'll treat the page that this block properties is for as the current page
                int blockId = rockBlock.PageParameter("BlockId").AsInteger();
                var block   = BlockCache.Get(blockId);
                if (block?.PageId != null)
                {
                    pageId = block.PageId;
                }
                else
                {
                    pageId = rockBlock.PageParameter("CurrentPageId").AsIntegerOrNull();
                }
            }
            else
            {
                pageId = rockBlock.PageCache.Id;
            }

            if (pageId.HasValue)
            {
                var currentPage = new PageService(new RockContext()).Get(pageId.Value);
                this.SetValue(currentPage);
            }

            ShowDropDown = true;
        }
Beispiel #7
0
        /// <summary>
        /// Loads the custom settings tabs.
        /// </summary>
        protected void LoadCustomSettingsTabs()
        {
            int blockId = PageParameter("BlockId").AsInteger();
            var block   = BlockCache.Get(blockId);

            CustomSettingsProviders = new Dictionary <RockCustomSettingsProvider, Control>();

            var providers = RockCustomSettingsProvider.GetProvidersForType(block.BlockType.GetCompiledType()).Reverse();

            foreach (var provider in providers)
            {
                var control = provider.GetCustomSettingsControl(block, phCustomSettings);
                control.Visible = false;

                if (provider.CustomSettingsTitle == "Basic Settings")
                {
                    phCustomBasicSettings.Controls.Add(control);
                }
                else if (provider.CustomSettingsTitle == "Advanced Settings")
                {
                    phCustomAdvancedSettings.Controls.Add(control);
                }
                else
                {
                    phCustomSettings.Controls.Add(control);
                }

                CustomSettingsProviders.Add(provider, control);
            }
        }
        /// <summary>
        /// Loads the custom settings tabs.
        /// </summary>
        protected void LoadCustomSettingsTabs()
        {
            int blockId = PageParameter("BlockId").AsInteger();
            var block   = BlockCache.Get(blockId);

            CustomSettingsProviders = new Dictionary <RockCustomSettingsProvider, Control>();

            var providers = RockCustomSettingsProvider.GetProvidersForType(block.BlockType.GetCompiledType()).Reverse();

            foreach (var provider in providers)
            {
                // Place the custom controls in a naming container to avoid
                // ID collisions.
                var controlContainer = new CompositePlaceHolder();

                if (provider.CustomSettingsTitle == "Basic Settings")
                {
                    phCustomBasicSettings.Controls.Add(controlContainer);
                }
                else if (provider.CustomSettingsTitle == "Advanced Settings")
                {
                    phCustomAdvancedSettings.Controls.Add(controlContainer);
                }
                else
                {
                    phCustomSettings.Controls.Add(controlContainer);
                }

                var control = provider.GetCustomSettingsControl(block, phCustomSettings);
                control.Visible = false;
                controlContainer.Controls.Add(control);

                CustomSettingsProviders.Add(provider, control);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Binds the custom columns configuration.
        /// </summary>
        private void BindCustomColumnsConfig()
        {
            int        blockId = Convert.ToInt32(PageParameter("BlockId"));
            BlockCache _block  = BlockCache.Get(blockId);

            rptCustomGridColumns.DataSource = CustomGridColumnsConfigState.ColumnsConfig;
            rptCustomGridColumns.DataBind();
        }
        /// <summary>
        /// Binds the custom actions configuration.
        /// </summary>
        private void BindCustomActionsConfig()
        {
            var blockId = Convert.ToInt32(PageParameter("BlockId"));
            var _block  = BlockCache.Get(blockId);

            rptCustomActions.DataSource = CustomActionsConfigState;
            rptCustomActions.DataBind();
        }
Beispiel #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);

            string name = BlockCache.Get(BlockId).BlockType.Path.Replace("~", "").Replace(".ascx", "");

            Id        = "bid_" + BlockId;
            Path      = name;
            Component = name.Replace("/", ".").Remove(0, 1);
        }
        public HttpResponseMessage Family(string param)
        {
            try
            {
                var Session = HttpContext.Current.Session;

                var localDeviceConfigCookie = HttpContext.Current.Request.Cookies[CheckInCookieKey.LocalDeviceConfig].Value;
                var localDevice             = localDeviceConfigCookie.FromJsonOrNull <LocalDeviceConfiguration>();

                CurrentKioskId = localDevice.CurrentKioskId.Value;
                Guid blockGuid = ( Guid )Session["BlockGuid"];
                CurrentCheckInState = new CheckInState(CurrentKioskId, localDevice.CurrentCheckinTypeId, localDevice.CurrentGroupTypeIds);
                CurrentCheckInState.CheckIn.UserEnteredSearch   = true;
                CurrentCheckInState.CheckIn.ConfirmSingleFamily = true;
                CurrentCheckInState.CheckIn.SearchType          = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER);
                CurrentCheckInState.CheckIn.SearchValue         = param;

                var    rockContext      = new Rock.Data.RockContext();
                var    block            = BlockCache.Get(blockGuid);
                string workflowActivity = block.GetAttributeValue("WorkflowActivity");
                Guid?  workflowGuid     = block.GetAttributeValue("WorkflowType").AsGuidOrNull();

                List <string> errors;
                var           workflowService = new WorkflowService(rockContext);
                var           workflowType    = WorkflowTypeCache.Get(workflowGuid.Value);

                var CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, CurrentCheckInState.Kiosk.Device.Name, rockContext);

                var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                if (activityType != null)
                {
                    WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext);
                    if (workflowService.Process(CurrentWorkflow, CurrentCheckInState, out errors))
                    {
                        // Keep workflow active for continued processing
                        CurrentWorkflow.CompletedDateTime = null;
                        SaveState(Session);
                        List <CheckInFamily> families = CurrentCheckInState.CheckIn.Families;
                        families = families.OrderBy(f => f.Caption).ToList();
                        return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, families));
                    }
                }
                else
                {
                    return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("Workflow type does not have a '{0}' activity type", workflowActivity)));
                }
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, String.Join("\n", errors)));
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, HttpContext.Current);
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden"));
            }
        }
Beispiel #13
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);
        }
Beispiel #14
0
        /// <summary>
        /// Gets the Guid for the Block that has the specified Id
        /// </summary>
        /// <param name="id">The identifier.</param>
        /// <returns></returns>
        public override Guid?GetGuid(int id)
        {
            var cacheItem = BlockCache.Get(id);

            if (cacheItem != null)
            {
                return(cacheItem.Guid);
            }

            return(null);
        }
Beispiel #15
0
        /// <summary>
        /// Handles the Click event of the btnDefault 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 btnDefault_Click(object sender, EventArgs e)
        {
            var         bioBlock = BlockCache.Get(Rock.SystemGuid.Block.BIO.AsGuid());
            List <Guid> workflowActionGuidList = bioBlock.GetAttributeValues("WorkflowActions").AsGuidList();

            if (workflowActionGuidList == null || workflowActionGuidList.Count == 0)
            {
                // Add Checkr to Bio Workflow Actions
                bioBlock.SetAttributeValue("WorkflowActions", CheckrSystemGuid.CHECKR_WORKFLOW_TYPE);
            }
            else
            {
                //var workflowActionValues = workflowActionValue.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();
                Guid guid = CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid();
                if (!workflowActionGuidList.Any(w => w == guid))
                {
                    // Add Checkr to Bio Workflow Actions
                    workflowActionGuidList.Add(guid);
                }

                // Remove PMM from Bio Workflow Actions
                guid = Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid();
                workflowActionGuidList.RemoveAll(w => w == guid);
                bioBlock.SetAttributeValue("WorkflowActions", workflowActionGuidList.AsDelimited(","));
            }

            bioBlock.SaveAttributeValue("WorkflowActions");

            string checkrTypeName  = (typeof(Rock.Checkr.Checkr)).FullName;
            var    checkrComponent = BackgroundCheckContainer.Instance.Components.Values.FirstOrDefault(c => c.Value.TypeName == checkrTypeName);

            checkrComponent.Value.SetAttributeValue("Active", "True");
            checkrComponent.Value.SaveAttributeValue("Active");

            using (var rockContext = new RockContext())
            {
                WorkflowTypeService workflowTypeService = new WorkflowTypeService(rockContext);
                // Rename PMM Workflow
                var pmmWorkflowAction = workflowTypeService.Get(Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid());
                pmmWorkflowAction.Name = Checkr_CreatePages.NEW_PMM_WORKFLOW_TYPE_NAME;

                var checkrWorkflowAction = workflowTypeService.Get(CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid());
                // Rename Checkr Workflow
                checkrWorkflowAction.Name = "Background Check";

                rockContext.SaveChanges();
            }

            ShowDetail();
        }
        /// <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)
        {
            try
            {
                int?blockId = PageParameter("BlockId").AsIntegerOrNull();
                if (!blockId.HasValue)
                {
                    return;
                }

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

                Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage;
                if (dialogPage != null)
                {
                    dialogPage.OnSave  += new EventHandler <EventArgs>(masterPage_OnSave);
                    dialogPage.Title    = _block.BlockType.Name;
                    dialogPage.SubTitle = string.Format("{0} / Id: {1}", _block.BlockType.Category, blockId);
                }

                if (_block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                {
                    var blockTypeId = _block.BlockTypeId;
                    var blockType   = BlockTypeCache.Get(blockTypeId);
                    if (blockType != null && !blockType.IsInstancePropertiesVerified)
                    {
                        using (var rockContext = new RockContext())
                        {
                            var  blockCompiledType = _block.BlockType.GetCompiledType();
                            int? blockEntityTypeId = EntityTypeCache.Get(typeof(Block)).Id;
                            bool attributesUpdated = Rock.Attribute.Helper.UpdateAttributes(blockCompiledType, blockEntityTypeId, "BlockTypeId", blockTypeId.ToString(), rockContext);
                            BlockTypeCache.Get(blockTypeId).MarkInstancePropertiesVerified(true);
                        }
                    }
                }
                else
                {
                    DisplayError("You are not authorized to edit this block", null);
                }
            }
            catch (SystemException ex)
            {
                DisplayError(ex.Message, "<pre>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</pre>");
            }

            base.OnInit(e);

            LoadCustomSettingsTabs();
        }
Beispiel #17
0
        /// <summary>
        /// Handles the Click event of the lbProperty 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 lbProperty_Click(object sender, EventArgs e)
        {
            LinkButton lb = sender as LinkButton;

            if (lb != null)
            {
                CurrentTab = lb.Text;

                int        blockId = Convert.ToInt32(PageParameter("BlockId"));
                BlockCache _block  = BlockCache.Get(blockId);
                rptProperties.DataSource = GetTabs(_block.BlockType);
                rptProperties.DataBind();
            }

            ShowSelectedPane();
        }
Beispiel #18
0
        /// <summary>
        /// Handles the ItemDataBound event of the any of the rptrBlocks controls.
        /// </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 rptrBlocks_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var blockInstance = e.Item.DataItem as BlockInstance;

            if (blockInstance != null)
            {
                BlockCache block = BlockCache.Get(blockInstance.Id);
                if (block != null)
                {
                    var phAdminButtons = e.Item.FindControl("phAdminButtons") as PlaceHolder;
                    var phSettings     = e.Item.FindControl("phSettings") as PlaceHolder;

                    AddAdminControls(block, phAdminButtons);
                    AddSettingsControls(block, phSettings);
                }
            }
        }
        public async Task <IActionResult> Postback(int blockId, string actionName, [FromBody] JToken parameters, [FromServices] RockRequestContext rockRequestContext)
        {
            try
            {
                var blockCache = BlockCache.Get(blockId);
                var block      = blockCache.GetMappedBlockType(HttpContext.RequestServices);

                block.Block     = blockCache;
                block.PageCache = blockCache.Page;
                block.RockPage  = new RockPage(PageCache.Get(blockCache.PageId.Value), rockRequestContext);
                rockRequestContext.CurrentPage = block.RockPage;

                if (!(block is IAsyncActionBlock actionBlock))
                {
                    return(new BadRequestObjectResult("Block does not support actions."));
                }

                ActionData actionData;
                try
                {
                    actionData = parameters.ToObject <ActionData>();
                }
                catch
                {
                    return(new BadRequestObjectResult("Invalid parameter data."));
                }

                foreach (var q in Request.Query)
                {
                    actionData.Parameters.AddOrReplace(q.Key, JToken.FromObject(q.Value.ToString()));
                }

                return(await actionBlock.ProcessActionAsync(actionName, actionData));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Beispiel #20
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)
        {
            int?   entityTypeId   = PageParameter("EntityTypeId").AsIntegerOrNull();
            string entityTypeName = string.Empty;
            Type   type           = null;

            // Get Entity Type
            if (entityTypeId.HasValue)
            {
                var entityType = EntityTypeCache.Get(entityTypeId.Value);
                if (entityType != null)
                {
                    entityTypeName = entityType.FriendlyName;
                    type           = entityType.GetEntityType();
                }
            }

            // Get Entity Id
            int entityId = PageParameter("EntityId").AsIntegerOrNull() ?? 0;

            // Get object type
            if (type != null)
            {
                if (entityId == 0)
                {
                    iSecured = ( ISecured )Activator.CreateInstance(type);
                }
                else
                {
                    iSecured = Rock.Reflection.GetIEntityForEntityType(type, entityId) as ISecured;
                }

                var block = iSecured as Rock.Model.Block;
                if (block != null)
                {
                    // If the entity is a block, get any actions that were updated or added by the block type using
                    // one or more SecurityActionAttributes.
                    var blockCache = BlockCache.Get(block.Id);
                    if (blockCache != null && blockCache.BlockType != null)
                    {
                        foreach (var action in blockCache.BlockType.SecurityActions)
                        {
                            if (block.SupportedActions.ContainsKey(action.Key))
                            {
                                block.SupportedActions[action.Key] = action.Value;
                            }
                            else
                            {
                                block.SupportedActions.Add(action.Key, action.Value);
                            }
                        }
                    }

                    iSecured = block;
                }

                if (iSecured != null)
                {
                    if (iSecured.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                    {
                        if (iSecured.SupportedActions.Any())
                        {
                            lActionDescription.Text = iSecured.SupportedActions.FirstOrDefault().Value;
                        }

                        rptActions.DataSource = iSecured.SupportedActions;
                        rptActions.DataBind();

                        rGrid.DataKeyNames        = new string[] { "Id" };
                        rGrid.GridReorder        += new GridReorderEventHandler(rGrid_GridReorder);
                        rGrid.GridRebind         += new GridRebindEventHandler(rGrid_GridRebind);
                        rGrid.RowDataBound       += new GridViewRowEventHandler(rGrid_RowDataBound);
                        rGrid.ShowHeaderWhenEmpty = false;
                        rGrid.EmptyDataText       = string.Empty;
                        rGrid.ShowActionRow       = false;

                        rGridParentRules.DataKeyNames        = new string[] { "Id" };
                        rGridParentRules.ShowHeaderWhenEmpty = false;
                        rGridParentRules.EmptyDataText       = string.Empty;
                        rGridParentRules.ShowActionRow       = false;

                        BindRoles();

                        string scriptFormat = @"
                    Sys.Application.add_load(function () {{
                        $('#modal-popup div.modal-header h3 small', window.parent.document).html('{0}');
                    }});
                ";
                        string script       = string.Format(scriptFormat, HttpUtility.JavaScriptStringEncode(iSecured.ToString()));

                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("set-html-{0}", this.ClientID), script, true);
                    }
                    else
                    {
                        nbMessage.Text = "Unfortunately, you are not able to edit security because you do not belong to a role that has been configured to allow administration of this item.";
                    }
                }
                else
                {
                    nbMessage.Text = "The item you are trying to secure does not exist or does not implement ISecured.";
                }
            }
            else
            {
                nbMessage.Text = string.Format("The requested entity type ('{0}') could not be loaded to determine security attributes.", entityTypeName);
            }

            base.OnInit(e);
        }
Beispiel #21
0
        /// <summary>
        /// Builds the mobile package that can be archived for deployment.
        /// </summary>
        /// <param name="applicationId">The application identifier.</param>
        /// <param name="deviceType">The type of device to build for.</param>
        /// <param name="versionId">The version identifier to use on this package.</param>
        /// <returns>An update package for the specified application and device type.</returns>
        public static UpdatePackage BuildMobilePackage(int applicationId, DeviceType deviceType, int versionId)
        {
            var    site               = SiteCache.Get(applicationId);
            string applicationRoot    = GlobalAttributesCache.Value("PublicApplicationRoot");
            var    additionalSettings = site.AdditionalSettings.FromJsonOrNull <AdditionalSiteSettings>();

            if (additionalSettings == null)
            {
                throw new Exception("Invalid or non-existing AdditionalSettings property on site.");
            }

            //
            // Get all the system phone formats.
            //
            var phoneFormats = DefinedTypeCache.Get(SystemGuid.DefinedType.COMMUNICATION_PHONE_COUNTRY_CODE)
                               .DefinedValues
                               .Select(dv => new MobilePhoneFormat
            {
                CountryCode      = dv.Value,
                MatchExpression  = dv.GetAttributeValue("MatchRegEx"),
                FormatExpression = dv.GetAttributeValue("FormatRegEx")
            })
                               .ToList();

            //
            // Get all the defined values.
            //
            var definedTypeGuids = new[]
            {
                SystemGuid.DefinedType.LOCATION_COUNTRIES,
                SystemGuid.DefinedType.LOCATION_ADDRESS_STATE,
                SystemGuid.DefinedType.PERSON_MARITAL_STATUS
            };
            var definedValues = new List <MobileDefinedValue>();

            foreach (var definedTypeGuid in definedTypeGuids)
            {
                var definedType = DefinedTypeCache.Get(definedTypeGuid);
                definedValues.AddRange(definedType.DefinedValues
                                       .Select(a => new MobileDefinedValue
                {
                    Guid            = a.Guid,
                    DefinedTypeGuid = a.DefinedType.Guid,
                    Value           = a.Value,
                    Description     = a.Description,
                    Attributes      = GetMobileAttributeValues(a, a.Attributes.Select(b => b.Value))
                }));
            }

            //
            // Build CSS Styles
            //
            var settings = additionalSettings.DownhillSettings;

            settings.Platform = DownhillPlatform.Mobile;           // ensure the settings are set to mobile

            var cssStyles = CssUtilities.BuildFramework(settings); // append custom css but parse it for downhill variables

            if (additionalSettings.CssStyle.IsNotNullOrWhiteSpace())
            {
                cssStyles += CssUtilities.ParseCss(additionalSettings.CssStyle, settings);
            }

            // Run Lava on CSS to enable color utilities
            cssStyles = cssStyles.ResolveMergeFields(Lava.LavaHelper.GetCommonMergeFields(null, null, new Lava.CommonMergeFieldsOptions {
                GetLegacyGlobalMergeFields = false
            }));

            // Get the Rock organization time zone. If not found back to the
            // OS time zone. If not found just use Greenwich.
            var timeZoneMapping = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping;
            var timeZoneName    = timeZoneMapping.GetValueOrNull(RockDateTime.OrgTimeZoneInfo.Id)
                                  ?? timeZoneMapping.GetValueOrNull(TimeZoneInfo.Local.Id)
                                  ?? "GMT";

            //
            // Initialize the base update package settings.
            //
            var package = new UpdatePackage
            {
                ApplicationType                  = additionalSettings.ShellType ?? ShellType.Blank,
                ApplicationVersionId             = versionId,
                CssStyles                        = cssStyles,
                LoginPageGuid                    = site.LoginPageId.HasValue ? PageCache.Get(site.LoginPageId.Value)?.Guid : null,
                ProfileDetailsPageGuid           = additionalSettings.ProfilePageId.HasValue ? PageCache.Get(additionalSettings.ProfilePageId.Value)?.Guid : null,
                PhoneFormats                     = phoneFormats,
                DefinedValues                    = definedValues,
                TabsOnBottomOnAndroid            = additionalSettings.TabLocation == TabLocation.Bottom,
                HomepageRoutingLogic             = additionalSettings.HomepageRoutingLogic,
                DoNotEnableNotificationsAtLaunch = !additionalSettings.EnableNotificationsAutomatically,
                TimeZone             = timeZoneName,
                PushTokenUpdateValue = additionalSettings.PushTokenUpdateValue
            };

            //
            // Setup the appearance settings.
            //
            package.AppearanceSettings.BarBackgroundColor     = additionalSettings.BarBackgroundColor;
            package.AppearanceSettings.MenuButtonColor        = additionalSettings.MenuButtonColor;
            package.AppearanceSettings.ActivityIndicatorColor = additionalSettings.ActivityIndicatorColor;
            package.AppearanceSettings.FlyoutXaml             = additionalSettings.FlyoutXaml;
            package.AppearanceSettings.ToastXaml = additionalSettings.ToastXaml;
            package.AppearanceSettings.NavigationBarActionsXaml = additionalSettings.NavigationBarActionXaml;
            package.AppearanceSettings.LockedPhoneOrientation   = additionalSettings.LockedPhoneOrientation;
            package.AppearanceSettings.LockedTabletOrientation  = additionalSettings.LockedTabletOrientation;
            package.AppearanceSettings.PaletteColors.Add("text-color", additionalSettings.DownhillSettings.TextColor);
            package.AppearanceSettings.PaletteColors.Add("heading-color", additionalSettings.DownhillSettings.HeadingColor);
            package.AppearanceSettings.PaletteColors.Add("background-color", additionalSettings.DownhillSettings.BackgroundColor);
            package.AppearanceSettings.PaletteColors.Add("app-primary", additionalSettings.DownhillSettings.ApplicationColors.Primary);
            package.AppearanceSettings.PaletteColors.Add("app-secondary", additionalSettings.DownhillSettings.ApplicationColors.Secondary);
            package.AppearanceSettings.PaletteColors.Add("app-success", additionalSettings.DownhillSettings.ApplicationColors.Success);
            package.AppearanceSettings.PaletteColors.Add("app-info", additionalSettings.DownhillSettings.ApplicationColors.Info);
            package.AppearanceSettings.PaletteColors.Add("app-danger", additionalSettings.DownhillSettings.ApplicationColors.Danger);
            package.AppearanceSettings.PaletteColors.Add("app-warning", additionalSettings.DownhillSettings.ApplicationColors.Warning);
            package.AppearanceSettings.PaletteColors.Add("app-light", additionalSettings.DownhillSettings.ApplicationColors.Light);
            package.AppearanceSettings.PaletteColors.Add("app-dark", additionalSettings.DownhillSettings.ApplicationColors.Dark);
            package.AppearanceSettings.PaletteColors.Add("app-brand", additionalSettings.DownhillSettings.ApplicationColors.Brand);

            if (site.FavIconBinaryFileId.HasValue)
            {
                package.AppearanceSettings.LogoUrl = $"{applicationRoot}/GetImage.ashx?Id={site.FavIconBinaryFileId.Value}";
            }

            //
            // Load all the layouts.
            //
            foreach (var layout in LayoutCache.All().Where(l => l.SiteId == site.Id))
            {
                var mobileLayout = new MobileLayout
                {
                    LayoutGuid = layout.Guid,
                    Name       = layout.Name,
                    LayoutXaml = deviceType == DeviceType.Tablet ? layout.LayoutMobileTablet : layout.LayoutMobilePhone
                };

                package.Layouts.Add(mobileLayout);
            }

            //
            // Load all the pages.
            //
            var blockIds = new List <int>();

            using (var rockContext = new RockContext())
            {
                AddPagesToUpdatePackage(package, applicationRoot, rockContext, new[] { PageCache.Get(site.DefaultPageId.Value) });

                blockIds = new BlockService(rockContext).Queryable()
                           .Where(b => b.Page != null && b.Page.Layout.SiteId == site.Id && b.BlockType.EntityTypeId.HasValue)
                           .OrderBy(b => b.Order)
                           .Select(b => b.Id)
                           .ToList();
            }

            //
            // Load all the blocks.
            //
            foreach (var blockId in blockIds)
            {
                var block           = BlockCache.Get(blockId);
                var blockEntityType = block?.BlockType.EntityType.GetEntityType();

                if (blockEntityType != null && typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockEntityType))
                {
                    var additionalBlockSettings = block.AdditionalSettings.FromJsonOrNull <AdditionalBlockSettings>() ?? new AdditionalBlockSettings();

                    var mobileBlockEntity = (Rock.Blocks.IRockMobileBlockType)Activator.CreateInstance(blockEntityType);

                    mobileBlockEntity.BlockCache     = block;
                    mobileBlockEntity.PageCache      = block.Page;
                    mobileBlockEntity.RequestContext = new Net.RockRequestContext();

                    var attributes = block.Attributes
                                     .Select(a => a.Value)
                                     .Where(a => a.Categories.Any(c => c.Name == "custommobile"));

                    var mobileBlock = new MobileBlock
                    {
                        PageGuid            = block.Page.Guid,
                        Zone                = block.Zone,
                        BlockGuid           = block.Guid,
                        RequiredAbiVersion  = mobileBlockEntity.RequiredMobileAbiVersion,
                        BlockType           = mobileBlockEntity.MobileBlockType,
                        ConfigurationValues = mobileBlockEntity.GetBlockInitialization(Blocks.RockClientType.Mobile),
                        Order               = block.Order,
                        AttributeValues     = GetMobileAttributeValues(block, attributes),
                        PreXaml             = block.PreHtml,
                        PostXaml            = block.PostHtml,
                        CssClasses          = block.CssClass,
                        CssStyles           = additionalBlockSettings.CssStyles,
                        ShowOnTablet        = additionalBlockSettings.ShowOnTablet,
                        ShowOnPhone         = additionalBlockSettings.ShowOnPhone,
                        RequiresNetwork     = additionalBlockSettings.RequiresNetwork,
                        NoNetworkContent    = additionalBlockSettings.NoNetworkContent,
                        AuthorizationRules  = string.Join(",", GetOrderedExplicitAuthorizationRules(block))
                    };

                    package.Blocks.Add(mobileBlock);
                }
            }

            //
            // Load all the campuses.
            //
            foreach (var campus in CampusCache.All().Where(c => c.IsActive ?? true))
            {
                var mobileCampus = new MobileCampus
                {
                    Guid = campus.Guid,
                    Name = campus.Name
                };

                if (campus.Location != null)
                {
                    if (campus.Location.Latitude.HasValue && campus.Location.Longitude.HasValue)
                    {
                        mobileCampus.Latitude  = campus.Location.Latitude;
                        mobileCampus.Longitude = campus.Location.Longitude;
                    }

                    if (!string.IsNullOrWhiteSpace(campus.Location.Street1))
                    {
                        mobileCampus.Street1    = campus.Location.Street1;
                        mobileCampus.City       = campus.Location.City;
                        mobileCampus.State      = campus.Location.State;
                        mobileCampus.PostalCode = campus.Location.PostalCode;
                    }
                }

                // Get the campus time zone, If not found try the Rock
                // organization time zone. If not found back to the
                // OS time zone. If not found just use Greenwich.
                mobileCampus.TimeZone = timeZoneMapping.GetValueOrNull(campus.TimeZoneId ?? string.Empty)
                                        ?? timeZoneMapping.GetValueOrNull(RockDateTime.OrgTimeZoneInfo.Id)
                                        ?? timeZoneMapping.GetValueOrNull(TimeZoneInfo.Local.Id)
                                        ?? "GMT";

                package.Campuses.Add(mobileCampus);
            }

            return(package);
        }
Beispiel #22
0
 /// <summary>
 /// Gets the cache object associated with this Entity
 /// </summary>
 /// <returns></returns>
 public IEntityCache GetCacheObject()
 {
     return(BlockCache.Get(this.Id));
 }
        /// <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));
            }
        }
        /// <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 #25
0
        /// <summary>
        /// Handles the Click event of the btnDefault 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 btnDefault_Click(object sender, EventArgs e)
        {
            var bioBlock = BlockCache.Get(Rock.SystemGuid.Block.BIO.AsGuid());

            // Record an exception if the stock Bio block has been deleted but continue processing
            // the remaining settings.
            if (bioBlock == null)
            {
                var errorMessage = string.Format("Stock Bio block ({0}) is missing.", Rock.SystemGuid.Block.BIO);
                ExceptionLogService.LogException(new Exception(errorMessage));
            }
            else
            {
                List <Guid> workflowActionGuidList = bioBlock.GetAttributeValues("WorkflowActions").AsGuidList();
                if (workflowActionGuidList == null || workflowActionGuidList.Count == 0)
                {
                    // Add to Bio Workflow Actions
                    bioBlock.SetAttributeValue("WorkflowActions", Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY);
                    ///BackgroundCheckContainer.Instance.Components
                }
                else
                {
                    //var workflowActionValues = workflowActionValue.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList();
                    Guid guid = Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid();
                    if (!workflowActionGuidList.Any(w => w == guid))
                    {
                        // Add Checkr to Bio Workflow Actions
                        workflowActionGuidList.Add(guid);
                    }

                    // Remove PMM from Bio Workflow Actions
                    guid = CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid();
                    workflowActionGuidList.RemoveAll(w => w == guid);
                    bioBlock.SetAttributeValue("WorkflowActions", workflowActionGuidList.AsDelimited(","));
                }

                bioBlock.SaveAttributeValue("WorkflowActions");
            }

            string pmmTypeName  = (typeof(Rock.Security.BackgroundCheck.ProtectMyMinistry)).FullName;
            var    pmmComponent = BackgroundCheckContainer.Instance.Components.Values.FirstOrDefault(c => c.Value.TypeName == pmmTypeName);

            pmmComponent.Value.SetAttributeValue("Active", "True");
            pmmComponent.Value.SaveAttributeValue("Active");
            // Set as the default provider in the system setting
            SystemSettings.SetValue(Rock.SystemKey.SystemSetting.DEFAULT_BACKGROUND_CHECK_PROVIDER, pmmTypeName);

            using (var rockContext = new RockContext())
            {
                WorkflowTypeService workflowTypeService = new WorkflowTypeService(rockContext);
                // Rename PMM Workflow
                var pmmWorkflowAction = workflowTypeService.Get(Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid());
                pmmWorkflowAction.Name = "Background Check";

                var checkrWorkflowAction = workflowTypeService.Get(CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid());
                // Rename Checkr Workflow
                checkrWorkflowAction.Name = CheckrConstants.CHECKR_WORKFLOW_TYPE_NAME;

                rockContext.SaveChanges();

                // Enable PMM packages and disable Checkr packages
                DefinedValueService definedValueService = new DefinedValueService(rockContext);
                var packages = definedValueService
                               .GetByDefinedTypeGuid(Rock.SystemGuid.DefinedType.BACKGROUND_CHECK_TYPES.AsGuid())
                               .ToList();

                foreach (var package in packages)
                {
                    package.IsActive = package.ForeignId == 1;
                }

                rockContext.SaveChanges();
            }

            ShowDetail();
        }
Beispiel #26
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)
        {
            int?   entityTypeId   = PageParameter("EntityTypeId").AsIntegerOrNull();
            string entityTypeName = string.Empty;
            Type   type           = null;

            // Get Entity Type
            if (entityTypeId.HasValue)
            {
                var entityType = EntityTypeCache.Get(entityTypeId.Value);
                if (entityType != null)
                {
                    entityTypeName = entityType.FriendlyName;
                    type           = entityType.GetEntityType();
                }
            }

            // Get Entity Id
            int entityId = PageParameter("EntityId").AsIntegerOrNull() ?? 0;

            // Get object type
            if (type != null)
            {
                if (entityId == 0)
                {
                    iSecured = (ISecured)Activator.CreateInstance(type);
                }
                else
                {
                    // Get the context type since this may be for a non-rock core object
                    Type contextType = null;
                    var  contexts    = Rock.Reflection.SearchAssembly(type.Assembly, typeof(Rock.Data.DbContext));
                    if (contexts.Any())
                    {
                        contextType = contexts.First().Value;
                    }
                    else
                    {
                        contextType = typeof(RockContext);
                    }

                    Type   serviceType = typeof(Rock.Data.Service <>);
                    Type[] modelType   = { type };
                    Type   service     = serviceType.MakeGenericType(modelType);
                    var    getMethod   = service.GetMethod("Get", new Type[] { typeof(int) });

                    var context         = Activator.CreateInstance(contextType);
                    var serviceInstance = Activator.CreateInstance(service, new object[] { context });
                    iSecured = getMethod.Invoke(serviceInstance, new object[] { entityId }) as ISecured;
                }

                var block = iSecured as Rock.Model.Block;
                if (block != null)
                {
                    // If the entity is a block, get any actions that were updated or added by the block type using
                    // one or more SecurityActionAttributes.
                    var blockCache = BlockCache.Get(block.Id);
                    if (blockCache != null && blockCache.BlockType != null)
                    {
                        // just in case the block hasn't had its security actions set (they get loaded on page load), set them
                        if (blockCache.BlockType.SecurityActions == null)
                        {
                            if (block.BlockType.Path.IsNotNullOrWhiteSpace())
                            {
                                blockCache.BlockType.SetSecurityActions(TemplateControl.LoadControl(block.BlockType.Path) as RockBlock);
                            }
                            if (block.BlockType.EntityTypeId.HasValue)
                            {
                                blockCache.BlockType.SetSecurityActions(blockCache.BlockType.GetCompiledType());
                            }
                        }

                        foreach (var action in blockCache.BlockType.SecurityActions)
                        {
                            if (block.SupportedActions.ContainsKey(action.Key))
                            {
                                block.SupportedActions[action.Key] = action.Value;
                            }
                            else
                            {
                                block.SupportedActions.Add(action.Key, action.Value);
                            }
                        }
                    }

                    iSecured = block;
                }

                if (iSecured != null)
                {
                    if (iSecured.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson))
                    {
                        if (iSecured.SupportedActions.Any())
                        {
                            lActionDescription.Text = iSecured.SupportedActions.FirstOrDefault().Value;
                        }

                        rptActions.DataSource = iSecured.SupportedActions;
                        rptActions.DataBind();

                        rGrid.DataKeyNames        = new string[] { "Id" };
                        rGrid.GridReorder        += new GridReorderEventHandler(rGrid_GridReorder);
                        rGrid.GridRebind         += new GridRebindEventHandler(rGrid_GridRebind);
                        rGrid.RowDataBound       += new GridViewRowEventHandler(rGrid_RowDataBound);
                        rGrid.ShowHeaderWhenEmpty = false;
                        rGrid.EmptyDataText       = string.Empty;
                        rGrid.ShowActionRow       = false;

                        rGridParentRules.DataKeyNames        = new string[] { "Id" };
                        rGridParentRules.ShowHeaderWhenEmpty = false;
                        rGridParentRules.EmptyDataText       = string.Empty;
                        rGridParentRules.ShowActionRow       = false;

                        BindRoles();

                        string scriptFormat = @"
                    Sys.Application.add_load(function () {{
                        $('#modal-popup div.modal-header h3 small', window.parent.document).html('{0}');
                    }});
                ";
                        string script       = string.Format(scriptFormat, HttpUtility.JavaScriptStringEncode(iSecured.ToString()));

                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), string.Format("set-html-{0}", this.ClientID), script, true);
                    }
                    else
                    {
                        nbMessage.Text = "Unfortunately, you are not able to edit security because you do not belong to a role that has been configured to allow administration of this item.";
                    }
                }
                else
                {
                    nbMessage.Text = "The item you are trying to secure does not exist or does not implement ISecured.";
                }
            }
            else
            {
                nbMessage.Text = string.Format("The requested entity type ('{0}') could not be loaded to determine security attributes.", entityTypeName);
            }

            base.OnInit(e);
        }
Beispiel #27
0
        public void TestJounalSST()
        {
            using var cache  = new BlockCache(100);
            using var scache = cache.Get(0);

            using var js = new KeepOpenMemoryStream();
            using var ms = new KeepOpenMemoryStream();
            using (var journal = new Journal(js, new PlaneDBOptions())) {
                for (var i = 0; i < COUNT; ++i)
                {
                    var v = i.ToString();
                    journal.Put(v, v + v + v);
                    if (i % 10 == 0)
                    {
                        journal.Put("o" + v, v + v + v);
                    }

                    if (i % 30 == 0)
                    {
                        Assert.IsTrue(journal.Update("o" + v, v + v + v + v));
                    }
                    else if (i % 20 == 0)
                    {
                        journal.Remove("o" + v);
                    }
                }
            }

            using (var builder = new SSTableBuilder(ms, new PlaneDBOptions())) {
                Journal.ReplayOnto(js, new PlaneDBOptions(), builder);
            }

            using var table = new SSTable(ms, scache, new PlaneDBOptions());
            for (var i = 0; i < COUNT; ++i)
            {
                var v = i.ToString();
                Assert.IsTrue(table.ContainsKey(v, out _));
                Assert.IsFalse(table.ContainsKey($"nope{v}", out _));
                Assert.IsTrue(table.TryGet(v, out var s));
                Assert.AreEqual(v + v + v, s);

                if (i % 30 == 0)
                {
                    Assert.IsTrue(table.ContainsKey("o" + v, out _));
                    Assert.IsTrue(table.TryGet("o" + v, out var val));
                    Assert.AreEqual(v + v + v + v, val);
                }
                else if (i % 20 == 0)
                {
                    Assert.IsTrue(table.ContainsKey("o" + v, out _));
                    Assert.IsTrue(table.TryGet("o" + v, out var val));
                    Assert.IsNull(val);
                }
                else if (i % 10 == 0)
                {
                    Assert.IsTrue(table.ContainsKey("o" + v, out _));
                    Assert.IsTrue(table.TryGet("o" + v, out var val));
                    Assert.AreEqual(v + v + v, val);
                }
            }
        }
        public MobilePage GetPage(int id, string parameter = "")
        {
            var person = GetPerson();

            if (!HttpContext.Current.Items.Contains("CurrentPerson"))
            {
                HttpContext.Current.Items.Add("CurrentPerson", person);
            }

            var pageCache = PageCache.Get(id);

            if (pageCache == null || !pageCache.IsAuthorized(Authorization.VIEW, person))
            {
                return(new MobilePage());
            }

            SavePageViewInteraction(pageCache, person);

            string theme      = pageCache.Layout.Site.Theme;
            string layout     = pageCache.Layout.FileName;
            string layoutPath = PageCache.FormatPath(theme, layout);

            Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage));

            MobilePage mobilePage = new MobilePage();

            mobilePage.Layout    = AvalancheUtilities.GetLayout(pageCache.Layout.Name);
            mobilePage.Title     = pageCache.PageTitle;
            mobilePage.ShowTitle = pageCache.PageDisplayTitle;

            foreach (var attribute in pageCache.Attributes)
            {
                mobilePage.Attributes.Add(attribute.Key, pageCache.GetAttributeValue(attribute.Key));
            }
            foreach (var block in pageCache.Blocks)
            {
                if (block.IsAuthorized(Authorization.VIEW, person))
                {
                    var blockCache = BlockCache.Get(block.Id);
                    try
                    {
                        var control = ( RockBlock )cmsPage.TemplateControl.LoadControl(blockCache.BlockType.Path);
                        if (control is RockBlock && control is IMobileResource)
                        {
                            control.SetBlock(pageCache, blockCache);
                            var mobileResource = control as IMobileResource;
                            var mobileBlock    = mobileResource.GetMobile(parameter);
                            mobileBlock.BlockId = blockCache.Id;
                            mobileBlock.Zone    = blockCache.Zone;
                            mobilePage.Blocks.Add(mobileBlock);
                        }
                    }
                    catch (Exception e)
                    {
                        ExceptionLogService.LogException(e, HttpContext.Current);
                    }
                }
            }
            HttpContext.Current.Response.Headers.Set("TTL", pageCache.OutputCacheDuration.ToString());
            return(mobilePage);
        }
Beispiel #29
0
        public HttpResponseMessage ProcessMobileCheckin(string param)
        {
            try
            {
                var session = HttpContext.Current.Session;

                var currentCheckInState = session["CheckInState"] as CheckInState;
                if (currentCheckInState.CheckIn.SearchType.Guid != Constants.CHECKIN_SEARCH_TYPE_USERLOGIN.AsGuid())
                {
                    throw new Exception(); //We'll catch this later and return a forbidden
                }

                var localDeviceConfigCookie = HttpContext.Current.Request.Cookies[CheckInCookieKey.LocalDeviceConfig].Value;
                var localDevice             = localDeviceConfigCookie.FromJsonOrNull <LocalDeviceConfiguration>();

                var rockContext = new Rock.Data.RockContext();

                UserLoginService userLoginService = new UserLoginService(rockContext);
                var family = userLoginService.Queryable().AsNoTracking()
                             .Where(u => u.UserName == currentCheckInState.CheckIn.SearchValue)
                             .Select(u => u.Person.PrimaryFamily)
                             .FirstOrDefault();
                var checkinFamily = new CheckInFamily
                {
                    Group    = family.Clone(false),
                    Caption  = family.ToString(),
                    Selected = true
                };
                currentCheckInState.CheckIn.Families.Add(checkinFamily);
                SaveState(session, currentCheckInState);

                Guid   blockGuid        = ( Guid )session["BlockGuid"];
                var    block            = BlockCache.Get(blockGuid);
                Guid?  workflowGuid     = block.GetAttributeValue("WorkflowType").AsGuidOrNull();
                string workflowActivity = block.GetAttributeValue("WorkflowActivity");

                List <string> errors;
                var           workflowService = new WorkflowService(rockContext);
                var           workflowType    = WorkflowTypeCache.Get(workflowGuid.Value);

                var CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, currentCheckInState.Kiosk.Device.Name, rockContext);

                var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault();
                if (activityType != null)
                {
                    WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext);
                    if (workflowService.Process(CurrentWorkflow, currentCheckInState, out errors))
                    {
                        if (errors.Any())
                        {
                            var innerException = new Exception(string.Join(" -- ", errors));
                            ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException));
                        }

                        // Keep workflow active for continued processing
                        CurrentWorkflow.CompletedDateTime = null;
                        SaveState(session, currentCheckInState);
                        List <CheckInFamily> families = currentCheckInState.CheckIn.Families;
                        families = families.OrderBy(f => f.Caption).ToList();
                        return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, param));
                    }
                    else
                    {
                        if (errors.Any())
                        {
                            var innerException = new Exception(string.Join(" -- ", errors));
                            ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details.", innerException));
                        }
                        else
                        {
                            ExceptionLogService.LogException(new Exception("Process Mobile Checkin failed initial workflow. See inner exception for details."));
                        }
                    }
                }
                else
                {
                    return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("Workflow type does not have a '{0}' activity type", workflowActivity)));
                }
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, String.Join("\n", errors)));
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, HttpContext.Current);
                return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden"));
            }
        }
        /// <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;

            // Set the validation group on any custom settings providers.
            SetValidationGroup(CustomSettingsProviders.Values.ToArray(), this.BlockValidationGroup);

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

            if (!blockId.HasValue)
            {
                return;
            }

            var       _block = BlockCache.Get(blockId.Value);
            SiteCache _site  = null;

            // Get site info from Page -> Layout -> Site
            if (_block.Page.IsNotNull())
            {
                _site = SiteCache.Get(_block.Page.SiteId);
            }
            else if (_block.Layout.IsNotNull())
            {
                _site = SiteCache.Get(_block.Layout.SiteId);
            }
            else if (_block.SiteId.HasValue)
            {
                _site = SiteCache.Get(_block.SiteId.Value);
            }

            // Change Pre/Post text labels if this is a mobile block
            if (_site.IsNotNull() && _site.SiteType == SiteType.Mobile)
            {
                cePostHtml.Label = "Post-XAML";
                cePreHtml.Label  = "Pre-XAML";
            }

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