System Library Common Framework
Search Results for

    *.Benchmark*,*.Tests*,*.ApiTests*,*.BaseTest*,DelegateJsonConverter,CalleeCancelledRequestException,ClientResponse,ContentType,OutputCachePolicy
    Show / Hide Table of Contents Show / Hide Table of Contents
    NamespaceSystemLibrary.Common.Framework.App SystemLibrary.Common.Framework.Cache.dll

    Caching for applications

    Default duration is 3 minutes

    Try using auto-generating cache keys, which differentiate caching down to user roles.

    - Cache things per user, by userId/email? Create your own cacheKey

    'Ignore' means the function will always be invoked directly, bypassing the cache entirely.

    Skip options:

    - skipWhenAuthenticated, false by default

    - skipWhenAdmin, true by default

    The user must belong to one of the following case-sensitive roles: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators.

    - skipWhen, your own condition, must return True to skip
    Remarks
    X

    Cache is configured to a max capacity of 320.000 items, divided by 8 cache containers, where any item added takes up 1 size

    Each container is configured to a max capacity of 40.000 items, once reached 33% of the oldest are removed, ready to be GC'ed

    A null value is never added to cache

    Overwrite default cache configurations in appsettings.json:

    - duration: 180, minimum 1

    - fallbackDuration: 300, set to 0 or negative to disable fallback cache globally

    - containerSizeLimit: 60000, minimum 10

    Auto-generating cache key adds namespace, class, method, method-scoped variables of types such as bool, string, int, datetime, enum and few others

    - If a method-scoped variable is a class, its public members of same types are also appended as cacheKey

    - IsAuthenticated is always appended to cacheKey

    - Claim 'role', 'Role' and RoleClaimType if found, is always appended to cacheKey

    - Always adds built-in prefix

    Cache

    public static class Cache

    Inheritance
    object
    Cache
    Examples
    X

    Use cache:

    using SystemLibrary.Common.Framework.App;
    
    var cacheKey = "key";
    var item = Cache.Get(cacheKey);
    // null if not in cache
    Arguments
    X

    Methods

    Clear all entries found, which was set through this Cache class

    Remarks
    X

    Only entries set through either TryGet, Get or Set will be cleared

    - other cache mechanisms that you are using are not touched

    Clearing cache is not thread safe as it null's out the cache containers and recreates them all

    - null checks exists before the cache containers are used, but it does not gurantee thread safety

    public static void Clear()

    X
    Cache.Clear();
    X

    Get item from Cache as T using auto-generated cache key

    Remarks
    X

    A null value is never added to cache

    Throws exception if getItem can throw

    Default duration is 200 seconds

    'Ignore' means the function will always be invoked directly, bypassing the cache entirely.

    Skip options:

    - skipWhenAuthenticated, false by default

    - skipWhenAdmin, true by default

    The user must belong to one of the following case-sensitive roles: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators.

    - skipWhen, your own condition, must return True to skip

    public static T Get<T>(Func<T> getItem, string cacheKey = "", CacheDuration duration = CacheDuration.Unset, Func<T, bool> condition = null, bool skipWhenAuthenticated = false, bool skipWhenAdmin = true, Func<bool> skipWhen = null)

    X

    Simplest example:

    var data = Cache.Get(() => {
        return "hello world";
    });
    
    //'data' is now 'hello world', if called multiple times within the default cache duration of 180 seconds, "hello world" is returned from the cache for all non-admin users

    Simplest example with cacheKey:

    var cacheKey = "hello-world-key";
    var data = Cache.Get(() => {
        return "hello world";
    },
    cacheKey: cacheKey);
    
    //'data' is now 'hello world', if called multiple times within the default cache duration of 180 seconds, "hello world" is returned from the cache for all non-admin users

    Example with multiple options passed, and a condition that always fails:

    var cacheKey = "hello-world-key";
    var data = Cache.Get(() => {
            return "hello world";
        },
        cacheKey: cacheKey,
        duration: TimeSpan.FromSeconds(1),
        condition: x => x != "hello world",
        skipWhenAuthenticated: false);
    
    //'data' is equal to 'hello world', cache duration is 1 second, but it only adds the result to cache, if it is not equal to "hello world"
    // so in this scenario - "hello world" is never added to cache, and our function that returns "hello world" is always invoked

    Example without a cache key

    class CarService
    {
        public string GetCars() 
        {
            return Cache.Get<string>(() => {
                return Client.Get<string>("https://systemlibrary.com/api/cars?top=1");
            },
            skipWhenAdmin: false);
        }
    }
    // This caches top 1 cars for every user, even admins, as we set 'skipWhenAdmin' to False

    Example without a cache key and with 'external' variables

    class CarService
    {
        public string GetCars(int top = 10) 
        {
            var url = "https://systemlibrary.com/api/cars";
            var urlQueryValue = "?filter=none";
    
            return Cache.Get<string>(() => {
                return Client.Get<string>(url + urlQueryValue + " top=" + top);
            });
        }
    }
    
    // Returns top 10 cars from the API, and adds result to cache (assumes not null) for a duration of 180 seconds by default
    // For simplicity, pretend an auto cache key looks like this: SLF%...
    
    // Note: cache key is created with the outside variable "top", it is ".ToString'd", works on many types: bool, datetime, string, and simple POCO's with 1 depth level of properties/fields, not "class inside class" is not supported
    // Note: cache key for wether or not user is logged in is always appended so it always varies on "IsAuthenticated"
    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    Func<T> getItem
    string cacheKey

    "" to use auto-generating of cacheKey, null to always skip cache

    CacheDuration duration
    Func<T, bool> condition

    Add to cache only if condition is true, for instance: data?.Count > 0

    bool skipWhenAuthenticated

    Skip cache for any user that is authenticated through the current HttpContext.User instance

    bool skipWhenAdmin

    Skip cache for any user that is authenticated through the current HttpContext.User and is in any role: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators

    Func<bool> skipWhen

    Implement your own logic for when to skip cache, let it return true on your conditions to avoid caching

    X
    Type Description
    T

    Returns item from cache or getItem

    Get item from Cache as T using auto-generated cache key

    Remarks
    X

    A null value is never added to cache

    Throws exception if getItem can throw

    Default duration is 200 seconds

    'Ignore' means the function will always be invoked directly, bypassing the cache entirely.

    Skip options:

    - skipWhenAuthenticated, false by default

    - skipWhenAdmin, true by default

    The user must belong to one of the following case-sensitive roles: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators.

    - skipWhen, your own condition, must return True to skip

    public static T Get<T>(Func<T> getItem, CacheDuration duration, Func<T, bool> condition = null, bool skipWhenAuthenticated = false, bool skipWhenAdmin = true, Func<bool> skipWhen = null)

    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    Func<T> getItem
    CacheDuration duration
    Func<T, bool> condition

    Add to cache only if condition is true, for instance: data?.Count > 0

    bool skipWhenAuthenticated

    Skip cache for any user that is authenticated through the current HttpContext.User instance

    bool skipWhenAdmin

    Skip cache for any user that is authenticated through the current HttpContext.User and is in any role: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators

    Func<bool> skipWhen

    Implement your own logic for when to skip cache, let it return true on your conditions to avoid caching

    X
    Type Description
    T

    Returns T from cache or from getItem, or throws if getItem throws

    Get item from Cache as T

    Remarks
    X

    CacheKey null or blank returns default without checking cache

    This never checks fallback cache

    public static T Get<T>(string cacheKey)

    X
    var cacheKey = "helloworld";
    var data = Cache.Get<string>(cacheKey);
    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    string cacheKey
    X
    Type Description
    T

    Return item from cache if exists or default

    Get item from Cache as T

    Remarks
    X

    A null value is never added to cache

    Throws exception if getItem can throw

    Default duration is 200 seconds

    'Ignore' means the function will always be invoked directly, bypassing the cache entirely.

    Skip options:

    - skipWhenAuthenticated, false by default

    - skipWhenAdmin, true by default

    The user must belong to one of the following case-sensitive roles: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators.

    - skipWhen, your own condition, must return True to skip

    public static T Get<T>(string cacheKey, Func<T> getItem, CacheDuration duration = CacheDuration.Unset, Func<T, bool> condition = null, bool skipWhenAuthenticated = false, bool skipWhenAdmin = true, Func<bool> skipWhen = null)

    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    string cacheKey

    "" to use auto-generating of cacheKey, null to always skip cache

    Func<T> getItem
    CacheDuration duration
    Func<T, bool> condition

    Add to cache only if condition is true, for instance: data?.Count > 0

    bool skipWhenAuthenticated

    Skip cache for any user that is authenticated through the current HttpContext.User instance

    bool skipWhenAdmin

    Skip cache for any user that is authenticated through the current HttpContext.User and is in any role: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators

    Func<bool> skipWhen

    Implement your own logic for when to skip cache, let it return true on your conditions to avoid caching

    X
    Type Description
    T

    Returns T from cache or from getItem, or throws if getItem throws

    Ensures that the enclosed code block executes only once within the specified duration

    Default break duration is 60 seconds

    Remarks
    X

    Uses the stack frame to read current namespace and method as cache key, so max 1 invocation per function scope, else you must fill out the breakKey parameter too

    - in the future it might support multiple...

    Multiple threads running at same time, will trigger this multiple times as we do not really 'lock'

    public static bool Lock(CacheDuration duration = CacheDuration.Unset, string lockKey = null)

    X
    if(Cache.Lock(TimeSpan.FromSeconds(60), "send-email") 
    {
        new Email(...).Send(); // Pseudo code
        // Example: invoking this code 66 times, one time per second, where first invocation is one second from "now", will send two emails: one at second 1, and another at second 61
    }
    X
    Methods arguments
    Type Name Description
    CacheDuration duration

    The time span for which subsequent executions are prevented.

    string lockKey
    X
    Type Description
    bool

    True if the block is allowed to execute; otherwise, false.

    Remove item from Cache

    Remarks
    X

    Does nothing if item do not exist in cache or if cacheKey is null/blank

    public static void Remove(string cacheKey)

    X
    var cacheKey = "hello world";
    Cache.Remove(cacheKey);
    X
    Methods arguments
    Type Name Description
    string cacheKey

    Add item to cache

    Remarks
    X

    A null value is never added to cache

    public static void Set<T>(string cacheKey, T item, CacheDuration duration = CacheDuration.Unset)

    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    string cacheKey

    CacheKey to set item as, if null or empty this does nothing

    T item
    CacheDuration duration

    Defaults to 180 seconds

    Try get item from Cache as T using auto-generated cache key

    Logs exception if getItem() throws

    Remarks
    X

    A null value is never added to cache

    Default duration is 200 seconds

    'Ignore' means the function will always be invoked directly, bypassing the cache entirely.

    Skip options:

    - skipWhenAuthenticated, false by default

    - skipWhenAdmin, true by default

    The user must belong to one of the following case-sensitive roles: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators.

    - skipWhen, your own condition, must return True to skip

    public static T TryGet<T>(Func<T> getItem, string cacheKey = "", CacheDuration duration = CacheDuration.Unset, Func<T, bool> condition = null, bool skipWhenAuthenticated = false, bool skipWhenAdmin = true, Func<bool> skipWhen = null)

    X
    var data = Cache.TryGet<string>(() => throw new Exception("does not crash application"));
    
    // Exception is logged through your ILogWriter implementation
    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    Func<T> getItem
    string cacheKey

    "" to use auto-generating of cacheKey, null to always skip cache

    CacheDuration duration
    Func<T, bool> condition

    Add to cache only if condition is true, for instance: data?.Count > 0

    bool skipWhenAuthenticated

    Skip cache for any user that is authenticated through the current HttpContext.User instance

    bool skipWhenAdmin

    Skip cache for any user that is authenticated through the current HttpContext.User and is in any role: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators

    Func<bool> skipWhen

    Implement your own logic for when to skip cache, let it return true on your conditions to avoid caching

    X
    Type Description
    T

    Returns T from cache or from getItem. If getItem throws, the exception is logged as error and default is returned

    Try get item from Cache as T using auto-generated cache key

    Logs exception if getItem() throws

    Remarks
    X

    A null value is never added to cache

    Default duration is 200 seconds

    'Ignore' means the function will always be invoked directly, bypassing the cache entirely.

    Skip options:

    - skipWhenAuthenticated, false by default

    - skipWhenAdmin, true by default

    The user must belong to one of the following case-sensitive roles: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators.

    - skipWhen, your own condition, must return True to skip

    public static T TryGet<T>(Func<T> getItem, CacheDuration duration, Func<T, bool> condition = null, bool skipWhenAuthenticated = false, bool skipWhenAdmin = true, Func<bool> skipWhen = null)

    X
    var data = Cache.TryGet<string>(() => throw new Exception("does not crash application"));
    // Exception is logged through your ILogWriter implementation
    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    Func<T> getItem
    CacheDuration duration
    Func<T, bool> condition

    Add to cache only if condition is true, for instance: data?.Count > 0

    bool skipWhenAuthenticated

    Skip cache for any user that is authenticated through the current HttpContext.User instance

    bool skipWhenAdmin

    Skip cache for any user that is authenticated through the current HttpContext.User and is in any role: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators

    Func<bool> skipWhen

    Implement your own logic for when to skip cache, let it return true on your conditions to avoid caching

    X
    Type Description
    T

    Returns T from cache or from getItem. If getItem throws, the exception is logged as error and default is returned

    Try get item from Cache as T

    If getItem throws, the exception is logged as 'Error'

    Remarks
    X

    A null value is never added to cache

    Default duration is 200 seconds

    'Ignore' means the function will always be invoked directly, bypassing the cache entirely.

    Skip options:

    - skipWhenAuthenticated, false by default

    - skipWhenAdmin, true by default

    The user must belong to one of the following case-sensitive roles: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators.

    - skipWhen, your own condition, must return True to skip

    public static T TryGet<T>(string cacheKey, Func<T> getItem, CacheDuration duration = CacheDuration.Unset, Func<T, bool> condition = null, bool skipWhenAuthenticated = false, bool skipWhenAdmin = true, Func<bool> skipWhen = null)

    X
    var cacheKey = "key";
    
    var data = Cache.TryGet<string>(cacheKey, () => throw new Exception("does not crash application"));
    
    // Exception is logged through your ILogWriter implementation
    X
    Generic types
    Name Description
    T
    Methods arguments
    Type Name Description
    string cacheKey

    "" to use auto-generating of cacheKey, null to always skip cache

    Func<T> getItem
    CacheDuration duration
    Func<T, bool> condition

    Add to cache only if condition is true, for instance: data?.Count > 0

    bool skipWhenAuthenticated

    Skip cache for any user that is authenticated through the current HttpContext.User instance

    bool skipWhenAdmin

    Skip cache for any user that is authenticated through the current HttpContext.User and is in any role: Admin, Admins, Administrator, Administrators, WebAdmins, CmsAdmins, admin, admins, administrator, administrators

    Func<bool> skipWhen

    Implement your own logic for when to skip cache, let it return true on your conditions to avoid caching

    X
    Type Description
    T

    Returns T from cache or from getItem. If getItem throws, the exception is logged as error and default is returned

    }

    In This Article
    Package: nuget
    Source: github
    Website: System Library Common Framework