Esempio n. 1
0
        /// <summary>
        /// Inserts travel time from an origin to a set of destination objects.
        /// </summary>
        /// <param name="origin">The origin address</param>
        /// <param name="destinations">List of destination objects</param>
        public void LoadDurations(string origin, List <Destination> destinations)
        {
            foreach (var destination in destinations)
            {
                var destinationCache = RockCache.Get(origin + destination.Address, "org.secc.Mapping.LocationDistance") as Destination;
                if (destinationCache != null)
                {
                    destination.TravelDistance = destinationCache.TravelDistance;
                    destination.TravelDuration = destinationCache.TravelDuration;
                    destination.IsCalculated   = true;
                }
            }
            var searchList = destinations.Where(d => d.IsCalculated == false).Select(d => d.Address);

            var locationDistances = this.Queryable().Where(d => d.Origin == origin && searchList.Contains(d.Destination));

            foreach (var locationDistance in locationDistances)
            {
                var destinationItems = destinations.Where(d => d.Address == locationDistance.Destination);
                foreach (var destinationItem in destinationItems)
                {
                    destinationItem.TravelDuration = locationDistance.TravelDuration;
                    destinationItem.TravelDistance = locationDistance.TravelDistance;
                    destinationItem.IsCalculated   = true;
                    RockCache.AddOrUpdate(origin + destinationItem.Address, "org.secc.Mapping.LocationDistance", destinationItem);
                }
            }
        }
Esempio n. 2
0
        public static T Get(string qualifiedKey, Func <T> itemFactory, Func <List <string> > keyFactory)
        {
            var item = ( T )RockCache.Get(qualifiedKey);

            if (item != null)
            {
                return(item);
            }

            item = itemFactory();
            if (item != null)
            {
                var keys = AllKeys();
                if (!keys.Any() || !keys.Contains(qualifiedKey))
                {
                    UpdateKeys(keyFactory);
                }

                RockCache.AddOrUpdate(qualifiedKey, item);
            }
            else
            {
                //This item is gone! Make sure it's not in our key list
                UpdateKeys(keyFactory);
            }

            return(item);
        }
Esempio n. 3
0
        /// <summary>
        /// Removes this instance.
        /// </summary>
        public static void Remove()
        {
            RockCache.Remove(CacheKey);

            // use startDayOfWeekCache to optimize how long it takes to get the StartDayOfWeek, since will be used for all .GetSundayDate() calls (1 millions calls was taking 15seconds, but this reduces that down to 25 ms)
            startDayOfWeekCache = null;
        }
