コード例 #1
0
        /// <summary>
        /// Used to manually flush the attribute cache.
        /// </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 btnClearCache_Click(object sender, EventArgs e)
        {
            var msgs = new List <string>();

            // Clear the static object that contains all auth rules (so that it will be refreshed)
            Rock.Security.Authorization.Flush();
            msgs.Add("Authorizations have been cleared");

            // Flush the static entity attributes cache
            Rock.Web.Cache.AttributeCache.FlushEntityAttributes();
            msgs.Add("EntityAttributes have been cleared");

            // Clear all cached items
            Rock.Web.Cache.RockMemoryCache.Clear();
            msgs.Add("RockMemoryCache has been cleared");

            // Flush Site Domains
            Rock.Web.Cache.SiteCache.Flush();

            // Flush today's Check-in Codes
            Rock.Model.AttendanceCodeService.FlushTodaysCodes();

            string webAppPath = Server.MapPath("~");

            // Check for any unregistered entity types, field types, and block types
            EntityTypeService.RegisterEntityTypes(webAppPath);
            FieldTypeService.RegisterFieldTypes(webAppPath);
            BlockTypeService.RegisterBlockTypes(webAppPath, Page, false);
            msgs.Add("EntityTypes, FieldTypes, BlockTypes have been re-registered");

            // Clear workflow trigger cache
            Rock.Workflow.TriggerCache.Refresh();

            // Delete all cached files
            try
            {
                var dirInfo = new DirectoryInfo(Path.Combine(webAppPath, "App_Data/Cache"));
                foreach (var childDir in dirInfo.GetDirectories())
                {
                    childDir.Delete(true);
                }
                foreach (var file in dirInfo.GetFiles().Where(f => f.Name != ".gitignore"))
                {
                    file.Delete();
                }
                msgs.Add("Cached files have been deleted");
            }
            catch (Exception ex)
            {
                nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                nbMessage.Visible             = true;
                nbMessage.Text = "The following error occurred when attempting to delete cached files: " + ex.Message;
                return;
            }

            nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Success;
            nbMessage.Visible             = true;
            nbMessage.Title = "Clear Cache";
            nbMessage.Text  = string.Format("<p>{0}</p>", msgs.AsDelimited("<br />"));
        }
コード例 #2
0
ファイル: FieldTypeCache.cs プロジェクト: shelsonjava/Rock
        /// <summary>
        /// Returns FieldType object from cache.  If fieldType does not already exist in cache, it
        /// will be read and added to cache
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static FieldTypeCache Read(int id)
        {
            string cacheKey = FieldTypeCache.CacheKey(id);

            ObjectCache    cache     = MemoryCache.Default;
            FieldTypeCache fieldType = cache[cacheKey] as FieldTypeCache;

            if (fieldType != null)
            {
                return(fieldType);
            }
            else
            {
                var fieldTypeService = new FieldTypeService();
                var fieldTypeModel   = fieldTypeService.Get(id);
                if (fieldTypeModel != null)
                {
                    fieldTypeModel.LoadAttributes();
                    fieldType = new FieldTypeCache(fieldTypeModel);

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set(cacheKey, fieldType, cachePolicy);
                    cache.Set(fieldType.Guid.ToString(), fieldType.Id, cachePolicy);

                    return(fieldType);
                }
                else
                {
                    return(null);
                }
            }
        }
コード例 #3
0
ファイル: FieldTypeCache.cs プロジェクト: shelsonjava/Rock
        /// <summary>
        /// Reads the specified GUID.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        public static FieldTypeCache Read(Guid guid)
        {
            ObjectCache cache    = MemoryCache.Default;
            object      cacheObj = cache[guid.ToString()];

            if (cacheObj != null)
            {
                return(Read((int)cacheObj));
            }
            else
            {
                var fieldTypeService = new FieldTypeService();
                var fieldTypeModel   = fieldTypeService.Get(guid);
                if (fieldTypeModel != null)
                {
                    fieldTypeModel.LoadAttributes();
                    var fieldType = new FieldTypeCache(fieldTypeModel);

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set(FieldTypeCache.CacheKey(fieldType.Id), fieldType, cachePolicy);
                    cache.Set(fieldType.Guid.ToString(), fieldType.Id, cachePolicy);

                    return(fieldType);
                }
                else
                {
                    return(null);
                }
            }
        }
コード例 #4
0
ファイル: FieldTypeCache.cs プロジェクト: timothybaloyi/Rock
        private static int LoadByGuid2(Guid guid, RockContext rockContext)
        {
            var fieldTypeService = new FieldTypeService(rockContext);

            return(fieldTypeService
                   .Queryable().AsNoTracking()
                   .Where(c => c.Guid.Equals(guid))
                   .Select(c => c.Id)
                   .FirstOrDefault());
        }
コード例 #5
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns()
        {
            ddlDateRangeType.BindToEnum(typeof(DateRangeTypeEnum));

            FieldTypeService fieldTypeService = new FieldTypeService();
            List <FieldType> fieldTypes       = fieldTypeService.Queryable().OrderBy(a => a.Name).ToList();

            ddlAttributeFieldType.DataSource = fieldTypes;
            ddlAttributeFieldType.DataBind();
        }
コード例 #6
0
ファイル: FieldTypeCache.cs プロジェクト: timothybaloyi/Rock
        private static FieldTypeCache LoadById2(int id, RockContext rockContext)
        {
            var fieldTypeService = new FieldTypeService(rockContext);
            var fieldTypeModel   = fieldTypeService.Get(id);

            if (fieldTypeModel != null)
            {
                return(new FieldTypeCache(fieldTypeModel));
            }

            return(null);
        }
