• Stars
    star
    629
  • Rank 71,454 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Easily cache any data structure for a specific amount of time in any .NET application.

๐Ÿ’Cache

2.0-beta -> This is a WIP and targets only .NET 6 using source generators instead of Newtonsoft.Json. This is cutting edge, please don't update yet unless you want to try out some crazy awesome stuff ;)

Easily cache any data structure for a specific amount of time in any .NET application.

Monkey Cache is comprised of one core package (MonkeyCache) and three providers which reference the core package as a dependency. At least one provider must be installed for Monkey Cache to work and each offer the same API (IBarrel). Depending on your existing application you may already have SQLite or LiteDB installed so these would be your natural choice. A lightweight file based Monkey Cache is also provided if you aren't already using one of these options.

Listen to our podcast Merge Conflict: Episode 76 for an overview of Monkey Cache and it's creation.

A full breakdown of performance can be found in the performance.xlsx. When dealing with a small amount of records such as inserting under 50 records, the performance difference between each provider is negligible and it is only when dealing with a large amount of records at a single time that you should have to worry about the provider type.

Azure DevOps

You can follow the full project here: https://dev.azure.com/jamesmontemagno/MonkeyCache

Build Status:

NuGets

Name Description NuGet
๐Ÿ’ MonkeyCache Contains base interfaces and helpers NuGet
๐Ÿ™Š MonkeyCache.SQLite A SQLite backing for Monkey Cache NuGet
๐Ÿ™‰ MonkeyCache.LiteDB A LiteDB backing for Monkey Cache NuGet
๐Ÿ™ˆ MonkeyCache.FileStore A local file based backing for Monkey Cache NuGet
Development Feed MyGet

Platform Support

Monkey Cache is a .NET Standard 2.0 library, but has some platform specific tweaks for storing data in the correct Cache directory.

Platform Version
Xamarin.iOS iOS 7+
Xamarin.Mac All
Xamarin.Android API 14+
Windows 10 UWP 10.0.16299+
.NET Core 2.0+
ASP.NET Core 2.0+
.NET Framework 4.6.1+

Setup

First, select an implementation of Monkey Cache that you would like (LiteDB, SQLite, or FileStore). Install the specific NuGet for that implementation, which will also install the base MonkeyCache library. Installing MonkeyCache without an implementation will only give you the high level interfaces.

It is required that you set an ApplicationId for your application so a folder is created specifically for your app on disk. This can be done with a static string on Barrel before calling ANY method:

Barrel.ApplicationId = "your_unique_name_here";

LiteDB Encryption

LiteDB offers built in encryption support, which can be enabled with a static string on Barrel before calling ANY method. You must choose this up front before saving any data.

Barrel.EncryptionKey = "SomeKey";

LiteDB Upgrade (4 -> 5) | NuGet 1.3 -> 1.5

If you are upgrading from 1.3 to 1.5 of the NuGet package it also went through an upgrade of LiteDB.

You may need to do an upgrade of the database before using it. In your project you can set the folowing after setting your EncryptionKey or Applicationid:

Barrel.Upgrade = true;

What is Monkey Cache?

The goal of Monkey Cache is to enable developers to easily cache any data for a limited amount of time. It is not Monkey Cache's mission to handle network requests to get or post data, only to cache data easily.

All data for Monkey Cache is stored and retrieved in a Barrel.

For instance you are making a web request and you get some json back from the server. You would want the ability to cache this data in case you go offline, but also you need it to expire after 24 hours.

That may look something like this:

async Task<IEnumerable<Monkey>> GetMonkeysAsync()
{
    var url = "http://montemagno.com/monkeys.json";

    //Dev handle online/offline scenario
    if (!CrossConnectivity.Current.IsConnected)
    {
        return Barrel.Current.Get<IEnumerable<Monkey>>(key: url);
    }
    
    //Dev handles checking if cache is expired
    if (!Barrel.Current.IsExpired(key: url))
    {
        return Barrel.Current.Get<IEnumerable<Monkey>>(key: url);
    }

    var client = new HttpClient();
    var monkeys = await client.GetFromJsonAsync<IEnumerable<Monkey>>(url);

    //Saves the cache and pass it a timespan for expiration
    Barrel.Current.Add(key: url, data: monkeys, expireIn: TimeSpan.FromDays(1));
}

