-
Notifications
You must be signed in to change notification settings - Fork 64
/
S04_Write_to_stream.cs
96 lines (75 loc) · 3.06 KB
/
S04_Write_to_stream.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Streamstone;
namespace Example.Scenarios
{
public class S04_Write_to_stream : Scenario
{
public override void Run()
{
WriteToExistingOrCreateNewStream();
WriteSequentiallyToExistingStream();
}
void WriteToExistingOrCreateNewStream()
{
var existent = Stream.TryOpen(Partition);
var stream = existent.Found
? existent.Stream
: new Stream(Partition);
Console.WriteLine("Writing to new stream in partition '{0}'", stream.Partition);
var result = Stream.Write(stream, new[]
{
Event(new InventoryItemCreated(Id, "iPhone6")),
Event(new InventoryItemCheckedIn(Id, 100)),
});
Console.WriteLine("Succesfully written to new stream.\r\nEtag: {0}, Version: {1}",
result.Stream.ETag, result.Stream.Version);
}
void WriteSequentiallyToExistingStream()
{
var stream = Stream.Open(Partition);
Console.WriteLine("Writing sequentially to existing stream in partition '{0}'", stream.Partition);
Console.WriteLine("Etag: {0}, Version: {1}", stream.ETag, stream.Version);
for (int i = 1; i <= 10; i++)
{
var result = Stream.Write(stream, new[]
{
Event(new InventoryItemCheckedIn(Id, i*100)),
});
Console.WriteLine("Succesfully written event '{0}' under version '{1}'",
result.Events[0].Id, result.Events[0].Version);
Console.WriteLine("Etag: {0}, Version: {1}",
result.Stream.ETag, result.Stream.Version);
stream = result.Stream;
}
}
static EventData Event(object e)
{
var id = Guid.NewGuid();
var properties = new
{
Id = id, // id that you specify for Event ctor is used only for duplicate event detection
Type = e.GetType().Name, // you can include any number of custom properties along with event
Data = JSON(e), // you're free to choose any name you like for data property
Bin = BSON(e) // and any storage format: binary, string, whatever (any EdmType)
};
return new EventData(id.ToString("D"), EventProperties.From(properties));
}
static string JSON(object data)
{
return JsonConvert.SerializeObject(data);
}
static byte[] BSON(object data)
{
var stream = new System.IO.MemoryStream();
using (var writer = new BsonWriter(stream))
{
var serializer = new JsonSerializer();
serializer.Serialize(writer, data);
}
return stream.ToArray();
}
}
}