diff --git a/BunqSdk.Tests/Context/ApiContextTest.cs b/BunqSdk.Tests/Context/ApiContextTest.cs index 521adc8..fb2b145 100644 --- a/BunqSdk.Tests/Context/ApiContextTest.cs +++ b/BunqSdk.Tests/Context/ApiContextTest.cs @@ -1,4 +1,5 @@ -using Bunq.Sdk.Context; +using System.IO; +using Bunq.Sdk.Context; using Xunit; namespace Bunq.Sdk.Tests.Context @@ -45,5 +46,22 @@ public void TestApiContextSaveRestore() Assert.Equal(apiContextJson, apiContextRestored.ToJson()); } + + /// + /// Tests saving and restoring of the API context. + /// + [Fact] + public void TestApiContextSaveRestoreReader() + { + var buffer = new MemoryStream(); + var apiContextJson = apiContext.ToJson(); + + apiContext.Save(buffer); + + buffer.Seek(0, SeekOrigin.Begin); + var apiContextRestored = ApiContext.Restore(buffer); + + Assert.Equal(apiContextJson, apiContextRestored.ToJson()); + } } } diff --git a/BunqSdk/Context/ApiContext.cs b/BunqSdk/Context/ApiContext.cs index adfbeb7..89f4163 100644 --- a/BunqSdk/Context/ApiContext.cs +++ b/BunqSdk/Context/ApiContext.cs @@ -188,7 +188,7 @@ public bool IsSessionActive() { return false; } - + var timeToExpiry = SessionContext.ExpiryTime.Subtract(DateTime.Now); var timeToExpiryMinimum = new TimeSpan( TIME_UNIT_COUNT_NONE, @@ -222,6 +222,22 @@ public void Save(string fileName) } } + /// + /// Save a JSON representation of the API Context to a given writer. + /// + public void Save(Stream stream) + { + try + { + var writer = new StreamWriter(stream, ENCODING_BUNQ_CONF); + writer.Write(ToJson()); + } + catch (IOException exception) + { + throw new BunqException(ERROR_COULD_NOT_SAVE_API_CONTEXT, exception); + } + } + /// /// Serialize the API Context to JSON. /// @@ -253,6 +269,22 @@ public static ApiContext Restore(string fileName) } } + /// + /// Restores a context from a given reader. + /// + public static ApiContext Restore(Stream stream) + { + try + { + var reader = new StreamReader(stream); + return FromJson(reader.ReadToEnd()); + } + catch (IOException exception) + { + throw new BunqException(ERROR_COULD_NOT_RESTORE_API_CONTEXT, exception); + } + } + /// /// De-serializes a context from JSON. ///