Ideally, you can make these calls extremely generic and just pass in a string:

public async Task<T> GetAsync<T>(string url, int days = 7, bool forceRefresh = false)
{
    if (!CrossConnectivity.Current.IsConnected)
        return Barrel.Current.Get<T>(url);

    if (!forceRefresh && !Barrel.Current.IsExpired(url))
       return Barrel.Current.Get<T>(url);

    try
    {
        T result = await httpClient.GetFromJsonAsync<T>(url);
        Barrel.Current.Add(url, result, TimeSpan.FromDays(days));
        return result;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Unable to get information from server {ex}");
        //probably re-throw here :)
    }

    return default;
}

MonkeyCache will never delete data unless you want to, which is pretty nice incase you are offline for a long period of time. However, there are additional helpers to clean up data:

    //removes all data
    Barrel.Current.EmptyAll();
	
	//removes all expired data
    Barrel.Current.EmptyExpired();

    //param list of keys to flush
    Barrel.Current.Empty(key: url);

The above shows how you can integrate Monkey Cache into your existing source code without any modifications to your network code. However, MonkeyCache can help you there too! MonkeyCache also offers helpers when dealing with network calls via HttpCache.

HttpCache balances on top of the Barrel and offers helper methods to pass in a simple url that will handle adding and updating data into the Barrel based on the ETag if possible.

Task<IEnumerable<Monkey>> GetMonkeysAsync()
{
    var url = "http://montemagno.com/monkeys.json";

    //Dev handle online/offline scenario
   
	var result = await HttpCache.Current.GetCachedAsync(barrel, url, TimeSpan.FromSeconds(60), TimeSpan.FromDays(1));
    return JsonConvert.DeserializeObject<IEnumerable<Monkey>>(result);
}

Cache will always be stored in the default platform specific location:

Platform Location
Xamarin.iOS NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User)[0];
Xamarin.Mac NSSearchPath.GetDirectories(NSSearchPathDirectory.CachesDirectory, NSSearchPathDomain.User)[0];
Xamarin.Android Application.Context.CacheDir.AbsolutePath
Windows 10 UWP Windows.Storage.ApplicationData.Current.LocalFolder.Path
.NET Core Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
ASP.NET Core Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
.NET Framework Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)

Persisting Data Longer

Since the default is to use the Cache directories the platform can clean this up at any time. If you want to change the base path of where the data is stored you can call the following static method:

BarrelUtils.SetBaseCachePath("Path");

You MUST call this before initializing or accessing anything in the Barrel, and it can only ever be called once else it will throw an InvalidOperationException.

Json Serialization

MonkeyCache v2.0 and higher uses System.Text.Json to serialize objects to/from the backing store. By default, the default System.Text.Json serialization behavior is used. There are two options for controlling this serialization:

  1. Pass an optional JsonSerializationOptions instance to Barrel.Current.Add and Barrel.Current.Get.
  2. Pass a JsonTypeInfo<T> instance to Barrel.Current.Add and Barrel.Current.Get. You can get a JsonTypeInfo<T> instance by using the System.Text.Json source generator. See How to use source generation in System.Text.Json for more information.

No matter which option you choose, it is recommended to use the same option between Barrel.Current.Add and Barrel.Current.Get. If the options are inconsistent, the information going into the backing store may not be read properly when retrieving it back from the Barrel.

FAQ

Have questions? Open up an issue. Here are a few:

How does Monkey Cache differ from the Settings Plugin?