Esempio n. 4
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            int                 cacheTagDefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.CACHE_TAGS).Id;
            RockContext         rockContext           = new RockContext();
            DefinedValueService definedValueService   = new DefinedValueService(rockContext);
            var                 cacheTags             = definedValueService.Queryable().Where(v => v.DefinedTypeId == cacheTagDefinedTypeId).ToList();

            var gridData = new List <CacheTagGridRow>();

            foreach (var tag in cacheTags)
            {
                // do something here to get linked keys count
                long linkedKeys = RockCache.GetCountOfCachedItemsForTag(tag.Value);
                var  row        = new CacheTagGridRow
                {
                    TagName        = tag.Value,
                    TagDescription = tag.Description,
                    LinkedKeys     = linkedKeys,
                    DefinedValueId = tag.Id
                };

                gridData.Add(row);
            }

            gCacheTagList.DataSource = gridData;
            gCacheTagList.DataBind();
        }
        public static void RemoveAttendance(Attendance attendance)
        {
            lock ( LOCK )
            {
                var lglsc = (List <GroupLocationScheduleCount>)RockCache.Get(cacheKey);
                if (lglsc == null)
                {
                    lglsc = UpdateCache();
                }

                var personId = attendance.PersonAlias.PersonId;

                var items = lglsc.Where(g =>
                                        g.LocationId == attendance.Occurrence.LocationId &&
                                        g.ScheduleId == attendance.Occurrence.ScheduleId &&
                                        g.GroupId == attendance.Occurrence.GroupId)
                            .ToList();

                foreach (var glsc in items)
                {
                    while (glsc.PersonIds.Contains(personId))
                    {
                        glsc.PersonIds.Remove(personId);
                    }
                    while (glsc.InRoomPersonIds.Contains(personId))
                    {
                        glsc.InRoomPersonIds.Remove(personId);
                    }
                    RockCache.AddOrUpdate(cacheKey, null, lglsc, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// This fetches a dimension's related data.
        /// </summary>
        /// <returns>List of RestrictedData objects.</returns>
        public List <RestrictedData> GetDimensionRestrictedData(IntacctModel model)
        {
            string cacheKey             = INTACCT_CACHE_PREFIX + model.GetType().Name.ToUpper() + "_" + model.Id;
            List <RestrictedData> items = RockCache.Get(cacheKey) as List <RestrictedData>;

            if (items == null)
            {
                var request = GetRequest();
                var getDimensionRestrictedData = new GetDimensionRestrictedData();
                getDimensionRestrictedData.Function.DimensionValue.Dimension = model.GetType().Name.ToUpper();
                getDimensionRestrictedData.Function.DimensionValue.Value     = model.ApiId;
                request.Operation.Content.Function = getDimensionRestrictedData;

                var restRequest = new RestRequest("", Method.POST);
                restRequest.AddHeader("Content-Type", "application/xml");
                restRequest.RequestFormat = DataFormat.Xml;
                restRequest.AddBody(request);

                var response = client.Execute <List <RestrictedData> >(restRequest);

                var xmlDeserializer = new RestSharp.Deserializers.XmlDeserializer();
                var responseObj     = xmlDeserializer.Deserialize <Response>(response);
                if (responseObj?.Operation?.Result?.Status != "success" && !string.IsNullOrWhiteSpace(responseObj?.ErrorMessage?.Error?.Description))
                {
                    CheckResponse(response);
                }

                items = response.Data;

                RockCache.AddOrUpdate(cacheKey, items);
            }
            return(items);
        }
        private static List <GroupLocationScheduleCount> UpdateCache()
        {
            var output = new List <GroupLocationScheduleCount>();

            RockContext rockContext = new RockContext();

            AttendanceOccurrenceService attendanceOccurrenceService = new AttendanceOccurrenceService(rockContext);
            var attendances = attendanceOccurrenceService.Queryable()
                              .Where(ao => ao.OccurrenceDate == RockDateTime.Today)
                              .SelectMany(ao => ao.Attendees)
                              .Where(a => a.EndDateTime == null)
                              .GroupBy(a => new { a.Occurrence.GroupId, a.Occurrence.LocationId, a.Occurrence.ScheduleId })
                              .ToList();

            foreach (var attendance in attendances)
            {
                var glsc = new GroupLocationScheduleCount()
                {
                    GroupId         = attendance.Key.GroupId ?? 0,
                    LocationId      = attendance.Key.LocationId ?? 0,
                    ScheduleId      = attendance.Key.ScheduleId ?? 0,
                    PersonIds       = attendance.Select(a => a.PersonAlias?.PersonId ?? 0).ToList(),
                    InRoomPersonIds = attendance.Where(a => a.DidAttend == true).Select(a => a.PersonAlias?.PersonId ?? 0).ToList()
                };
                output.Add(glsc);
            }

            RockCache.AddOrUpdate(cacheKey, null, output, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            return(output);
        }
Esempio n. 8
0
        /// <summary>
        /// Gets the roles.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private static List <int> GetRoles(RockContext rockContext)
        {
            string cacheKey = "Rock.FindRelationships.Roles";

            List <int> roles = RockCache.Get(cacheKey) as List <int>;

            if (roles == null)
            {
                roles = new List <int>();

                foreach (var role in new GroupTypeRoleService(rockContext)
                         .Queryable().AsNoTracking()
                         .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS))))
                {
                    role.LoadAttributes(rockContext);
                    if (role.Attributes.ContainsKey("CanCheckin"))
                    {
                        bool canCheckIn = false;
                        if (bool.TryParse(role.GetAttributeValue("CanCheckin"), out canCheckIn) && canCheckIn)
                        {
                            roles.Add(role.Id);
                        }
                    }
                }

                RockCache.AddOrUpdate(cacheKey, null, roles, RockDateTime.Now.AddSeconds(300));
            }

            return(roles);
        }
Esempio n. 9
0
        private static List <Rock.Model.Group> GetBreakoutGroups(Person person, RockContext rockContext)
        {
            List <Rock.Model.Group> allBreakoutGroups = RockCache.Get(cacheKey) as List <Rock.Model.Group>;

            if (allBreakoutGroups == null || !allBreakoutGroups.Any())
            {
                //If the cache is empty, fill it up!
                Guid breakoutGroupTypeGuid = Constants.GROUP_TYPE_BREAKOUT_GROUPS.AsGuid();
                var  breakoutGroups        = new GroupService(rockContext)
                                             .Queryable("Members")
                                             .AsNoTracking()
                                             .Where(g => g.GroupType.Guid == breakoutGroupTypeGuid && g.IsActive && !g.IsArchived)
                                             .ToList();

                allBreakoutGroups = new List <Rock.Model.Group>();

                foreach (var breakoutGroup in breakoutGroups)
                {
                    allBreakoutGroups.Add(breakoutGroup.Clone(false));
                }

                RockCache.AddOrUpdate(cacheKey, null, allBreakoutGroups, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
            }

            return(allBreakoutGroups.Where(g => g.Members
                                           .Where(gm => gm.PersonId == person.Id && gm.GroupMemberStatus == GroupMemberStatus.Active).Any() &&
                                           g.IsActive && !g.IsArchived)
                   .ToList());
        }
        private List <Group> GetBreakoutGroups(Person person, RockContext rockContext, WorkflowAction action)
        {
            if (!string.IsNullOrWhiteSpace(GetAttributeValue(action, "BreakoutGroupType")))
            {
                List <Group> allBreakoutGroups = RockCache.Get(cacheKey) as List <Group>;
                if (allBreakoutGroups == null || !allBreakoutGroups.Any())
                {
                    //If the cache is empty, fill it up!
                    Guid breakoutGroupTypeGuid = GetAttributeValue(action, "BreakoutGroupType").AsGuid();
                    var  breakoutGroups        = new GroupService(rockContext)
                                                 .Queryable("Members")
                                                 .AsNoTracking()
                                                 .Where(g => g.GroupType.Guid == breakoutGroupTypeGuid && g.IsActive && !g.IsArchived)
                                                 .ToList();

                    allBreakoutGroups = new List <Group>();

                    foreach (var breakoutGroup in breakoutGroups)
                    {
                        allBreakoutGroups.Add(breakoutGroup.Clone(false));
                    }

                    RockCache.AddOrUpdate(cacheKey, null, allBreakoutGroups, RockDateTime.Now.AddMinutes(10), Constants.CACHE_TAG);
                }

                return(allBreakoutGroups.Where(g => g.Members
                                               .Where(gm => gm.PersonId == person.Id && gm.GroupMemberStatus == GroupMemberStatus.Active).Any() &&
                                               g.IsActive && !g.IsArchived)
                       .ToList());
            }
            else
            {
                return(new List <Group>());
            }
        }
Esempio n. 11
0
        private static List <string> UpdateKeys(Func <List <string> > keyFactory)
        {
            var keys = keyFactory().Select(k => QualifiedKey(k)).ToList();

            RockCache.AddOrUpdate(AllKey, AllRegion, keys);

            return(keys);
        }
Esempio n. 12
0
        /// <summary>
        /// Handles the ClearCacheTag event of the gCacheTagList control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        protected void gCacheTagList_ClearCacheTag(object sender, RowEventArgs e)
        {
            var definedValueId = e.RowKeyId;
            var definedValue   = DefinedValueCache.Get(definedValueId);

            RockCache.RemoveForTags(definedValue.Value);
            DisplayNotification(nbMessage, string.Format("Removed cached items tagged with \"{0}\".", definedValue.Value), NotificationBoxType.Success);
        }
Esempio n. 13
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var canAdministrateBlockOnPage = false;
            var pageBlocks = PageCache.Blocks;

            foreach (Rock.Web.Cache.BlockCache block in pageBlocks)
            {
                bool canAdministrate = block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson);
                bool canEdit         = block.IsAuthorized(Authorization.EDIT, CurrentPerson);
                bool canView         = block.IsAuthorized(Authorization.VIEW, CurrentPerson);

                // Make sure user has access to view block instance
                if (canAdministrate || canEdit || canView)
                {
                    Control control = null;

                    // Check to see if block is configured to use a "Cache Duration'
                    if (block.OutputCacheDuration > 0)
                    {
                        string blockCacheKey = string.Format("Rock:BlockOutput:{0}", block.Id);
                        if (RockCache.Get(blockCacheKey) != null)
                        {
                            // If the current block exists in our custom output cache, add the cached output instead of adding the control
                            control = new LiteralControl(RockCache.Get(blockCacheKey) as string);
                        }
                    }

                    if (control == null)
                    {
                        try
                        {
                            control = TemplateControl.LoadControl(block.BlockType.Path);
                            control.ClientIDMode = ClientIDMode.AutoID;
                        }
                        catch (Exception)
                        {
                            // Swallow this exception--NOM NOM
                        }
                    }

                    if (control != null)
                    {
                        if (canAdministrate || (canEdit && control is RockBlockCustomSettings))
                        {
                            canAdministrateBlockOnPage = true;
                        }
                    }
                }
            }

            if (PageCache.IncludeAdminFooter && (PageCache.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson) || canAdministrateBlockOnPage))
            {
                RockPage.AddCSSLink(ResolveRockUrl("~~/Styles/theme.css"));
            }
        }
        public static List <GroupLocationScheduleCount> GetByLocation(int locationId)
        {
            var glsc = (List <GroupLocationScheduleCount>)RockCache.Get(cacheKey);

            if (glsc == null)
            {
                glsc = UpdateCache();
            }
            return(glsc.Where(a => a.LocationId == locationId).ToList());
        }