コード例 #7
0
 public JsonResult GetFieldTypes()
 {
     try
     {
         var records = FieldTypeService.QueryFieldTypes();
         return(Json(records, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         return(Json(ex.Message, JsonRequestBehavior.AllowGet));
     }
 }
コード例 #8
0
ファイル: Attributes.ascx.cs プロジェクト: jh2mhs8/Rock-ChMS
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="attributeId">The attribute id.</param>
        protected void ShowEdit(int attributeId)
        {
            var attributeModel = new AttributeService().Get(attributeId);

            if (attributeModel != null)
            {
                var attribute = AttributeCache.Read(attributeModel);

                lActionTitle.Text = "Edit Attribute";
                hfId.Value        = attribute.Id.ToString();

                tbKey.Text                 = attribute.Key;
                tbName.Text                = attribute.Name;
                tbCategory.Text            = attribute.Category;
                tbDescription.Text         = attribute.Description;
                ddlFieldType.SelectedValue = attribute.FieldType.Id.ToString();
                BuildConfigControls(attribute.QualifierValues);
                tbDefaultValue.Text  = attribute.DefaultValue;
                cbMultiValue.Checked = attribute.IsMultiValue;
                cbRequired.Checked   = attribute.IsRequired;
            }
            else
            {
                lActionTitle.Text = "Add Attribute";
                hfId.Value        = string.Empty;

                tbKey.Text         = string.Empty;
                tbName.Text        = string.Empty;
                tbCategory.Text    = ddlCategoryFilter.SelectedValue != "[All]" ? ddlCategoryFilter.SelectedValue : string.Empty;
                tbDescription.Text = string.Empty;

                FieldTypeService fieldTypeService = new FieldTypeService();
                var fieldTypeModel = fieldTypeService.GetByName("Text").FirstOrDefault();
                if (fieldTypeModel != null)
                {
                    ddlFieldType.SelectedValue = fieldTypeModel.Id.ToString();
                }

                BuildConfigControls();

                tbDefaultValue.Text  = string.Empty;
                cbMultiValue.Checked = false;
                cbRequired.Checked   = false;
            }

            pnlList.Visible    = false;
            pnlDetails.Visible = true;
        }
コード例 #9
0
ファイル: SystemInfo.vue.cs プロジェクト: cabal95/RockWebCore
        public IActionResult btnClearCache_Click()
        {
            var msgs = RockCache.ClearAllCachedItems();

            // Flush today's Check-in Codes
            Rock.Model.AttendanceCodeService.FlushTodaysCodes();

#if false
            string webAppPath = Server.MapPath( "~" );

            // Check for any unregistered entity types, field types, and block types
            EntityTypeService.RegisterEntityTypes( webAppPath );
            FieldTypeService.RegisterFieldTypes( webAppPath );
            BlockTypeService.RegisterBlockTypes( webAppPath, Page, false );
            msgs.Add( "EntityTypes, FieldTypes, BlockTypes have been re-registered" );

            // Delete all cached files
            try
            {
                var dirInfo = new DirectoryInfo( Path.Combine( webAppPath, "App_Data/Cache" ) );
                foreach ( var childDir in dirInfo.GetDirectories() )
                {
                    childDir.Delete( true );
                }
                foreach ( var file in dirInfo.GetFiles().Where( f => f.Name != ".gitignore" ) )
                {
                    file.Delete();
                }
                msgs.Add( "Cached files have been deleted" );
            }
            catch ( Exception ex )
            {
                return new OkObjectResult( new {
                    Error = true,
                    Messages = new [] { $"The following error occurred when attempting to delete cahced files: {ex.Message}"
                } );
            }
#endif

            return new OkObjectResult( new {
                Error = false,
                Messages = msgs
            } );
        }

        #endregion
    }
コード例 #10
0
        public JsonResult UpdateEntity(List <KeyValue> keyValues)
        {
            try
            {
                var id                   = keyValues.FirstOrDefault(x => x.Key == "Id")?.Value;
                var name                 = keyValues.FirstOrDefault(x => x.Key == "Name")?.Value;
                var displayName          = keyValues.FirstOrDefault(x => x.Key == "DisplayName")?.Value;
                var pluralName           = keyValues.FirstOrDefault(x => x.Key == "PluralName")?.Value;
                var isDisplayOnSideMenu  = keyValues.FirstOrDefault(x => x.Key == "IsDisplayOnSideMenu")?.Value;
                var sideMenuParentItemId = keyValues.FirstOrDefault(x => x.Key == "SideMenuParentItemId")?.Value;
                var sideMenuItemPosition = keyValues.FirstOrDefault(x => x.Key == "SideMenuItemPosition")?.Value;

                var fieldTypes = FieldTypeService.QueryFieldTypes();

                #region Update entity record
                var returnValue = SharedService.ExecutePostSqlStoredProcedure("[eduq].[Entity_update]",
                                                                              new List <SqlParameter>
                {
                    new SqlParameter("@id", id),
                    new SqlParameter("@name", name),
                    new SqlParameter("@displayName", displayName),
                    new SqlParameter("@pluralName", pluralName),
                    new SqlParameter("@isDisplayOnSideMenu", isDisplayOnSideMenu),
                    new SqlParameter("@sideMenuParentItemId", sideMenuParentItemId),
                    new SqlParameter("@sideMenuItemPosition", sideMenuItemPosition),
                    new SqlParameter("@stateId", 1)
                });

                if (returnValue != 1)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                var newlyCreatedEntity = EntityService.QueryEntityById(Guid.Parse(id));
                if (newlyCreatedEntity == null)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                return(Json(new { message = id, type = "success" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(ex.Message, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #11
0
        /// <summary>
        /// Used to manually flush the attribute cache.
        /// </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 btnClearCache_Click(object sender, EventArgs e)
        {
            var msgs = RockCache.ClearAllCachedItems();

            // Flush today's Check-in Codes
            Rock.Model.AttendanceCodeService.FlushTodaysCodes();

            string webAppPath = Server.MapPath("~");

            // Check for any unregistered entity types, field types, and block types
            EntityTypeService.RegisterEntityTypes();
            FieldTypeService.RegisterFieldTypes();

            BlockTypeService.FlushRegistrationCache();
            BlockTypeService.RegisterBlockTypes(webAppPath, Page, false);

            msgs.Add("EntityTypes, FieldTypes, BlockTypes have been re-registered");

            // Delete all cached files
            try
            {
                var dirInfo = new DirectoryInfo(Path.Combine(webAppPath, "App_Data/Cache"));
                foreach (var childDir in dirInfo.GetDirectories())
                {
                    childDir.Delete(true);
                }
                foreach (var file in dirInfo.GetFiles().Where(f => f.Name != ".gitignore"))
                {
                    file.Delete();
                }
                msgs.Add("Cached files have been deleted");
            }
            catch (Exception ex)
            {
                nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                nbMessage.Visible             = true;
                nbMessage.Text = "The following error occurred when attempting to delete cached files: " + ex.Message;
                return;
            }

            nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Success;
            nbMessage.Visible             = true;
            nbMessage.Title = "Clear Cache";
            nbMessage.Text  = string.Format("<p>{0}</p>", msgs.AsDelimited("<br />"));
        }
コード例 #12
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string attributeKey = GetAttributeValue("OAuthConfigAttributeKey");
            Dictionary <string, string> settings = GlobalAttributesCache.Value(attributeKey).AsDictionary();

            settings["OAuthAuthorizePath"]        = "/" + ddlAuthorizeRoute.SelectedValue;
            settings["OAuthLoginPath"]            = "/" + ddlLoginRoute.SelectedValue;
            settings["OAuthLogoutPath"]           = "/" + ddlLogoutRoute.SelectedValue;
            settings["OAuthTokenPath"]            = "/" + ddlTokenRoute.SelectedValue;
            settings["OAuthRequireSsl"]           = cbSSLRequired.Checked.ToString();
            settings["OAuthTokenLifespan"]        = tbTokenLifespan.Text;
            settings["OAuthRefreshTokenLifespan"] = tbRefreshTokenLifespan.Text;

            RockContext      context          = new RockContext();
            AttributeService attributeService = new AttributeService(context);

            Rock.Model.Attribute attribute = attributeService.Queryable().Where(a => a.Key == attributeKey).FirstOrDefault();
            if (attribute == null)
            {
                attribute             = new Rock.Model.Attribute();
                attribute.Name        = "OAuth Settings";
                attribute.Description = "Settings for the OAuth server plugin.";
                attribute.Key         = "OAuthSettings";
                FieldTypeService fieldTypeService = new FieldTypeService(context);
                attribute.FieldType = fieldTypeService.Get(Rock.SystemGuid.FieldType.KEY_VALUE_LIST.AsGuid());
                context.SaveChanges();
            }
            // Update the actual attribute value.
            AttributeValueService attributeValueService = new AttributeValueService(context);
            AttributeValue        attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, null);

            if (attributeValue == null)
            {
                attributeValue             = new AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValueService.Add(attributeValue);
            }
            attributeValue.Value = string.Join("|", settings.Select(a => a.Key + "^" + a.Value).ToList());
            context.SaveChanges();

            // Flush the cache(s)
            AttributeCache.Flush(attribute.Id);
            GlobalAttributesCache.Flush();
        }
コード例 #13
0
        /// <summary>
        /// Used to manually flush the attribute cache.
        /// </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 btnClearCache_Click(object sender, EventArgs e)
        {
            // Clear all cached items
            Rock.Web.Cache.RockMemoryCache.Clear();

            // Clear the static object that contains all auth rules (so that it will be refreshed)
            Rock.Security.Authorization.Flush();

            // Flush the static entity attributes cache
            Rock.Web.Cache.AttributeCache.FlushEntityAttributes();

            // Check for any unregistered entity types, field types, and block types
            string webAppPath = Server.MapPath("~");

            EntityTypeService.RegisterEntityTypes(webAppPath);
            FieldTypeService.RegisterFieldTypes(webAppPath);
            BlockTypeService.RegisterBlockTypes(webAppPath, Page, false);

            // Delete all cached files
            try
            {
                var dirInfo = new DirectoryInfo(Path.Combine(webAppPath, "App_Data/Cache"));
                foreach (var childDir in dirInfo.GetDirectories())
                {
                    childDir.Delete(true);
                }
                foreach (var file in dirInfo.GetFiles().Where(f => f.Name != ".gitignore"))
                {
                    file.Delete();
                }
            }
            catch (Exception ex)
            {
                nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                nbMessage.Visible             = true;
                nbMessage.Text = "Cache has been cleared, but following error occurred when attempting to delete cached files: " + ex.Message;
                return;
            }

            nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Success;
            nbMessage.Visible             = true;
            nbMessage.Text = "The cache has been cleared.";
        }
コード例 #14
0
ファイル: Reference.cs プロジェクト: waldo2590/Rock
        /// <summary>
        /// Restore this reference into the entity object.
        /// </summary>
        /// <param name="entity">The entity to restore the reference into.</param>
        /// <param name="helper">The helper that provides us data access.</param>
        public void Restore(IEntity entity, EntityDecoder helper)
        {
            PropertyInfo property    = entity.GetType().GetProperty(Property);
            object       otherEntity = null;

            if (property == null || Type == ReferenceType.Null)
            {
                return;
            }

            //
            // Find the referenced entity based on the reference type.
            //
            if (Type == ReferenceType.Guid)
            {
                otherEntity = helper.GetExistingEntity(EntityType, helper.FindMappedGuid(new Guid(( string )Data)));
            }
            else if (Type == ReferenceType.EntityType)
            {
                otherEntity = new EntityTypeService(helper.RockContext).Queryable().Where(e => e.Name == ( string )Data).FirstOrDefault();
            }
            else if (Type == ReferenceType.FieldType)
            {
                otherEntity = new FieldTypeService(helper.RockContext).Queryable().Where(f => f.Class == ( string )Data).FirstOrDefault();
            }
            else if (Type == ReferenceType.UserDefined)
            {
                otherEntity = helper.GetUserDefinedValue(( string )Data);
            }
            else
            {
                throw new Exception(string.Format("Don't know how to handle reference type {0}.", Type));
            }

            //
            // If we found an entity then get its Id number and store that.
            //
            if (otherEntity != null)
            {
                property.SetValue(entity, EntityCoder.ChangeType(property.PropertyType, otherEntity.GetPropertyValue("Id")));
            }
        }
コード例 #15
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string attributeKey = GetAttributeValue("RoomscannerConfigAttributeKey");
            Dictionary <string, string> settings = GlobalAttributesCache.Value(attributeKey).AsDictionary();

            settings["AllowedGroupId"]      = tbAllowedGroupId.Text;
            settings["SubroomLocationType"] = tbSubroomLocationTypeId.Text;

            RockContext      context          = new RockContext();
            AttributeService attributeService = new AttributeService(context);

            Rock.Model.Attribute attribute = attributeService.Queryable().Where(a => a.Key == attributeKey).FirstOrDefault();
            if (attribute == null)
            {
                attribute             = new Rock.Model.Attribute();
                attribute.Name        = "RoomScanner Settings";
                attribute.Description = "Settings for the OAuth server plugin.";
                attribute.Key         = "RoomScannerSettings";
                FieldTypeService fieldTypeService = new FieldTypeService(context);
                attribute.FieldType = fieldTypeService.Get(Rock.SystemGuid.FieldType.KEY_VALUE_LIST.AsGuid());
                context.SaveChanges();
            }
            // Update the actual attribute value.
            AttributeValueService attributeValueService = new AttributeValueService(context);
            AttributeValue        attributeValue        = attributeValueService.GetByAttributeIdAndEntityId(attribute.Id, null);

            if (attributeValue == null)
            {
                attributeValue             = new AttributeValue();
                attributeValue.AttributeId = attribute.Id;
                attributeValueService.Add(attributeValue);
            }
            attributeValue.Value = string.Join("|", settings.Select(a => a.Key + "^" + a.Value).ToList());
            context.SaveChanges();

            // Flush the cache(s)
            AttributeCache.Remove(attribute.Id);
            GlobalAttributesCache.Clear();
        }
コード例 #16
0
        public JsonResult CreateEntity(List <KeyValue> keyValues)
        {
            try
            {
                var id          = Guid.NewGuid();
                var name        = keyValues.FirstOrDefault(x => x.Key == "Name")?.Value;
                var displayName = keyValues.FirstOrDefault(x => x.Key == "DisplayName")?.Value;
                var pluralName  = keyValues.FirstOrDefault(x => x.Key == "PluralName")?.Value;

                var fieldTypes = FieldTypeService.QueryFieldTypes();

                #region Create entity record
                var returnValue = SharedService.ExecutePostSqlStoredProcedure("[eduq].[Entity_create]",
                                                                              new List <SqlParameter>
                {
                    new SqlParameter("@id", id),
                    new SqlParameter("@name", (name.ToLower())),
                    new SqlParameter("@displayName", displayName),
                    new SqlParameter("@pluralName", pluralName),
                    new SqlParameter("@stateId", 1)
                });

                if (returnValue != 1)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                var newlyCreatedEntity = EntityService.QueryEntityById(id);
                if (newlyCreatedEntity == null)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                #region Create sql table
                var returnValueCreateSqlTable = SqlService.CreateSqlTable(name);

                if (!returnValueCreateSqlTable)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                /*Create Fields*/
                #region Id Field
                /*Id*/
                var fieldId                  = Guid.NewGuid();
                var fieldName                = "Id";
                var fieldDisplayName         = "Id";
                var fieldDescription         = "";
                var fieldDefaultValue        = "";
                var fieldEntityId            = id;
                var GuidFieldType            = FieldTypeService.QueryFieldTypeByName("Guid");
                var GuidFieldTypeId          = (int)GuidFieldType.FirstOrDefault(x => x.Key == "Id").Value;
                var GuidFieldTypeSqlDataType = GuidFieldType.FirstOrDefault(x => x.Key == "SqlDataTypeName").Value.ToString();
                var fieldStateId             = 1;
                var returnValueCreateField   = FieldService.CreateField(fieldId, fieldName, fieldDisplayName, fieldDescription, fieldDefaultValue, fieldEntityId, GuidFieldTypeId, true, fieldStateId);
                if (returnValueCreateField == Guid.Empty)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                #region Name Field
                /*Name*/
                fieldId           = Guid.NewGuid();
                fieldName         = "Name";
                fieldDisplayName  = "Name";
                fieldDescription  = "";
                fieldDefaultValue = "";
                fieldEntityId     = id;
                var texteFieldType   = FieldTypeService.QueryFieldTypeByName("Texte");
                var texteFieldTypeId = (int)texteFieldType.FirstOrDefault(x => x.Key == "Id").Value;
                fieldStateId           = 1;
                returnValueCreateField = FieldService.CreateField(fieldId, fieldName, fieldDisplayName, fieldDescription, fieldDefaultValue, fieldEntityId, texteFieldTypeId, true, fieldStateId);
                if (returnValueCreateField == Guid.Empty)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                #region CreatedOn Field
                /*CreatedOn*/
                fieldId           = Guid.NewGuid();
                fieldName         = "CreatedOn";
                fieldDisplayName  = "Date de Création";
                fieldDescription  = "";
                fieldDefaultValue = "";
                fieldEntityId     = id;
                var dateTimeFieldType   = FieldTypeService.QueryFieldTypeByName("Date et Heure");
                var dateTimeFieldTypeId = (int)dateTimeFieldType.FirstOrDefault(x => x.Key == "Id").Value;
                fieldStateId           = 1;
                returnValueCreateField = FieldService.CreateField(fieldId, fieldName, fieldDisplayName, fieldDescription, fieldDefaultValue, fieldEntityId, dateTimeFieldTypeId, true, fieldStateId);
                if (returnValueCreateField == Guid.Empty)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                #region CreatedById Field
                /*CreatedId*/
                fieldId           = Guid.NewGuid();
                fieldName         = "CreatedById";
                fieldDisplayName  = "Créer par";
                fieldDescription  = "";
                fieldDefaultValue = "";
                fieldEntityId     = id;
                var lookupFieldType   = FieldTypeService.QueryFieldTypeByName("Recherche");
                var lookupFieldTypeId = (int)lookupFieldType.FirstOrDefault(x => x.Key == "Id").Value;
                fieldStateId           = 1;
                returnValueCreateField = FieldService.CreateField(fieldId, fieldName, fieldDisplayName, fieldDescription, fieldDefaultValue, fieldEntityId, lookupFieldTypeId, true, fieldStateId);
                if (returnValueCreateField == Guid.Empty)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                #region ModifiedOn
                /*ModifiedOn*/
                fieldId                = Guid.NewGuid();
                fieldName              = "ModifiedOn";
                fieldDisplayName       = "Date de modification";
                fieldDescription       = "";
                fieldDefaultValue      = "";
                fieldEntityId          = id;
                fieldStateId           = 1;
                returnValueCreateField = FieldService.CreateField(fieldId, fieldName, fieldDisplayName, fieldDescription, fieldDefaultValue, fieldEntityId, dateTimeFieldTypeId, true, fieldStateId);
                if (returnValueCreateField == Guid.Empty)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                #region ModifiedById Field
                /*ModifiedById*/
                fieldId                = Guid.NewGuid();
                fieldName              = "ModifiedById";
                fieldDisplayName       = "Modifié par";
                fieldDescription       = "";
                fieldDefaultValue      = "";
                fieldEntityId          = id;
                lookupFieldType        = FieldTypeService.QueryFieldTypeByName("Recherche");
                lookupFieldTypeId      = (int)lookupFieldType.FirstOrDefault(x => x.Key == "Id").Value;
                fieldStateId           = 1;
                returnValueCreateField = FieldService.CreateField(fieldId, fieldName, fieldDisplayName, fieldDescription, fieldDefaultValue, fieldEntityId, lookupFieldTypeId, true, fieldStateId);
                if (returnValueCreateField == Guid.Empty)
                {
                    return(Json(new { message = "Une erreur s'est produise pendant la creation de l'entité!", type = "error" }, JsonRequestBehavior.AllowGet));
                }
                #endregion

                return(Json(new { message = id, type = "success" }, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                return(Json(ex.Message, JsonRequestBehavior.AllowGet));
            }
        }
コード例 #17
0
        /// <summary>
        /// Handles the Start event of the Application 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 Application_Start(object sender, EventArgs e)
        {
            try
            {
                var stopwatch = System.Diagnostics.Stopwatch.StartNew();
                LogMessage(APP_LOG_FILENAME, "Application Starting...");

                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Application_Start: {0}", RockDateTime.Now.ToString("hh:mm:ss.FFF")));
                }

                // Clear all cache
                RockMemoryCache.Clear();

                // Get a db context
                using (var rockContext = new RockContext())
                {
                    if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                    {
                        try
                        {
                            // default Initializer is CreateDatabaseIfNotExists, so set it to NULL so that nothing happens if there isn't a database yet
                            Database.SetInitializer <Rock.Data.RockContext>(null);
                            new AttributeService(rockContext).Get(0);
                            System.Diagnostics.Debug.WriteLine(string.Format("ConnectToDatabase {2}/{1} - {0} ms", stopwatch.Elapsed.TotalMilliseconds, rockContext.Database.Connection.Database, rockContext.Database.Connection.DataSource));
                        }
                        catch
                        {
                            // Intentionally Blank
                        }
                    }

                    //// Run any needed Rock and/or plugin migrations
                    //// NOTE: MigrateDatabase must be the first thing that touches the database to help prevent EF from creating empty tables for a new database
                    MigrateDatabase(rockContext);

                    // Preload the commonly used objects
                    stopwatch.Restart();
                    LoadCacheObjects(rockContext);

                    if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("LoadCacheObjects - {0} ms", stopwatch.Elapsed.TotalMilliseconds));
                    }

                    // Run any plugin migrations
                    MigratePlugins(rockContext);

                    RegisterRoutes(rockContext, RouteTable.Routes);

                    // Configure Rock Rest API
                    stopwatch.Restart();
                    GlobalConfiguration.Configure(Rock.Rest.WebApiConfig.Register);
                    if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("Configure WebApiConfig - {0} ms", stopwatch.Elapsed.TotalMilliseconds));
                        stopwatch.Restart();
                    }

                    // setup and launch the jobs infrastructure if running under IIS
                    bool runJobsInContext = Convert.ToBoolean(ConfigurationManager.AppSettings["RunJobsInIISContext"]);
                    if (runJobsInContext)
                    {
                        ISchedulerFactory sf;

                        // create scheduler
                        sf    = new StdSchedulerFactory();
                        sched = sf.GetScheduler();

                        // get list of active jobs
                        ServiceJobService jobService = new ServiceJobService(rockContext);
                        foreach (ServiceJob job in jobService.GetActiveJobs().ToList())
                        {
                            const string errorLoadingStatus = "Error Loading Job";
                            try
                            {
                                IJobDetail jobDetail  = jobService.BuildQuartzJob(job);
                                ITrigger   jobTrigger = jobService.BuildQuartzTrigger(job);

                                sched.ScheduleJob(jobDetail, jobTrigger);

                                //// if the last status was an error, but we now loaded successful, clear the error
                                // also, if the last status was 'Running', clear that status because it would have stopped if the app restarted
                                if (job.LastStatus == errorLoadingStatus || job.LastStatus == "Running")
                                {
                                    job.LastStatusMessage = string.Empty;
                                    job.LastStatus        = string.Empty;
                                    rockContext.SaveChanges();
                                }
                            }
                            catch (Exception ex)
                            {
                                // log the error
                                LogError(ex, null);

                                // create a friendly error message
                                string message = string.Format("Error loading the job: {0}.\n\n{2}", job.Name, job.Assembly, ex.Message);
                                job.LastStatusMessage = message;
                                job.LastStatus        = errorLoadingStatus;
                                rockContext.SaveChanges();
                            }
                        }

                        // set up the listener to report back from jobs as they complete
                        sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs());

                        // start the scheduler
                        sched.Start();
                    }

                    // Force the static Liquid class to get instantiated so that the standard filters are loaded prior
                    // to the custom RockFilter.  This is to allow the custom 'Date' filter to replace the standard
                    // Date filter.
                    Liquid.UseRubyDateFormat = false;

                    //// NOTE: This means that template filters will also use CSharpNamingConvention
                    //// For example the dotliquid documentation says to do this for formatting dates:
                    //// {{ some_date_value | date:"MMM dd, yyyy" }}
                    //// However, if CSharpNamingConvention is enabled, it needs to be:
                    //// {{ some_date_value | Date:"MMM dd, yyyy" }}
                    Template.NamingConvention = new DotLiquid.NamingConventions.CSharpNamingConvention();
                    Template.FileSystem       = new RockWeb.LavaFileSystem();
                    Template.RegisterSafeType(typeof(Enum), o => o.ToString());
                    Template.RegisterFilter(typeof(Rock.Lava.RockFilters));

                    // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
                    AddCallBack();

                    Rock.Security.Authorization.Load();
                }

                EntityTypeService.RegisterEntityTypes(Server.MapPath("~"));
                FieldTypeService.RegisterFieldTypes(Server.MapPath("~"));

                BundleConfig.RegisterBundles(BundleTable.Bundles);

                // mark any user login stored as 'IsOnline' in the database as offline
                MarkOnlineUsersOffline();

                SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~"));

                LogMessage(APP_LOG_FILENAME, "Application Started Successfully");
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Application_Started_Successfully: {0}", RockDateTime.Now.ToString("hh:mm:ss.FFF")));
                }
            }
            catch (Exception ex)
            {
                SetError66();
                throw (new Exception("Error occurred during application startup", ex));
            }
        }