Great question. I would also first say to read through this: https://github.com/jamesmontemagno/SettingsPlugin#settings-plugin-or-xamarinforms-appproperties as it will compare it to app.properties.

So with the Settings Plugin it is storing properties to the users local preferences/settings api of each platform. This is great for simple data (bool, int, and small strings). Each platform has different limitations when it comes to these different types of data and strings especially should never house a large amount of data. In fact if you try to store a super huge string on Android you could easily get an exception.

Monkey Cache enables you to easily store any type of data or just a simple string that you can easily serialize and deserialize back and forth. The key here is that you can set an expiration data associated with that data. So you can say this data should be used for the next few days. A key here is the ETag that is extra data that can be used to help with http caching and is used in the http caching library.

Isn't this just Akavache?

Akavache offers up a great and super fast asynchronous, persistent key-value store that is based on SQLite and Reactive Extensions. I love me some Akavache and works great for applications, but wasn't exactly what I was looking for in a data caching library. Akavache offers up a lot of different features and really cool Reactive type of programming, but Monkey Cache focuses in on trying to create a drop dead simple API with a focus on data expiration. My goal was also to minimize dependencies on the NuGet package, which is why Monkey Cache offers a SQLite, LiteDB, or a simple FileStore implementation for use.

How about the link settings?

You may need to --linkskip=SQLite-net or other libraries.

Where Can I Learn More?

Listen to our podcast Merge Conflict: Episode 76 for an overview of Monkey Cache and it's creation.

License

Under MIT (see license file)

Want To Support This Project?

All I have ever asked is to be active by submitting bugs, features, and sending those pull requests down! Want to go further? Make sure to subscribe to my weekly development podcast Merge Conflict, where I talk all about awesome Xamarin goodies and you can optionally support the show by becoming a supporter on Patreon.

More Repositories

1

Xamarin.Plugins

Cross-platform Native API Access from Shared Code!
1,302
star
2

MediaPlugin

Take & Pick Photos and Video Plugin for Xamarin and Windows
C#
713
star
3

mvvm-helpers

Collection of MVVM helper classes for any application
C#
673
star
4

Hanselman.Forms

The most awesome Hanselman app
C#
671
star
5

InAppBillingPlugin

Cross-platform In App Billing Plugin for .NET
C#
630
star
6

SettingsPlugin

Read and Write Settings Plugin for Xamarin and Windows
C#
325
star
7

GeolocatorPlugin

Geolocation plugin for Xamarin and Windows
C#
293
star
8

PermissionsPlugin

Check and Request Permissions Plugin for Xamarin and Windows
C#
282
star
9

ConnectivityPlugin

Connectivity Plugin for Xamarin and Windows
C#
262
star
10

ImageCirclePlugin

Circle Images for your Xamarin.Forms Applications
C#
240
star
11

Xamarin.Forms-PullToRefreshLayout

Pull To Refresh a ScrollView or ListView in Xamarin.Forms
C#
222
star
12

StoreReviewPlugin

Request app store reviews across Xamarin and Windows applications
C#
183
star
13

MyCoffeeApp

Sample Xamarin.Forms app built live on in 101 series on YouTube
C#
153
star
14

MeetupManager

Meetup.com app to track users at events
C#
149
star
15

DeviceInfoPlugin

Device Information Plugin for Xamarin and Windows
C#
143
star
16

app-ac-islandtracker

Animal Crossing Island Tracking Mobile App
C#
135
star
17

Xamarin-Templates

Xamarin.Android Templates Pack
C#
130
star
18

xamarin.forms-toolkit

Toolkit for Xamarin.Forms (Controls, Behaviors, and Converters)
C#
128
star
19

Xam.NavDrawer

Navigation Drawer Sample + MvvmCross Sample for Xamarin.Android
C#
123
star
20

Xamarin.Forms-Awesome-Controls

Awesome controls to add to your Xamarin.Forms apps
C#
121
star
21

XamChat

SignalR Chat Xamarin App
C#
120
star
22