Esempio n. 15
0
        private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
        {
            string value = RockCache.Get(context.Token).ToString();

            if (!string.IsNullOrWhiteSpace(value))
            {
                RockCache.Remove(context.Token);
                context.DeserializeTicket(value);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Populates the drop down list with an ordered list of cache type names.
        /// The selected item is used for the button to clear all the cache of
        /// that type.
        /// </summary>
        protected void PopulateCacheTypes()
        {
            ddlCacheTypes.Items.Clear();
            var entityCacheTypes = RockCache.GetAllModelCacheTypes();

            foreach (var entityCacheType in entityCacheTypes.OrderBy(s => s.Name))
            {
                ddlCacheTypes.Items.Add(new ListItem(entityCacheType.Name, entityCacheType.Name));
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Resets the database by using the specified path to a database archive file.
        /// </summary>
        /// <param name="archivePath">The archive path that contains the MDF and LDF files.</param>
        public static void ResetDatabase(string archivePath)
        {
            try
            {
                var cs  = ConfigurationManager.ConnectionStrings["RockContext"].ConnectionString;
                var csb = new SqlConnectionStringBuilder(cs);

                //
                // We need to connect to the master database, but track the target database
                // for use later.
                //
                var dbName = csb.InitialCatalog;
                csb.InitialCatalog = "master";

                //
                // If this is a URL, download it.
                //
                if (archivePath.ToUpper().StartsWith("HTTP"))
                {
                    archivePath = DownloadUrl(archivePath);
                }

                using (var archive = new ZipArchive(File.Open(archivePath, FileMode.Open)))
                {
                    using (var connection = new SqlConnection(csb.ConnectionString))
                    {
                        connection.Open();

                        //
                        // Check if the database already exists as if something went horribly wrong
                        // then it may not have been deleted.
                        //
                        using (var cmd = connection.CreateCommand())
                        {
                            cmd.CommandText = "SELECT COUNT(*) FROM [sysdatabases] WHERE [name] = @dbName";
                            cmd.Parameters.AddWithValue("dbName", dbName);

                            if (( int )cmd.ExecuteScalar() != 0)
                            {
                                DeleteDatabase(connection, dbName);
                            }
                        }

                        CreateDatabase(connection, dbName, archive);
                    }
                }

                RockCache.ClearAllCachedItems();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 18
0
        /// <summary>
        /// returns true if at least one of the endpoints is available.
        /// </summary>
        /// <returns>
        ///   <c>true</c> if [is redis available]; otherwise, <c>false</c>.
        /// </returns>
        private bool IsRedisAvailable(string[] endPoints)
        {
            string redisPassword      = SystemSettings.GetValueFromWebConfig(Rock.SystemKey.SystemSetting.REDIS_PASSWORD) ?? string.Empty;
            int    endPointErrorCount = 0;

            foreach (var endPoint in endPoints)
            {
                endPointErrorCount += RockCache.IsEndPointAvailable(endPoint, redisPassword) == true ? 0 : 1;
            }

            return(endPointErrorCount == endPoints.Length ? false : true);
        }
Esempio n. 19
0
        /// <summary>
        /// Populates the drop down list with an ordered list of cache type names.
        /// The selected item is used for the button to clear all the cache of
        /// that type.
        /// </summary>
        protected void PopulateDdlCacheTypes()
        {
            ddlCacheTypes.Items.Clear();
            ddlCacheTypes.Items.Add(new ListItem("All Cached Items", "all"));

            var cacheStats = RockCache.GetAllStatistics();

            foreach (CacheItemStatistics cacheItemStat in cacheStats.OrderBy(s => s.Name))
            {
                ddlCacheTypes.Items.Add(new ListItem(cacheItemStat.Name, cacheItemStat.Name));
            }
        }
Esempio n. 20
0
        private List <T> ReadByQuery <T>() where T : IntacctModel
        {
            string operation = typeof(T).Name.ToUpper();

            string   cacheKey = INTACCT_CACHE_PREFIX + operation;
            List <T> items    = RockCache.Get(cacheKey) as List <T>;

            if (items == null)
            {
                items = new List <T>();

                var request = GetRequest();
                request.Operation.Content.Function = new ReadByQuery(operation);

                var restRequest = new RestRequest("", Method.POST);
                restRequest.AddHeader("Content-Type", "application/xml");
                restRequest.RequestFormat = DataFormat.Xml;
                restRequest.AddBody(request);

                var response = client.Execute <List <T> >(restRequest);
                CheckResponse(response);

                var    responseObj  = new RestSharp.Deserializers.XmlDeserializer().Deserialize <Response>(response);
                int?   numRemaining = responseObj?.Operation?.Result?.Data?.NumRemaining ?? 0;
                string resultId     = responseObj?.Operation?.Result?.Data?.ResultId;
                items.AddRange(response.Data);

                while (numRemaining != 0 && !string.IsNullOrWhiteSpace(resultId))
                {
                    restRequest = new RestRequest("", Method.POST);
                    restRequest.AddHeader("Content-Type", "application/xml");
                    restRequest.RequestFormat = DataFormat.Xml;

                    request.Operation.Content.Function = new ReadMore(resultId);
                    restRequest.AddBody(request);

                    response = client.Execute <List <T> >(restRequest);
                    CheckResponse(response);

                    responseObj  = new RestSharp.Deserializers.XmlDeserializer().Deserialize <Response>(response);
                    numRemaining = responseObj?.Operation?.Result?.Data?.NumRemaining ?? 0;
                    items.AddRange(response.Data);
                }


                RockCache.AddOrUpdate(cacheKey, items);
            }
            return(items);
        }
        protected void btnClearCache_Click(object sender, EventArgs e)
        {
            var checkboxempty = cbl.SelectedValues;

            if (checkboxempty.Count > 0)
            {
                RockCache.RemoveForTags(GetSelectedValues());
                DisplayNotification(nbMessage, string.Format("Removed cached items tagged with \"{0}\".", GetSelectedValues()), NotificationBoxType.Success);
            }
            else
            {
                DisplayNotification(nbMessage, string.Format("No checkbox selected"), NotificationBoxType.Warning);
            }
            Save();
        }
Esempio n. 22
0
        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
    }
        public override void Up()
        {
            // Make sure this is unique
            if (DefinedTypeCache.Get(new Guid("0913F7A9-A2BF-479C-96EC-6CDB56310A83")) == null)
            {
                RockMigrationHelper.AddDefinedType("Global", "Hospitals", "Hospital List", "0913F7A9-A2BF-479C-96EC-6CDB56310A83", @"");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "City", "Qualifier2", "", 0, "", "CEDC60C1-0F9E-4FE2-BE62-41716813C968");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Notes", "Qualifier8", "", 0, "", "C47A879E-F737-4156-A1FF-B7C465FDB9BC");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Phone", "Qualifier5", "", 0, "", "A4E41679-2CE6-479F-84D4-6821B25E3648");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Speed Dial", "Qualifier6", "", 0, "", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F6");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "State", "Qualifier3", "", 0, "", "239E507C-7C1B-4B4D-84D4-33C368843F04");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Street Address", "Qualifier1", "", 0, "", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9C");
                RockMigrationHelper.AddDefinedTypeAttribute("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Zip", "Qualifier4", "", 0, "", "46A83E00-D530-48AD-B935-52C015DCA901");
                RockMigrationHelper.AddDefinedValue("0913F7A9-A2BF-479C-96EC-6CDB56310A83", "Sample Hospital", "", "0997ACB6-A4B4-4766-B573-3C44D14DF342", false);
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "239E507C-7C1B-4B4D-84D4-33C368843F04", @"KY");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "46A83E00-D530-48AD-B935-52C015DCA901", @"40023");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9C", @"1 Main St");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "A4E41679-2CE6-479F-84D4-6821B25E3648", @"(502) 111-1111");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "C47A879E-F737-4156-A1FF-B7C465FDB9BC", @"");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "CEDC60C1-0F9E-4FE2-BE62-41716813C968", @"Louisville");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF342", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F6", @"");
            }

            // Make sure this is unique
            if (DefinedTypeCache.Get(new Guid("4573E600-4E00-4BE9-BA92-D17093C735D6")) == null)
            {
                RockMigrationHelper.AddDefinedType("Global", "Nursing Homes", "Nursing Home List", "4573E600-4E00-4BE9-BA92-D17093C735D6", @"");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "City", "Qualifier2", "", 0, "", "CEDC60C1-0F9E-4FE2-BE62-41716813C969");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Notes", "Qualifier8", "", 0, "", "C47A879E-F737-4156-A1FF-B7C465FDB9BD");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Phone", "Qualifier5", "", 0, "", "A4E41679-2CE6-479F-84D4-6821B25E3649");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Pastoral Minister", "Qualifier6", "", 0, "", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F7");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "State", "Qualifier3", "", 0, "", "239E507C-7C1B-4B4D-84D4-33C368843F05");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Street Address", "Qualifier1", "", 0, "", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9D");
                RockMigrationHelper.AddDefinedTypeAttribute("4573E600-4E00-4BE9-BA92-D17093C735D6", "9C204CD0-1233-41C5-818A-C5DA439445AA", "Zip", "Qualifier4", "", 0, "", "46A83E00-D530-48AD-B935-52C015DCA902");
                RockMigrationHelper.AddDefinedValue("4573E600-4E00-4BE9-BA92-D17093C735D6", "Sample Nursing Home", "", "0997ACB6-A4B4-4766-B573-3C44D14DF343", false);
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "239E507C-7C1B-4B4D-84D4-33C368843F05", @"KY");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "46A83E00-D530-48AD-B935-52C015DCA902", @"40023");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "73AC0DCE-CE90-4835-AAE7-E98B08F52E9D", @"2 Main St");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "A4E41679-2CE6-479F-84D4-6821B25E3649", @"(502) 111-1111");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "C47A879E-F737-4156-A1FF-B7C465FDB9BD", @"");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "CEDC60C1-0F9E-4FE2-BE62-41716813C969", @"Louisville");
                RockMigrationHelper.AddDefinedValueAttributeValue("0997ACB6-A4B4-4766-B573-3C44D14DF343", "D97EC9DE-5D6A-42FD-B4CE-0516FD5455F7", @"John Adams");
            }
            // Make sure to clear the Rock Cache so the defined type above will be there
            RockCache.ClearAllCachedItems();
        }
