-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJournaledStreamExamples.cs
61 lines (54 loc) · 2.92 KB
/
JournaledStreamExamples.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
namespace MBW.Utilities.Journal.Tests;
public class JournaledStreamExamples
{
[Fact]
public void DemonstrateJournaledStreamUsage()
{
string filePath = Path.GetTempFileName();
string journalPath = filePath + ".journal";
try
{
// Create a file stream to work with
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// Wrap the file stream in a JournaledStream. This allows us to read and write to the stream without affecting the underlying file.
using (JournaledStream journalStream = JournaledStreamFactory.CreateWalJournal(fileStream, journalPath))
{
// Write data to the JournaledStream
// Note! Do not use the original FileStream directly, as this bypasses the Journal
string data = "Hello, Journaled World!";
journalStream.Write(System.Text.Encoding.UTF8.GetBytes(data));
// Commit the transaction, persisting the data to the file
// Alternatively, you can also call RollBack() to delete the journal and discard any changes
journalStream.Commit();
}
}
// At this point, the data has been written to the file and committed.
// At a later point, we can reopen the file and read the data using JournaledStream
using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
// Even though we will not write to the file, we still need to use the JournaledStream. This ensures
// that if our write was partial, we will replay the journal again to ensure it has been fully written.
using (JournaledStream journalStream = JournaledStreamFactory.CreateWalJournal(fileStream, journalPath))
{
// Read the data back from the JournaledStream
byte[] readBuffer = new byte[1024];
int bytesRead = journalStream.Read(readBuffer, 0, readBuffer.Length);
string readData = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytesRead);
Assert.Equal("Hello, Journaled World!", readData);
}
// Alternatively, we can ensure the journal has been applied, by using the utility
// After this utility has run, we know that any journal has either been applied fully or removed (if it wasn't committed by the original application)
JournaledUtilities.EnsureJournalCommitted(fileStream, journalPath);
}
}
finally
{
// Cleanup
if (File.Exists(filePath))
File.Delete(filePath);
if (File.Exists(journalPath))
File.Delete(journalPath);
}
}
}