コード例 #18
0
        /// <summary>
        /// Handles the Start event of the Application 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 Application_Start(object sender, EventArgs e)
        {
            RockApplicationStartupHelper.ShowDebugTimingMessage("Application Start");

            Rock.Bus.RockMessageBus.IsRockStarted = false;
            QueueInUse = false;

            /* 2020-05-20 MDP
             * Prior to Application_Start, Rock.WebStartup has an AssemblyInitializer class that runs as a PreApplicationStartMethod.
             *
             * This will call RockApplicationStartupHelper which will take care of the following
             *   -- EF Migrations
             *   -- Rock Plugin Migrations (except for ones that are in App_Code)
             *   -- Sending Version update notifications to Spark
             *   -- Pre-loading EntityTypeCache, FieldTypeCache, and AttributeCache
             *   -- Loading any attributes defined in web.config
             *   -- Registering HttpModules
             *   -- Initializing Lava
             *   -- Starting the Job Scheduler (if configured to run)
             */

            /* 2020-05-20 MDP
             * The remaining items need to be run here in Application_Start since they depend on things that don't happen until now
             * like Routes, plugin stuff in App_Code
             */

            try
            {
                // AssemblyInitializer will catch any exception that it gets and sets AssemblyInitializerException.
                // Doing this lets us do any error handling (now that RockWeb has started)
                if (AssemblyInitializer.AssemblyInitializerException != null)
                {
                    throw AssemblyInitializer.AssemblyInitializerException;
                }

                // register the App_Code assembly in the Rock.Reflection helper so that Reflection methods can search for types in it
                var appCodeAssembly = typeof(Global).Assembly;
                Rock.Reflection.SetAppCodeAssembly(appCodeAssembly);

                // Probably won't be any, but run any migrations that might be in App_Code. (Any that are dll's get run in RockApplicationStartupHelper.RunApplicationStartup())
                RockApplicationStartupHelper.RunPluginMigrations(appCodeAssembly);

                // Register Routes
                RouteTable.Routes.Clear();
                Rock.Web.RockRouteHandler.RegisterRoutes();

                // Configure Rock Rest API
                GlobalConfiguration.Configure(Rock.Rest.WebApiConfig.Register);

                // set the encryption protocols that are permissible for external SSL connections
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12;

                RockApplicationStartupHelper.ShowDebugTimingMessage("Register Routes");

                // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
                AddCallBack();

                // register any EntityTypes or FieldTypes that are discovered in Rock or any plugins (including ones in ~/App_Code)
                EntityTypeService.RegisterEntityTypes();
                FieldTypeService.RegisterFieldTypes();

                BundleConfig.RegisterBundles(BundleTable.Bundles);

                // mark any user login stored as 'IsOnline' in the database as offline
                MarkOnlineUsersOffline();

                SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~"));

                RockApplicationStartupHelper.ShowDebugTimingMessage("Register Types");

                RockApplicationStartupHelper.LogStartupMessage("Application Started Successfully");
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("[{0,5:#} ms] Total Startup Time", (RockDateTime.Now - RockApplicationStartupHelper.StartDateTime).TotalMilliseconds));
                }

                ExceptionLogService.AlwaysLogToFile = false;

                // Perform any Rock startups
                RunStartups();
            }
            catch (Exception ex)
            {
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("##Startup Exception##: {0}\n{1}", ex.Message, ex.StackTrace));
                }

                SetError66();
                var startupException = new RockStartupException("Error occurred during application startup", ex);
                LogError(startupException, null);
                throw startupException;
            }

            StartBlockTypeCompilationThread();

            StartWorkflowActionUpdateAttributesThread();

            StartCompileThemesThread();

            Rock.Bus.RockMessageBus.IsRockStarted = true;
        }