Esempio n. 24
0
        /// <summary>
        /// Handles the Click event of btnClearCache and clears the selected cache type.
        /// </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)
        {
            List <string> result = new List <string>();

            if (ddlCacheTypes.SelectedValue == "all")
            {
                result = RockCache.ClearAllCachedItems();
            }
            else
            {
                result.Add(RockCache.ClearCachedItemsForType(ddlCacheTypes.SelectedValue));
            }

            PopulateCacheStatistics();

            DisplayNotification(nbMessage, "All cached items have been cleared.", NotificationBoxType.Success);
        }
Esempio n. 25
0
        public static void AddOrUpdate(string qualifiedKey, T item, Func <List <string> > keyFactory)
        {
            if (item == null)
            {
                return;
            }

            var keys = AllKeys();

            if (!keys.Any() || !keys.Contains(qualifiedKey))
            {
                UpdateKeys(keyFactory);
            }

            //RockCacheManager<T>.Instance.Cache.AddOrUpdate( qualifiedKey, item, v => item );
            RockCache.AddOrUpdate(qualifiedKey, item);
        }
Esempio n. 26
0
        private string GetCacheInfo()
        {
            StringBuilder sb = new StringBuilder();

            var cacheStats = RockCache.GetAllStatistics();
            foreach ( CacheItemStatistics cacheItemStat in cacheStats.OrderBy( s => s.Name ) )
            {
                foreach ( CacheHandleStatistics cacheHandleStat in cacheItemStat.HandleStats )
                {
                    var stats = new List<string>();
                    cacheHandleStat.Stats.ForEach( s => stats.Add( string.Format( "{0}: {1:N0}", s.CounterType.ConvertToString(), s.Count ) ) );
                    sb.AppendFormat( "<p><strong>{0}:</strong><br/>{1}</p>{2}", cacheItemStat.Name, stats.AsDelimited( ", " ), Environment.NewLine );
                }
            }

            return sb.ToString();
        }