CurrentActivityPlugin

Always grab the current Activity of your Xamarin.Android app!
C#
115
star
23

Xamarin.Forms-Monkeys

Simple list of monkeys (master/detail) in a xamarin.forms application
C#
115
star
24

MyWeather.Forms

Xamarin.Forms Weather Demo using OpenWeatherMap
C#
110
star
25

app-monkeychat

Monkey Chat application feature Twilio IP Messaging
C#
109
star
26

MyStreamTimer

A cool app to count up or down that writes text to file for streamers
C#
99
star
27

FloatingActionButton-for-Xamarin.Android

FAB material design for Xamarin.Android
C#
91
star
28

PagerSlidingTabStrip-for-Xamarin.Android

Port of Pager Sliding Tab Strip for Xamarin.Android Material Design
C#
85
star
29

app-coffeecups

Coffee Consumption App built with Xamarin.Forms and Azure Mobile Apps
C#
82
star
30

vsts-mobile-tasks

VSTS Tasks for Mobile!
TypeScript
79
star
31

MonoDroidToolkit

A toolkit for Xamarin.Android providing a lot of awesome helpers
C#
71
star
32

TextToSpeechPlugin

Text to Speech Plugin for Xamarin and Windows
C#
62
star
33

MotzCodesLive

Sample Resources for Motz Codes Live on Twitch
C#
60
star
34

AndroidStreamingAudio

Sample of streaming audio in background service in Xamarin.Android
C#
57
star
35

MyExpenses

My Expenses Cross Platform Demo - VSToolBox
C#
54
star
36

app-pretty-weather

A very pretty weather application built with Xamarin :)
C#
54
star
37

app-essentials

Sample project highlighting Xamarin.Essentials
C#
53
star
38

AllExtensions-DI-IoC

C#
52
star
39

xamarin.forms-workshop

Xamarin.Forms Full Day Workshop
C#
49
star
40

LaunchMapsPlugin

Launch External Maps Plugin for Xamarin and Windows
C#
48
star
41

MauiApp-DI

C#
46
star
42

VibratePlugin

Vibrate Plugin for Windows and Xamarin
C#
45
star
43

TheXamarinShow

All source code from my show on Channel 9, The Xamarin Show!
C#
45
star
44

app-imagesearch-cogs

Image Search and Cognitive Service Xamarin app!
C#
45
star
45

MVVMSourceGenerators

C#
44
star
46

Coffee-Filter

Find Coffee Fast with this Xamarin.Android App
C#
43
star
47

VS2019-FirstXamarinApp

C#
40
star
48

app-myconference

Conference App Build with .NET MAUI
C#
40
star
49

BikeNow

Bike Now is the best way to enjoy Seattle's bike sharing system on Android
C#
39
star
50

MonkeysApp-Workshop

Xamarn.Forms Workshop sample monkey app for iOS, Android, and Windows
C#
39
star
51

Censored

A .NET Profanity Censoring Library
C#
38
star
52

work-from-home-setup

Equipment and Setup recommended for Work From Home
37
star
53

app-peloton

Peloton app clone built with Xamarin.Forms
C#
35
star
54

dotnet-conferences

A comprehensive community built list of .NET Conferences around the world!
34
star
55

app-compass

Creating a simple compass application with Xamarin.Forms and Xamarin.Essentials.
C#
32
star
56

CircleImageView-Xamarin.Android

A fast circle image for Xamarin.Android
C#
32
star
57

Xamarin.Forms-PullToRefreshListView

Implementation of pull to refresh for Xamarin.Forms ListView
C#
31
star
58

Mvx.Plugins.Settings

Settings plug-in for MvvmCross.
C#
30
star
59

app-SimpleSignalR

Xamarin app to listen to new items from SignalR and ASP.NET Core
C#
30
star
60

mycadence-arduino

With this DIY project and a simple $18 ESP32 Arduino board you will have a budget Cadence display for your indoor cycling bike for Peloton or Apple Fitness+
C++
29
star
61