コード例 #19
0
        /// <summary>
        /// Maps the Giftedness Program.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapGiftednessProgram(IQueryable <Row> tableData)
        {
            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying Giftedness Program import ({0:N0} found).", totalRows));

            foreach (var row in tableData)
            {
                var rockContext      = new RockContext();
                var categoryList     = new CategoryService(rockContext).Queryable().ToList();
                var attributeList    = new AttributeService(rockContext).Queryable().ToList();
                var definedTypeList  = new DefinedTypeService(rockContext).Queryable().ToList();
                var definedValueList = new DefinedValueService(rockContext).Queryable().ToList();

                //check if category exists
                string category = row["CategoryName"] as string;
                if (categoryList.Find(c => c.Name == category) == null)
                {
                    var entityType = new EntityTypeService(rockContext);
                    //creates if category doesn't exist
                    var newCategory = new Category();
                    newCategory.IsSystem     = false;
                    newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault();
                    newCategory.EntityTypeQualifierColumn = "EntityTypeId";
                    newCategory.EntityTypeQualifierValue  = Convert.ToString(PersonEntityTypeId);   //Convert.ToString(entityType.Queryable().Where( e => e.Name == "Rock.Model.Person" ).Select( e => e.Id ).FirstOrDefault());
                    newCategory.Name        = category;
                    newCategory.Description = "Contains the spiritual gifts attributes";

                    //var newCategoryContext = new RockContext();
                    //newCategoryContext.WrapTransaction( () =>
                    //{
                    //    newCategoryContext.Configuration.AutoDetectChangesEnabled = false;
                    //    newCategoryContext.Categories.Add( newCategory );
                    //    newCategoryContext.SaveChanges( DisableAudit );
                    //} );
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.Categories.Add(newCategory);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //Check if Attribute exists
                if (attributeList.Find(a => a.Key == "Rank1") == null || attributeList.Find(a => a.Key == "Rank2") == null || attributeList.Find(a => a.Key == "Rank3") == null || attributeList.Find(a => a.Key == "Rank4") == null)
                {
                    var fieldType        = new FieldTypeService(rockContext);
                    var newAttributeList = new List <Rock.Model.Attribute>();
                    var fieldTypeId      = fieldType.Queryable().Where(e => e.Name == "Defined Value").FirstOrDefault().Id;
                    var category2        = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Spiritual Gifts").FirstOrDefault();


                    if (attributeList.Find(a => a.Key == "Rank1") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank1";
                        newAttribute.Name                      = "Rank 1";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 1";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank2") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank2";
                        newAttribute.Name                      = "Rank 2";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 2";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank3") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank3";
                        newAttribute.Name                      = "Rank 3";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 3";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);

                        newAttributeList.Add(newAttribute);
                    }
                    if (attributeList.Find(a => a.Key == "Rank4") == null)
                    {
                        //Creates if attribute doesn't exist
                        var newAttribute = new Rock.Model.Attribute();
                        newAttribute.Key                       = "Rank4";
                        newAttribute.Name                      = "Rank 4";
                        newAttribute.FieldTypeId               = fieldTypeId;
                        newAttribute.EntityTypeId              = PersonEntityTypeId;
                        newAttribute.EntityTypeQualifierValue  = string.Empty;
                        newAttribute.EntityTypeQualifierColumn = string.Empty;
                        newAttribute.Description               = "Rank 4";
                        newAttribute.DefaultValue              = string.Empty;
                        newAttribute.IsMultiValue              = false;
                        newAttribute.IsRequired                = false;
                        newAttribute.Categories                = new List <Category>();
                        newAttribute.Categories.Add(category2);


                        newAttributeList.Add(newAttribute);
                    }

                    if (newAttributeList.Any())
                    {
                        //var newAttributeContext = new RockContext();
                        rockContext.WrapTransaction(() =>
                        {
                            rockContext.Configuration.AutoDetectChangesEnabled = false;
                            rockContext.Attributes.AddRange(newAttributeList);
                            rockContext.SaveChanges(DisableAudit);
                            newAttributeList.Clear();
                        });
                    }
                }
                //checks if Defined Type exists
                if (definedTypeList.Find(d => d.Name == "Spiritual Gifts") == null)
                {
                    var fieldTypeService = new FieldTypeService(rockContext);

                    //creates Defined Type
                    var newDefinedType = new DefinedType();
                    newDefinedType.IsSystem    = false;
                    newDefinedType.FieldTypeId = fieldTypeService.Queryable().Where(f => f.Name == "Text").Select(f => f.Id).FirstOrDefault();
                    newDefinedType.Name        = "Spiritual Gifts";
                    newDefinedType.Description = "Defined Type for Spiritual Gifts values";
                    newDefinedType.CategoryId  = categoryList.Find(c => c.Name == "Person").Id;

                    //var newDTContext = new RockContext();
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.DefinedTypes.Add(newDefinedType);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //checks if Defined Value exists
                var    spiritualGiftsDefineType = new DefinedTypeService(rockContext).Queryable().Where(d => d.Name == "Spiritual Gifts").FirstOrDefault();
                string attributeName            = row["AttributeName"] as string;
                int?   giftAttributeId          = row["GiftAttributeID"] as int?;
                if (definedValueList.Find(d => d.DefinedTypeId == spiritualGiftsDefineType.Id && d.Value == attributeName) == null)
                {
                    var definedTypeService = new DefinedTypeService(rockContext);
                    //creates Defined Value
                    var newDefinedValue = new DefinedValue();
                    newDefinedValue.IsSystem      = false;
                    newDefinedValue.DefinedTypeId = definedTypeService.Queryable().Where(d => d.Name == "Spiritual Gifts").Select(d => d.Id).FirstOrDefault();
                    newDefinedValue.Value         = attributeName;
                    newDefinedValue.Description   = "Spiritual Gift attribute value: " + attributeName;
                    newDefinedValue.ForeignId     = Convert.ToString(giftAttributeId);

                    //var newDVContext = new RockContext();
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.DefinedValues.Add(newDefinedValue);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }

                completed++;

                if (completed % percentage < 1)
                {
                    int percentComplete = completed / percentage;
                    ReportProgress(percentComplete, string.Format("{0:N0} spiritual gifts attributes imported ({1}% complete).", completed, percentComplete));
                }
                else if (completed % ReportingNumber < 1)
                {
                    ReportPartialProgress();
                }
            }

            ReportProgress(100, string.Format("Finished spiritual gifts import: {0:N0} spiritual gifts attributes imported.", completed));
        }