Esempio n. 27
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 />"));
        }
Esempio n. 28
0
        /// <summary>
        /// Resets the database by using the specified path to a database archive file.
        /// </summary>
        /// <param name="archivePath">The archive path that contains the MDF and LDF files.</param>
        public static void ResetDatabase(string archivePath)
        {
            var cs  = ConfigurationManager.ConnectionStrings["RockContext"].ConnectionString;
            var csb = new SqlConnectionStringBuilder(cs);

            //
            // We need to connect to the master database, but track the target database
            // for use later.
            //
            var dbName = csb.InitialCatalog;

            csb.InitialCatalog = "master";

            //
            // If this is a URL, download it.
            //
            if (archivePath.ToUpper().StartsWith("HTTP"))
            {
                archivePath = DownloadUrl(archivePath);
            }

            using (var archive = new ZipArchive(File.Open(archivePath, FileMode.Open)))
            {
                using (var connection = new SqlConnection(csb.ConnectionString))
                {
                    connection.Open();

                    //
                    // If the database exists, that means something probably went
                    // horribly wrong on a previous run so we need to manually
                    // delete the database.
                    if (DoesDatabaseExist(dbName, connection))
                    {
                        DeleteDatabase(connection, dbName);
                    }

                    RestoreDatabase(connection, dbName, archive);
                }
            }

            RockCache.ClearAllCachedItems();
        }
