Skip to content

Add ability to save context to streams #95

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion BunqSdk.Tests/Context/ApiContextTest.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Bunq.Sdk.Context;
using System.IO;
using Bunq.Sdk.Context;
using Xunit;

namespace Bunq.Sdk.Tests.Context
Expand Down Expand Up @@ -45,5 +46,22 @@ public void TestApiContextSaveRestore()

Assert.Equal(apiContextJson, apiContextRestored.ToJson());
}

/// <summary>
/// Tests saving and restoring of the API context.
/// </summary>
[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());
}
}
}
34 changes: 33 additions & 1 deletion BunqSdk/Context/ApiContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ public bool IsSessionActive()
{
return false;
}

var timeToExpiry = SessionContext.ExpiryTime.Subtract(DateTime.Now);
var timeToExpiryMinimum = new TimeSpan(
TIME_UNIT_COUNT_NONE,
Expand Down Expand Up @@ -222,6 +222,22 @@ public void Save(string fileName)
}
}

/// <summary>
/// Save a JSON representation of the API Context to a given writer.
/// </summary>
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);
}
}

/// <summary>
/// Serialize the API Context to JSON.
/// </summary>
Expand Down Expand Up @@ -253,6 +269,22 @@ public static ApiContext Restore(string fileName)
}
}

/// <summary>
/// Restores a context from a given reader.
/// </summary>
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);
}
}

/// <summary>
/// De-serializes a context from JSON.
/// </summary>
Expand Down