コード例 #20
0
ファイル: Global.asax.cs プロジェクト: klee66/Rock-CentralAZ
        /// <summary>
        /// Handles the Start event of the Application 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 Application_Start(object sender, EventArgs e)
        {
            try
            {
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Application_Start: {0}", RockDateTime.Now.ToString("hh:mm:ss.FFF")));
                }

                // Run any needed Rock and/or plugin migrations
                MigrateDatabase();

                // Get a db context
                var rockContext = new RockContext();

                RegisterRoutes(rockContext, RouteTable.Routes);

                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    new AttributeService(rockContext).Get(0);
                    System.Diagnostics.Debug.WriteLine(string.Format("ConnectToDatabase - Connected: {0}", RockDateTime.Now.ToString("hh:mm:ss.FFF")));
                }

                // Preload the commonly used objects
                LoadCacheObjects(rockContext);
                if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("LoadCacheObjects - Done: {0}", RockDateTime.Now.ToString("hh:mm:ss.FFF")));
                }

                // setup and launch the jobs infrastructure if running under IIS
                bool runJobsInContext = Convert.ToBoolean(ConfigurationManager.AppSettings["RunJobsInIISContext"]);
                if (runJobsInContext)
                {
                    ISchedulerFactory sf;

                    // create scheduler
                    sf    = new StdSchedulerFactory();
                    sched = sf.GetScheduler();

                    // get list of active jobs
                    ServiceJobService jobService = new ServiceJobService(rockContext);
                    foreach (ServiceJob job in jobService.GetActiveJobs().ToList())
                    {
                        try
                        {
                            IJobDetail jobDetail  = jobService.BuildQuartzJob(job);
                            ITrigger   jobTrigger = jobService.BuildQuartzTrigger(job);

                            sched.ScheduleJob(jobDetail, jobTrigger);
                        }
                        catch (Exception ex)
                        {
                            // create a friendly error message
                            string message = string.Format("Error loading the job: {0}.  Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message);
                            job.LastStatusMessage = message;
                            job.LastStatus        = "Error Loading Job";
                            rockContext.SaveChanges();
                        }
                    }

                    // set up the listener to report back from jobs as they complete
                    sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs());

                    // start the scheduler
                    sched.Start();
                }

                // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
                AddCallBack();

                RegisterFilters(GlobalConfiguration.Configuration.Filters);

                Rock.Security.Authorization.Load(rockContext);

                EntityTypeService.RegisterEntityTypes(Server.MapPath("~"));
                FieldTypeService.RegisterFieldTypes(Server.MapPath("~"));

                BundleConfig.RegisterBundles(BundleTable.Bundles);

                // mark any user login stored as 'IsOnline' in the database as offline
                MarkOnlineUsersOffline();

                SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~"));
            }
            catch (Exception ex)
            {
                Error66(ex);
            }
        }