Esempio n. 29
0
        /// <summary>
        /// Creates a recipient token to help track conversations.
        /// </summary>
        /// <param name="rockContext">A context to use for database calls.</param>
        /// <returns>String token</returns>
        public static string GenerateResponseCode(Rock.Data.RockContext rockContext)
        {
            DateTime tokenStartDate = RockDateTime.Now.Subtract(new TimeSpan(TOKEN_REUSE_DURATION, 0, 0, 0));
            var      communicationRecipientService = new CommunicationRecipientService(rockContext);

            lock ( _responseCodesLock )
            {
                var availableResponseCodes = RockCache.Get(RESPONSE_CODE_CACHE_KEY) as List <string>;

                //
                // Try up to 1,000 times to find a code. This really should never go past the first
                // loop but we will give the benefit of the doubt in case a code is issued via SQL.
                //
                for (int attempts = 0; attempts < 1000; attempts++)
                {
                    if (availableResponseCodes == null || !availableResponseCodes.Any())
                    {
                        availableResponseCodes = GenerateAvailableResponseCodeList(rockContext);
                    }

                    var code = availableResponseCodes[0];
                    availableResponseCodes.RemoveAt(0);

                    //
                    // Verify that the code is still unused.
                    //
                    var isUsed = communicationRecipientService.Queryable()
                                 .Where(c => c.ResponseCode == code)
                                 .Where(c => c.CreatedDateTime.HasValue && c.CreatedDateTime > tokenStartDate)
                                 .Any();

                    if (!isUsed)
                    {
                        RockCache.AddOrUpdate(RESPONSE_CODE_CACHE_KEY, availableResponseCodes);
                        return(code);
                    }
                }
            }

            throw new Exception("Could not find an available response code.");
        }
