// --------------------------------------------------------------------------------------------------------------------
//
// Copyright (c) 2020 All rights reserved.
//
//
// The JSON server storage.
//
// --------------------------------------------------------------------------------------------------------------------
namespace MQTTnet.TestApp.WinForm
{
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using MQTTnet.Server;
using Newtonsoft.Json;
///
///
/// The JSON server storage.
///
///
public class JsonServerStorage : IMqttServerStorage
{
///
/// The file name.
///
private readonly string filename = Path.Combine(Directory.GetCurrentDirectory(), "Retained.json");
///
/// Clears the file.
///
public void Clear()
{
if (File.Exists(this.filename))
{
File.Delete(this.filename);
}
}
///
///
/// Loads the retained messages.
///
/// A of .
///
public async Task> LoadRetainedMessagesAsync()
{
await Task.CompletedTask;
if (!File.Exists(this.filename))
{
return new List();
}
try
{
var json = await File.ReadAllTextAsync(this.filename);
return JsonConvert.DeserializeObject>(json);
}
catch
{
return new List();
}
}
///
///
/// Saves the retained messages to a file.
///
/// The messages.
/// A representing any asynchronous operation.
///
public async Task SaveRetainedMessagesAsync(IList messages)
{
await Task.CompletedTask;
var json = JsonConvert.SerializeObject(messages);
await File.WriteAllTextAsync(this.filename, json);
}
}
}