コード例 #21
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool hasValidationErrors = false;

            using (new UnitOfWorkScope())
            {
                GroupTypeService groupTypeService = new GroupTypeService();
                GroupService     groupService     = new GroupService();
                AttributeService attributeService = new AttributeService();

                int parentGroupTypeId = hfParentGroupTypeId.ValueAsInt();

                var groupTypeUIList = new List <GroupType>();

                foreach (var checkinGroupTypeEditor in phCheckinGroupTypes.Controls.OfType <CheckinGroupTypeEditor>().ToList())
                {
                    var groupType = checkinGroupTypeEditor.GetCheckinGroupType();
                    groupTypeUIList.Add(groupType);
                }

                var groupTypeDBList = new List <GroupType>();

                var groupTypesToDelete = new List <GroupType>();
                var groupsToDelete     = new List <Group>();

                var groupTypesToAddUpdate = new List <GroupType>();
                var groupsToAddUpdate     = new List <Group>();

                GroupType parentGroupTypeDB = groupTypeService.Get(parentGroupTypeId);
                GroupType parentGroupTypeUI = parentGroupTypeDB.Clone(false);
                parentGroupTypeUI.ChildGroupTypes = groupTypeUIList;

                PopulateDeleteLists(groupTypesToDelete, groupsToDelete, parentGroupTypeDB, parentGroupTypeUI);
                PopulateAddUpdateLists(groupTypesToAddUpdate, groupsToAddUpdate, parentGroupTypeUI);

                int binaryFileFieldTypeID = new FieldTypeService().Get(new Guid(Rock.SystemGuid.FieldType.BINARY_FILE)).Id;
                int binaryFileTypeId      = new BinaryFileTypeService().Get(new Guid(Rock.SystemGuid.BinaryFiletype.CHECKIN_LABEL)).Id;

                RockTransactionScope.WrapTransaction(() =>
                {
                    // delete in reverse order to get deepest child items first
                    groupsToDelete.Reverse();
                    foreach (var groupToDelete in groupsToDelete)
                    {
                        groupService.Delete(groupToDelete, this.CurrentPersonId);
                        groupService.Save(groupToDelete, this.CurrentPersonId);
                    }

                    // delete in reverse order to get deepest child items first
                    groupTypesToDelete.Reverse();
                    foreach (var groupTypeToDelete in groupTypesToDelete)
                    {
                        groupTypeService.Delete(groupTypeToDelete, this.CurrentPersonId);
                        groupTypeService.Save(groupTypeToDelete, this.CurrentPersonId);
                    }

                    // Add/Update grouptypes and groups that are in the UI
                    // Note:  We'll have to save all the groupTypes without changing the DB value of ChildGroupTypes, then come around again and save the ChildGroupTypes
                    // since the ChildGroupTypes may not exist in the database yet
                    foreach (GroupType groupTypeUI in groupTypesToAddUpdate)
                    {
                        GroupType groupTypeDB = groupTypeService.Get(groupTypeUI.Guid);
                        if (groupTypeDB == null)
                        {
                            groupTypeDB      = new GroupType();
                            groupTypeDB.Id   = 0;
                            groupTypeDB.Guid = groupTypeUI.Guid;
                        }

                        groupTypeDB.Name  = groupTypeUI.Name;
                        groupTypeDB.Order = groupTypeUI.Order;
                        groupTypeDB.InheritedGroupTypeId = groupTypeUI.InheritedGroupTypeId;

                        groupTypeDB.Attributes      = groupTypeUI.Attributes;
                        groupTypeDB.AttributeValues = groupTypeUI.AttributeValues;

                        if (groupTypeDB.Id == 0)
                        {
                            groupTypeService.Add(groupTypeDB, this.CurrentPersonId);
                        }

                        if (!groupTypeDB.IsValid)
                        {
                            hasValidationErrors = true;
                            CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                            groupTypeEditor.ForceContentVisible    = true;

                            return;
                        }

                        groupTypeService.Save(groupTypeDB, this.CurrentPersonId);

                        Rock.Attribute.Helper.SaveAttributeValues(groupTypeDB, this.CurrentPersonId);

                        // get fresh from database to make sure we have Id so we can update the CheckinLabel Attributes
                        groupTypeDB = groupTypeService.Get(groupTypeDB.Guid);

                        // rebuild the CheckinLabel attributes from the UI (brute-force)
                        foreach (var labelAttributeDB in CheckinGroupTypeEditor.GetCheckinLabelAttributes(groupTypeDB))
                        {
                            var attribute = attributeService.Get(labelAttributeDB.Value.Guid);
                            Rock.Web.Cache.AttributeCache.Flush(attribute.Id);
                            attributeService.Delete(attribute, this.CurrentPersonId);
                        }

                        foreach (var checkinLabelAttributeInfo in GroupTypeCheckinLabelAttributesState[groupTypeUI.Guid])
                        {
                            var attribute = new Rock.Model.Attribute();
                            attribute.AttributeQualifiers.Add(new AttributeQualifier {
                                Key = "binaryFileType", Value = binaryFileTypeId.ToString()
                            });
                            attribute.Guid         = Guid.NewGuid();
                            attribute.FieldTypeId  = binaryFileFieldTypeID;
                            attribute.EntityTypeId = EntityTypeCache.GetId(typeof(GroupType));
                            attribute.EntityTypeQualifierColumn = "Id";
                            attribute.EntityTypeQualifierValue  = groupTypeDB.Id.ToString();
                            attribute.DefaultValue = checkinLabelAttributeInfo.BinaryFileId.ToString();
                            attribute.Key          = checkinLabelAttributeInfo.AttributeKey;
                            attribute.Name         = checkinLabelAttributeInfo.FileName;

                            if (!attribute.IsValid)
                            {
                                hasValidationErrors = true;
                                CheckinGroupTypeEditor groupTypeEditor = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupTypeEditor>().First(a => a.GroupTypeGuid == groupTypeDB.Guid);
                                groupTypeEditor.ForceContentVisible    = true;

                                return;
                            }

                            attributeService.Add(attribute, this.CurrentPersonId);
                            attributeService.Save(attribute, this.CurrentPersonId);
                        }
                    }

                    // Add/Update Groups
                    foreach (var groupUI in groupsToAddUpdate)
                    {
                        Group groupDB = groupService.Get(groupUI.Guid);
                        if (groupDB == null)
                        {
                            groupDB      = new Group();
                            groupDB.Guid = groupUI.Guid;
                        }

                        groupDB.Name = groupUI.Name;

                        // delete any GroupLocations that were removed in the UI
                        foreach (var groupLocationDB in groupDB.GroupLocations.ToList())
                        {
                            if (!groupUI.GroupLocations.Select(a => a.LocationId).Contains(groupLocationDB.LocationId))
                            {
                                groupDB.GroupLocations.Remove(groupLocationDB);
                            }
                        }

                        // add any GroupLocations that were added in the UI
                        foreach (var groupLocationUI in groupUI.GroupLocations)
                        {
                            if (!groupDB.GroupLocations.Select(a => a.LocationId).Contains(groupLocationUI.LocationId))
                            {
                                GroupLocation groupLocationDB = new GroupLocation {
                                    LocationId = groupLocationUI.LocationId
                                };
                                groupDB.GroupLocations.Add(groupLocationDB);
                            }
                        }

                        groupDB.Order = groupUI.Order;

                        // get GroupTypeId from database in case the groupType is new
                        groupDB.GroupTypeId     = groupTypeService.Get(groupUI.GroupType.Guid).Id;
                        groupDB.Attributes      = groupUI.Attributes;
                        groupDB.AttributeValues = groupUI.AttributeValues;

                        if (groupDB.Id == 0)
                        {
                            groupService.Add(groupDB, this.CurrentPersonId);
                        }

                        if (!groupDB.IsValid)
                        {
                            hasValidationErrors             = true;
                            hasValidationErrors             = true;
                            CheckinGroupEditor groupEditor  = phCheckinGroupTypes.ControlsOfTypeRecursive <CheckinGroupEditor>().First(a => a.GroupGuid == groupDB.Guid);
                            groupEditor.ForceContentVisible = true;

                            return;
                        }

                        groupService.Save(groupDB, this.CurrentPersonId);

                        Rock.Attribute.Helper.SaveAttributeValues(groupDB, this.CurrentPersonId);
                    }

                    /* now that we have all the grouptypes saved, now lets go back and save them again with the current UI ChildGroupTypes */

                    // save main parentGroupType with current UI ChildGroupTypes
                    parentGroupTypeDB.ChildGroupTypes = new List <GroupType>();
                    parentGroupTypeDB.ChildGroupTypes.Clear();
                    foreach (var childGroupTypeUI in parentGroupTypeUI.ChildGroupTypes)
                    {
                        var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid);
                        parentGroupTypeDB.ChildGroupTypes.Add(childGroupTypeDB);
                    }

                    groupTypeService.Save(parentGroupTypeDB, this.CurrentPersonId);

                    // loop thru all the other GroupTypes in the UI and save their childgrouptypes
                    foreach (var groupTypeUI in groupTypesToAddUpdate)
                    {
                        var groupTypeDB             = groupTypeService.Get(groupTypeUI.Guid);
                        groupTypeDB.ChildGroupTypes = new List <GroupType>();
                        groupTypeDB.ChildGroupTypes.Clear();
                        foreach (var childGroupTypeUI in groupTypeUI.ChildGroupTypes)
                        {
                            var childGroupTypeDB = groupTypeService.Get(childGroupTypeUI.Guid);
                            groupTypeDB.ChildGroupTypes.Add(childGroupTypeDB);
                        }

                        groupTypeService.Save(groupTypeDB, this.CurrentPersonId);
                    }
                });
            }

            if (!hasValidationErrors)
            {
                NavigateToParentPage();
            }
        }
