Blog

My blog serves as a way for me to post solutions to problems I solve at work or during the long hours of freelance work.


C# How to Cache Data Using Generic Method

by Ezekiel 9. December 2011 03:31

 

using System;
using System.Web;
using System.Web.Caching;
using System.Collections.Generic;
using System.Linq;
using RoboticsDataCapture.Model;

namespace MyNameSpace
{
    /// <summary>
    /// Cache wrapper to handle caching data
    /// </summary>
    public static class CacheWrapper
    {
        /// <summary>
        /// Generic cache method
        /// </summary>
        /// <typeparam name="T">Object type</typeparam>
        /// <param name="key">Cache key</param>
        /// <param name="expiration">When cache expires</param>
        /// <param name="fetcher">Generic method to search cache</param>
        /// <returns></returns>
        public static T CacheFetch<T>(string key, DateTime expiration, Func<T> fetcher) where T : class
        {
            Cache DataCache = HttpContext.Current.Cache;

            // Cache if the key is not null or blank
            if ((key ?? "").Length <= 0)
            {
                return fetcher();
            }

            T result = DataCache[key] as T;

            if (result == null)
            {
                result = fetcher();

                if (result == null)
                {
                    DataCache.Remove(key);
                }
                else
                {
                    DataCache.Add(key, result, null, expiration,
                        Cache.NoSlidingExpiration, CacheItemPriority.AboveNormal, null);
                }
            }

            return result;
        }
    }

    /// <summary>
    /// Class using generic caching of entityframe database calls
    /// </summary>
    public class MyClass
    {
        public int Id { get; set; }
        public string Name { get; set; }

        // Set cache expiration
        private static DateTime expiration = DateTime.Now.AddHours(24);

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public static List<MyClass> GenericList()
        {
            return CacheWrapper.CacheFetch<List<MyClass>>("CachedDataName", expiration, () =>
            {
                using (Entities entities = new Entities())
                {
                    var databaseReturn = from t in entities.Table
                                         select new MyClass
                                          {
                                              Id = t.Id,
                                              Name = t.Name
                                          };

                    return databaseReturn.ToList();
                }
            });
        }
    }
}

Tags: , , , ,

ASP.NET | C# | Generics | Cache | LINQ to EntityFrame

C# Generic Extension Method to Move an Item to the Top of a Generic List

by Ezekiel 19. October 2011 07:54

 

    public static class ListExtensions
    {
        public static List<T> MoveToFront<T>(this List<T> list, Predicate<T> match)
        {
            int idx = list.FindIndex(match);

            if (idx != -1)
            {
                if (idx != 0) // move only if not already in front
                {
                    T value = list[idx]; // save matching value
                    list.RemoveAt(idx); // remove it from original location
                    list.Insert(0, value); // insert in front
                }

                return list;
            }

            return list; // matching value not found
        }
    }

 

How to use -

ClassName.ListMethod().MoveToFront(i => i.Id == 0); 

Tags: , , ,

C# | LAMBDA | Generics

RecentPosts