PlanetXamarin

Planet Xamarin
C#
28
star
62

BatteryPlugin

Battery Plugin for Xamarin and Windows
C#
27
star
63

iBeaconsEverywhere

iBeacon example on iOS and Android
C#
26
star
64

app-monkeys

C#
25
star
65

LocalizationSample

C#
25
star
66

GifImageView-Xamarin.Android

Animated ImageView for your Xamarin.Android apps
C#
25
star
67

ContactsPlugin

Contacts Plugin For Xamarin and Windows
C#
24
star
68

plugin-template

Plugin for .NET Template
C#
23
star
69

xamarin-workshop

Xamarin workshops for building a Xamarin.Android and Xamarin.Forms App
C#
19
star
70

app-ocr-functions

Cognitive Services, Azure Functions, Azure Mobile Apps, and Xamarin
C#
19
star
71

MyStocks.Forms

Xamarin.Forms example of querying stock quotes and using text to speech apis.
C#
18
star
72

AirQualityApps

C#
18
star
73

Xamarin.Forms-Android-CustomProgressBar

Using a custom renderer to display and bind to my custom progress bar
C#
18
star
74

build2017-future-of-mobile

Live Player Demos from Future of Mobile at Build 2017
C#
18
star
75

XamDroid.StickyListHeaders

Xamarin.Android Port of StickyListHeaders
C#
17
star
76

FiveLetters

A clone of a clone of Wordle built with .NET MAUI
C#
17
star
77

BetterTogether

Blazor, ASP.NET Core, Xamarin, .NET Standard <3
C#
16
star
78

XamarinDNR

Dot Net Rocks, PCL, Azure!
C#
16
star
79

FrenchPressTimer

Cross Platform timer that counts down from 4 minutes
C#
16
star
80

forms-native-embedding

Xamarin.Forms Native Embedding Sample
C#
16
star
81

embeddinator-weather

C#
15
star
82

Covid19Stats

Desktop app to retrieve COVID-19 Stats and download them to files on disk for OBS/SLOBS with a timer :)
C#
14
star
83

PuppyKittyOverflow

PuppyKittyOverflow
C#
14
star
84

Jeffsum.NET

Jeff Goldblum text placeholder generator of pure amazingness. (Unofficial .NET version of Jeffsum.com by @seanehalpin)
C#
13
star
85

MyFirstOouiApp

C#
13
star
86

MarshmallowSamples

Get ready for Android 6.0 with these Marshmallow Samples
C#
13
star
87

Xamarin.Android-AppCompat

App compat for android
C#
13
star
88

ToolkitMessenger

Esample of .NET Toolkit Messenger
C#
13
star
89

build2021-intro-csharp-python

C# and Python are two of the most popular programming languages for developers in all areas of tech. From making web apps to doing machine learning, you can't go wrong with either of them! James and Christopher are here to introduce you to these two powerful languages, explore some โ€œHello, Worldโ€ examples, and show you the docs, tools, and frameworks that can help students and beginners get started on coding today!
Jupyter Notebook
13
star
90

blog-samples

All code samples from http://motzcod.es and http://blog.xamarin.com
C#
12
star
91

jamesmontemagno

12
star
92

XamDroid.RobotoText

Roboto text everywhere!
C#
12
star
93

dotnet-maui-template

Default template idea for .NET MAUI
C#
12
star
94

app-tictactoe

A Xamarin.Forms Tic-Tac-Toe example
C#
12
star
95

embeddinator-hellosharedui

C#
11
star
96

OfficeLightControl

Workshop for building an office light switch app with IFTTT and Hues
C#
11
star
97

FormsAnimations

Sample application shown during the Xamarin.Forms webinar for animations.
C#
11
star
98

MonkeyFinder6000

C#
10
star
99

app-simplestocks

C#
10
star
100

MonkeyApi

C#
10
star