コード例 #22
0
ファイル: Attributes.ascx.cs プロジェクト: jh2mhs8/Rock-ChMS
        /// <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 entityTypeName = AttributeValue("Entity");

            if (string.IsNullOrWhiteSpace(entityTypeName))
            {
                entityTypeName = PageParameter("Entity");
            }
            _entityTypeId = Rock.Web.Cache.EntityTypeCache.GetId(entityTypeName);

            _entityQualifierColumn = AttributeValue("EntityQualifierColumn");
            if (string.IsNullOrWhiteSpace(_entityQualifierColumn))
            {
                _entityQualifierColumn = PageParameter("EntityQualifierColumn");
            }

            _entityQualifierValue = AttributeValue("EntityQualifierValue");
            if (string.IsNullOrWhiteSpace(_entityQualifierValue))
            {
                _entityQualifierValue = PageParameter("EntityQualifierValue");
            }

            _displayValueEdit = Convert.ToBoolean(AttributeValue("SetValues"));

            string entityIdString = AttributeValue("EntityId");

            if (string.IsNullOrWhiteSpace(entityIdString))
            {
                entityIdString = PageParameter("EntityId");
            }

            if (!string.IsNullOrWhiteSpace(entityIdString))
            {
                int entityIdint = 0;
                if (int.TryParse(entityIdString, out entityIdint))
                {
                    _entityId = entityIdint;
                }
            }

            _canConfigure = CurrentPage.IsAuthorized("Administrate", CurrentPerson);

            BindFilter();
            rFilter.ApplyFilterClick += rFilter_ApplyFilterClick;

            if (_canConfigure)
            {
                rGrid.DataKeyNames         = new string[] { "id" };
                rGrid.Actions.IsAddEnabled = true;

                rGrid.Actions.AddClick += rGrid_Add;
                rGrid.GridRebind       += rGrid_GridRebind;
                rGrid.RowDataBound     += rGrid_RowDataBound;

                rGrid.Columns[7].Visible = !_displayValueEdit;
                rGrid.Columns[8].Visible = _displayValueEdit;
                rGrid.Columns[9].Visible = _displayValueEdit;

                modalDetails.SaveClick     += modalDetails_SaveClick;
                modalDetails.OnCancelScript = string.Format("$('#{0}').val('');", hfIdValues.ClientID);

                // Create the dropdown list for listing the available field types
                var fieldTypeService = new FieldTypeService();
                var items            = fieldTypeService.
                                       Queryable().
                                       Select(f => new { f.Id, f.Name }).
                                       OrderBy(f => f.Name);

                ddlFieldType.AutoPostBack          = true;
                ddlFieldType.SelectedIndexChanged += new EventHandler(ddlFieldType_SelectedIndexChanged);
                ddlFieldType.Items.Clear();
                foreach (var item in items)
                {
                    ddlFieldType.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                }

                string editAttributeId = Request.Form[hfIdValues.UniqueID];
                if (Page.IsPostBack && editAttributeId != null && editAttributeId.Trim() != string.Empty)
                {
                    ShowEditValue(int.Parse(editAttributeId), false);
                }
            }
            else
            {
                nbMessage.Text    = "You are not authorized to configure this page";
                nbMessage.Visible = true;
            }
        }
