Tuesday, 15 November 2022

Create and use cache mechanism in D365 F&O using x++

Below class is used to set, get, remove cache from the application

public class ENCGlobalCacheManager

{

    // This string is appended for the values that are containers. Avoids type mismatches

    public static const str cont = "_container";

    private static str getUniqueSessionId()

    {

        return curUserId() + "_" + int2Str(sessionId());

    }

 

    public static anytype get(anytype _key, anytype _returnValue = '')

    {

        return appl.globalCache().get(ENCGlobalCacheManager::getUniqueSessionId(), _key, _returnValue);

    }

 

    public static anytype getContainer(anytype _key, anytype _returnValue = '')

    {

        if(ENCGlobalCacheManager::containerIsSet(_key))

        {

            return appl.globalCache().get(ENCGlobalCacheManager::getUniqueSessionId() + ENCGlobalCacheManager::cont, _key, _returnValue);

        }

        else

        {

            return null;

        }

    }

    public static boolean isSet(anytype _key)

    {

        return appl.globalCache().isSet(ENCGlobalCacheManager::getUniqueSessionId(), _key);

    }

    public static boolean containerIsSet(anytype _key)

    {

        return appl.globalCache().isSet(ENCGlobalCacheManager::getUniqueSessionId() + ENCGlobalCacheManager::cont, _key);

    }

 

    public static boolean remove(anytype _key)

    {

        return appl.globalCache().remove(ENCGlobalCacheManager::getUniqueSessionId(),  _key);

    }

 

    public static boolean removeContainer(anytype _key)

    {

        return appl.globalCache().remove(ENCGlobalCacheManager::getUniqueSessionId() + ENCGlobalCacheManager::cont,  _key);

    }

 

    public static boolean set(anytype _key, anytype _value, boolean _isVolatile = true)

    {

        return appl.globalCache().set(ENCGlobalCacheManager::getUniqueSessionId(), _key, _value, _isVolatile);

    }

 

    public static boolean setContainer(anytype _key, anytype _value, boolean _isVolatile = true)

    {

        return appl.globalCache().set(ENCGlobalCacheManager::getUniqueSessionId() + ENCGlobalCacheManager::cont, _key, _value, _isVolatile);

    } 

} 


How to set value to cache

If (ENCGlobalCacheManager::isSet("KeyValue"))

{

    ENCGlobalCacheManager::remove("KeyValue");

}

ENCGlobalCacheManager::set("KeyValue", "Value");


KeyValue - KeyValue can be anything like salesId, custGroupId

Value    - Actual value to set in cache


How to get value to cache

if(ENCGlobalCacheManager::isSet("KeyValue")

{

    this.Value= ENCGlobalCacheManager::get("KeyValue");

    ENCGlobalCacheManager::remove("KeyValue");

}