public async Task Persist(string streamtype, string id, IEnumerable<ISourcedEvent> pendingEvents) { Trace.TraceInformation("Preparing batch for stream {0}.", streamtype); var batch = new TableBatchOperation(); foreach (var @event in pendingEvents) { var entity = new DictionaryTableEntity { PartitionKey = streamtype, RowKey = id + "_" + @event.Version.ToString(VersionKeyFormat) }; var compressed = false; var body = Json.Encode(@event); if (body.Length > 32*1024) { body = new GzipCompression().Compress(body); compressed = true; } entity.Add("EventType", @event.GetType().FullName); entity.Add("SourceId", @event.SourceId); entity.Add("Version", @event.Version); entity.Add("Body", body); entity.Add("Compressed", compressed); batch.Add(TableOperation.Insert(entity)); } Trace.TraceInformation("Executing batch on stream {0}.", streamtype); await _table.ExecuteBatchAsync(batch).ContinueWith(r => { Trace.TraceInformation("Batch on stream {0} complete {1} exceptions.", streamtype, r.Exception != null ? "with" : "without"); if (r.Exception != null) { r.Exception.Handle(exception => { Trace.TraceError(exception.ToString()); return true; }); } }); }
private async Task<IEnumerable<ISourcedEvent>> LoadEvents(TableQuery<DictionaryTableEntity> query) { var events = new List<ISourcedEvent>(); TableQuerySegment<DictionaryTableEntity> querySegment = null; var entities = new List<DictionaryTableEntity>(); while (querySegment == null || querySegment.ContinuationToken != null) { querySegment = await _table.ExecuteQuerySegmentedAsync(query, querySegment != null ? querySegment.ContinuationToken : null); entities.AddRange(querySegment); } foreach (var entity in entities) { var eventType = GetType(entity["EventType"].StringValue); if (eventType == null) continue; var body = entity["Body"].StringValue; if (entity.ContainsKey("Compressed") && entity["Compressed"].BooleanValue.HasValue && entity["Compressed"].BooleanValue.Value) { body = new GzipCompression().Uncompress(body); } var @event = Json.Decode(body, eventType) as ISourcedEvent; if (@event != null) { events.Add(@event); } } return events; }