コード例 #23
0
ファイル: Helper.cs プロジェクト: scotthenry76/Rock-CentralAZ
        /// <summary>
        /// Adds or Updates a <see cref="Rock.Model.Attribute" /> item for the attribute.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <param name="entityTypeId">The entity type id.</param>
        /// <param name="entityQualifierColumn">The entity qualifier column.</param>
        /// <param name="entityQualifierValue">The entity qualifier value.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        /// <remarks>
        /// If a rockContext value is included, this method will save any previous changes made to the context
        /// </remarks>
        private static bool UpdateAttribute(FieldAttribute property, int?entityTypeId, string entityQualifierColumn, string entityQualifierValue, RockContext rockContext = null)
        {
            bool updated = false;

            rockContext = rockContext ?? new RockContext();

            var attributeService          = new AttributeService(rockContext);
            var attributeQualifierService = new AttributeQualifierService(rockContext);
            var fieldTypeService          = new FieldTypeService(rockContext);
            var categoryService           = new CategoryService(rockContext);

            var propertyCategories = property.Category.SplitDelimitedValues(false).ToList();

            // Look for an existing attribute record based on the entity, entityQualifierColumn and entityQualifierValue
            Model.Attribute attribute = attributeService.Get(entityTypeId, entityQualifierColumn, entityQualifierValue, property.Key);
            if (attribute == null)
            {
                // If an existing attribute record doesn't exist, create a new one
                updated = true;

                attribute = new Model.Attribute();
                attribute.EntityTypeId = entityTypeId;
                attribute.EntityTypeQualifierColumn = entityQualifierColumn;
                attribute.EntityTypeQualifierValue  = entityQualifierValue;
                attribute.Key          = property.Key;
                attribute.IconCssClass = string.Empty;
                attribute.IsGridColumn = false;
            }
            else
            {
                // Check to see if the existing attribute record needs to be updated
                if (attribute.Name != property.Name ||
                    attribute.DefaultValue != property.DefaultValue ||
                    attribute.Description != property.Description ||
                    attribute.Order != property.Order ||
                    attribute.FieldType.Assembly != property.FieldTypeAssembly ||
                    attribute.FieldType.Class != property.FieldTypeClass ||
                    attribute.IsRequired != property.IsRequired)
                {
                    updated = true;
                }

                // Check category
                else if (attribute.Categories.Select(c => c.Name).Except(propertyCategories).Any() ||
                         propertyCategories.Except(attribute.Categories.Select(c => c.Name)).Any())
                {
                    updated = true;
                }

                // Check the qualifier values
                else if (attribute.AttributeQualifiers.Select(q => q.Key).Except(property.FieldConfigurationValues.Select(c => c.Key)).Any() ||
                         property.FieldConfigurationValues.Select(c => c.Key).Except(attribute.AttributeQualifiers.Select(q => q.Key)).Any())
                {
                    updated = true;
                }
                else
                {
                    foreach (var attributeQualifier in attribute.AttributeQualifiers)
                    {
                        if (!property.FieldConfigurationValues.ContainsKey(attributeQualifier.Key) ||
                            property.FieldConfigurationValues[attributeQualifier.Key].Value != attributeQualifier.Value)
                        {
                            updated = true;
                            break;
                        }
                    }
                }
            }

            if (updated)
            {
                // Update the attribute
                attribute.Name         = property.Name;
                attribute.Description  = property.Description;
                attribute.DefaultValue = property.DefaultValue;
                attribute.Order        = property.Order;
                attribute.IsRequired   = property.IsRequired;

                attribute.Categories.Clear();
                if (propertyCategories.Any())
                {
                    foreach (string propertyCategory in propertyCategories)
                    {
                        int attributeEntityTypeId = EntityTypeCache.Read(typeof(Rock.Model.Attribute)).Id;
                        var category = categoryService.Get(propertyCategory, attributeEntityTypeId, "EntityTypeId", entityTypeId.ToString()).FirstOrDefault();
                        if (category == null)
                        {
                            category              = new Category();
                            category.Name         = propertyCategory;
                            category.EntityTypeId = attributeEntityTypeId;
                            category.EntityTypeQualifierColumn = "EntityTypeId";
                            category.EntityTypeQualifierValue  = entityTypeId.ToString();
                            category.Order = 0;
                        }
                        attribute.Categories.Add(category);
                    }
                }

                foreach (var qualifier in attribute.AttributeQualifiers.ToList())
                {
                    attributeQualifierService.Delete(qualifier);
                }
                attribute.AttributeQualifiers.Clear();

                foreach (var configValue in property.FieldConfigurationValues)
                {
                    var qualifier = new Model.AttributeQualifier();
                    qualifier.Key   = configValue.Key;
                    qualifier.Value = configValue.Value.Value;
                    attribute.AttributeQualifiers.Add(qualifier);
                }

                // Try to set the field type by searching for an existing field type with the same assembly and class name
                if (attribute.FieldType == null || attribute.FieldType.Assembly != property.FieldTypeAssembly ||
                    attribute.FieldType.Class != property.FieldTypeClass)
                {
                    attribute.FieldType = fieldTypeService.Queryable().FirstOrDefault(f =>
                                                                                      f.Assembly == property.FieldTypeAssembly &&
                                                                                      f.Class == property.FieldTypeClass);
                }

                // If this is a new attribute, add it, otherwise remove the exiting one from the cache
                if (attribute.Id == 0)
                {
                    attributeService.Add(attribute);
                }
                else
                {
                    AttributeCache.Flush(attribute.Id);
                }

                rockContext.SaveChanges();

                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #24
0
        /// <summary>
        /// Maps the authorizations to an attribute.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        private void MapAuthorizations(IQueryable <Row> tableData)
        {
            var lookupContext   = new RockContext();
            var rockContext     = new RockContext();
            var categoryService = new CategoryService(lookupContext);
            var personService   = new PersonService(lookupContext);

            var noteList = new List <Note>();


            int completed  = 0;
            int totalRows  = tableData.Count();
            int percentage = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying Authorization import ({0:N0} found).", totalRows));

            var attributeList            = new AttributeService(lookupContext).Queryable().ToList();
            int authorizationAttributeId = 0;

            if (attributeList.Find(a => a.Key == "PickupAuthorization") != null)
            {
                authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id;
            }

            var authorizationAttributeValueList = new List <AttributeValue>();

            authorizationAttributeValueList = new AttributeValueService(rockContext).Queryable().Where(av => av.AttributeId == authorizationAttributeId).ToList();

            int f1HouseholdIdAttributeId = attributeList.Find(a => a.Key == "F1HouseholdId").Id;

            //places all household attributes in a dictionary where the key is the personId and the houshold is the value.
            var householdDictionary = new AttributeValueService(lookupContext).Queryable()
                                      .Where(av => av.AttributeId == f1HouseholdIdAttributeId)
                                      .Select(av => new { PersonId = av.EntityId, HouseholdId = av.Value })
                                      .ToDictionary(t => t.PersonId, t => t.HouseholdId);


            foreach (var row in tableData)
            {
                //var rockContext = new RockContext();
                var categoryList = new CategoryService(rockContext).Queryable().ToList();


                //check if category exists
                //If it doesn't (though it should), it will create a new category called Authorization
                if (categoryList.Find(c => c.Name == "Childhood Information") == null)
                {
                    var entityType = new EntityTypeService(rockContext);
                    //creates if category doesn't exist
                    var newCategory = new Category();
                    newCategory.IsSystem     = false;
                    newCategory.EntityTypeId = entityType.Queryable().Where(e => e.Name == "Rock.Model.Attribute").Select(e => e.Id).FirstOrDefault();
                    newCategory.EntityTypeQualifierColumn = "EntityTypeId";
                    newCategory.EntityTypeQualifierValue  = Convert.ToString(PersonEntityTypeId);
                    newCategory.Name        = "Authorization";
                    newCategory.Description = "Contains the pickup authorization";

                    //var newCategoryContext = new RockContext();
                    //newCategoryContext.WrapTransaction( () =>
                    //{
                    //    newCategoryContext.Configuration.AutoDetectChangesEnabled = false;
                    //    newCategoryContext.Categories.Add( newCategory );
                    //    newCategoryContext.SaveChanges( DisableAudit );
                    //} );
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.Categories.Add(newCategory);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                attributeList = new AttributeService(lookupContext).Queryable().ToList();

                //Check if Attribute exists
                //If it doesn't it creates the attribute
                if (attributeList.Find(a => a.Key == "PickupAuthorization") == null)
                {
                    var fieldType = new FieldTypeService(rockContext);
                    //var newAttributeList = new List<Rock.Model.Attribute>();
                    var fieldTypeId = fieldType.Queryable().Where(e => e.Name == "Memo").FirstOrDefault().Id;
                    var category2   = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Childhood Information").FirstOrDefault();
                    var category3   = new CategoryService(rockContext).Queryable().Where(gt => gt.Name == "Authorization").FirstOrDefault();

                    //Creates if attribute doesn't exist
                    //The attribute is a memo attribute
                    var newAttribute = new Rock.Model.Attribute();
                    newAttribute.Key                       = "PickupAuthorization";
                    newAttribute.Name                      = "Pickup Authorization";
                    newAttribute.FieldTypeId               = fieldTypeId;
                    newAttribute.EntityTypeId              = PersonEntityTypeId;
                    newAttribute.EntityTypeQualifierValue  = string.Empty;
                    newAttribute.EntityTypeQualifierColumn = string.Empty;
                    newAttribute.Description               = "Lists who is authorized to pickup this child along with their current phone number.";
                    newAttribute.DefaultValue              = string.Empty;
                    newAttribute.IsMultiValue              = false;
                    newAttribute.IsRequired                = false;

                    if (categoryList.Find(c => c.Name == "Childhood Information") != null)
                    {
                        newAttribute.Categories = new List <Category>();
                        newAttribute.Categories.Add(category2);
                    }
                    //If authorization category was create, this is where the attribute is set to that category.
                    else
                    {
                        newAttribute.Categories = new List <Category>();
                        newAttribute.Categories.Add(category3);    //Sets to Authorization Attribute Category.
                    }

                    //saves the attribute
                    rockContext.WrapTransaction(() =>
                    {
                        rockContext.Configuration.AutoDetectChangesEnabled = false;
                        rockContext.Attributes.Add(newAttribute);
                        rockContext.SaveChanges(DisableAudit);
                    });
                }
                //Adding to the person's attributes
                int?     householdId       = row["HouseholdID"] as int?;
                string   personName        = row["PersonName"] as string;
                DateTime?authorizationDate = row["AuthorizationDate"] as DateTime?;

                attributeList = new AttributeService(rockContext).Queryable().ToList();

                //Gets the Attribute Id for Pickup Authorization.
                authorizationAttributeId = attributeList.Find(a => a.Key == "PickupAuthorization").Id;


                //since F1 authorization applies to the household id and not individual I have to apply it to all members in that household.
                //Value in F1 is a text entry and not a person select. Discuss with staff that we need to break away from this and start using known relationships for authorization
                foreach (var household in householdDictionary.Where(h => h.Value == Convert.ToString(householdId)))
                {
                    //checks if a record already exists in the list

                    if (authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key) == null)
                    {
                        var person = new PersonService(rockContext).Queryable().Where(p => p.Id == household.Key).FirstOrDefault();

                        //trying to keep from adding this attribute to adult records
                        if (person != null && (person.Age <= 18 || person.Age == null))
                        {
                            //creates new attribute record if it does not exist.
                            var newAuthorizationAttribute = new AttributeValue();
                            newAuthorizationAttribute.IsSystem        = false;
                            newAuthorizationAttribute.AttributeId     = authorizationAttributeId;
                            newAuthorizationAttribute.EntityId        = household.Key;     //the key is the person ID
                            newAuthorizationAttribute.Value           = personName + ", "; //text field
                            newAuthorizationAttribute.CreatedDateTime = authorizationDate;

                            //adds the new record to the list
                            authorizationAttributeValueList.Add(newAuthorizationAttribute);
                        }
                    }
                    //if a record already exists
                    else
                    {
                        //adds to the current value.
                        authorizationAttributeValueList.Find(a => a.AttributeId == authorizationAttributeId && a.EntityId == household.Key).Value = personName + ", ";
                    }
                }
                completed++;
                if (completed % percentage < 1)
                {
                    int percentComplete = completed / percentage;
                    ReportProgress(percentComplete, string.Format("{0:N0} authorizations imported ({1}% complete).", completed, percentComplete));
                }
                else if (completed % ReportingNumber < 1)
                {
                    //rockContext.WrapTransaction( () =>
                    // {
                    //     rockContext.Configuration.AutoDetectChangesEnabled = false;
                    //     rockContext.AttributeValues.AddRange( authorizationAttributeValueList );
                    //     rockContext.SaveChanges( DisableAudit );  //I get can't insert duplicate entry error
                    // } );

                    ReportPartialProgress();
                }
            }

            if (authorizationAttributeValueList.Any())
            {
                //var rockContext = new RockContext();
                rockContext.WrapTransaction(() =>
                {
                    rockContext.Configuration.AutoDetectChangesEnabled = false;
                    rockContext.AttributeValues.AddRange(authorizationAttributeValueList);
                    rockContext.SaveChanges(DisableAudit);
                });
            }

            ReportProgress(100, string.Format("Finished authorization import: {0:N0} notes imported.", completed));
        }