Esempio n. 30
0
        protected void PopulateRedisView()
        {
            // clear and hide edit
            ClearAndHideRedisEdit();

            RedisEndPointAvailabilityCheck();

            redisView.Visible = true;

            bool enabled = RockCache.IsCacheSerialized;

            if (!enabled)
            {
                DisplayNotification(nbRedisSettings, "Redis is currently not enabled. Review documentation for more information on enabling Redis backplane support.", NotificationBoxType.Info);
                redisEnabled.Visible = false;
                return;
            }

            redisEnabled.Visible = true;

            string redisPassword = SystemSettings.GetValueFromWebConfig(Rock.SystemKey.SystemSetting.REDIS_PASSWORD) ?? string.Empty;

            string serverList = string.Join(
                string.Empty,
                SystemSettings.GetValueFromWebConfig(Rock.SystemKey.SystemSetting.REDIS_ENDPOINT_LIST)
                .Split(',')
                .Select(s =>
                        (
                            RockCache.IsEndPointAvailable(s, redisPassword) == true ?
                            "<span class='label label-success'>" + s + " Endpoint is available </span><br />" :
                            "<span class='label label-warning'>" + s + " Endpoint is not available </span><br />"
                        )));

            // show and populate view
            cbEnabled.Checked      = enabled;
            lEndPointList.Text     = serverList;
            lblPassword.Text       = SystemSettings.GetValueFromWebConfig(Rock.SystemKey.SystemSetting.REDIS_PASSWORD).IsNullOrWhiteSpace() ? string.Empty : "***********";
            lblDatabaseNumber.Text = SystemSettings.GetValueFromWebConfig(Rock.SystemKey.SystemSetting.REDIS_DATABASE_NUMBER);
        }