internal static ISnapshotProvider GetProvider(ISnapshot sn) { Console.WriteLine(">>>>>>>>>>>>>>>>>>>>> snapshot type to string='" + sn.GetType().ToString()); switch (sn.GetType().ToString().Substring(sn.GetType().ToString().LastIndexOf('.') + 1)) { case "VSSSnapshot": return((ISnapshotProvider) new VSSProvider()); default: return((ISnapshotProvider) new NullProvider()); } }
/// <summary> /// Creates the snapshot data object from the aggregate root. /// </summary> /// <param name="aggregateRoot">The aggregate root for which the snapshot is being created.</param> /// <returns>The snapshot data object.</returns> public static SnapshotDataObject CreateFromAggregateRoot(ISourcedAggregateRoot aggregateRoot) { ISnapshotSerializer serializer = null; string eventSerializerTypeName = ConfigurationManager.AppSettings["napshotSerializer"]; if (eventSerializerTypeName == null) { serializer = new SnapshotXmlSerializer(); } else { Type serializerType = Type.GetType(eventSerializerTypeName); if (serializerType == null) { throw new InfrastructureException("The serializer defined by type '{0}' doesn't exist.", eventSerializerTypeName); } serializer = (ISnapshotSerializer)Activator.CreateInstance(serializerType); } ISnapshot snapshot = aggregateRoot.CreateSnapshot(); return(new SnapshotDataObject { AggregateRootId = aggregateRoot.Id, AggregateRootType = aggregateRoot.GetType().AssemblyQualifiedName, Version = aggregateRoot.Version, SnapshotType = snapshot.GetType().AssemblyQualifiedName, Timestamp = snapshot.Timestamp, SnapshotData = serializer.Serialize(snapshot) }); }
private bool AggregateRootSupportsSnapshot(Type aggType, ISnapshot snapshot) { var memType = GetSnapshotInterfaceType(aggType); var snapshotType = snapshot.GetType(); var expectedType = typeof(ISnapshotable <>).MakeGenericType(snapshotType); return(memType == expectedType); }
/// <summary> /// Creates a new instance of <see cref="SnapshotDescriptor"/> /// </summary> /// <param name="aggregateType">The full CLR name of the aggregate root</param> /// <param name="aggregateId">The id of the aggregate root</param> /// <param name="snapshot">The snapshot</param> public SnapshotDescriptor(string aggregateType, Guid aggregateId, ISnapshot snapshot) { this.AggregateType = aggregateType; this.AggregateId = aggregateId; this.Version = snapshot.Version; this.Timestamp = DateTime.Now; this.SnapshotType = snapshot.GetType().FullName; this.Snapshot = snapshot; }
private static void WriteSnapshotTest(ISnapshot source, string path, string jsonData) { try { source.EventSourceId.GetWriteLock("snapshot"); File.WriteAllText(path, source.GetType().AssemblyQualifiedName + "\n\r" + jsonData); } finally { source.EventSourceId.ReleaseWriteLock("snapshot"); } }
public SaveResult Save(ISnapshot instance) { var snapshot = new AggregateSnapshot { Identity = instance.Identity, Version = instance.Version, SnapshotType = AggregateRootBase.GetAggregateTypeDescriptor(instance.GetType()), ObjectData = this.serializer.SerializeToString(instance), }; return(base.Save(snapshot)); }
private SnapshotEntity CreateFromEventSourced(T eventSourced) { ISnapshot snapshot = eventSourced.CreateSnapshot(); return(new SnapshotEntity { AggregateId = eventSourced.Id, AggregateType = eventSourced.GetType().Name, Version = eventSourced.Version, SnapshotType = snapshot.GetType().AssemblyQualifiedName, Timestamp = DateTimeOffset.Now, SnapshotData = serializer.Serialize <string>(snapshot) }); }
/// <summary> /// Creates and returns a descriptor for the specified snapshot. /// </summary> /// <param name="snapshot">The <see cref="ISnapshot{TKey}">snapshot</see> to create a descriptor for.</param> /// <returns>A new <see cref="SqlSnapshotDescriptor{TKey}">snapshot descriptor</see>.</returns> protected virtual SqlSnapshotDescriptor <TKey> CreateDescriptor(ISnapshot <TKey> snapshot) { Arg.NotNull(snapshot, nameof(snapshot)); Contract.Ensures(Contract.Result <SqlSnapshotDescriptor <TKey> >() != null); var type = snapshot.GetType().GetTypeInfo(); if (!(snapshot is IEvent @event)) { throw new ArgumentException(SR.SnapshotMustAlsoBeEvent.FormatDefault(GetType().Name, type.Name)); } return(new SqlSnapshotDescriptor <TKey>() { AggregateId = snapshot.Id, SnapshotType = type.GetAssemblyQualifiedName(), Snapshot = Configuration.EventSerializer.Serialize(@event), Version = snapshot.Version, }); }
public void SaveSnapshot(ISnapshot snapshot) { if (!_storage.ContainsKey(snapshot.Id)) { _storage[snapshot.Id] = new SnasphotDescriptor { Data = JsonConvert.SerializeObject(snapshot), Id = snapshot.Id, Version = snapshot.Version, Type = snapshot.GetType().Name }; } else { if (_storage[snapshot.Id].Version < snapshot.Version) { _storage[snapshot.Id].Data = JsonConvert.SerializeObject(snapshot); _storage[snapshot.Id].Version = snapshot.Version; } } }
/// <summary> /// Saves a snapshot of the specified event source. /// </summary> public void SaveShapshot(ISnapshot snapshot) { using (var connection = new SqlConnection(_connectionString)) { // Open connection and begin a transaction so we can // commit or rollback all the changes that has been made. connection.Open(); using (SqlTransaction transaction = connection.BeginTransaction()) { try { using (var dataStream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(dataStream, snapshot); byte[] data = dataStream.ToArray(); using (var command = new SqlCommand(Queries.InsertSnapshot, transaction.Connection)) { command.Transaction = transaction; command.Parameters.AddWithValue("EventSourceId", snapshot.EventSourceId); command.Parameters.AddWithValue("Version", snapshot.EventSourceVersion); command.Parameters.AddWithValue("Type", snapshot.GetType().AssemblyQualifiedName); command.Parameters.AddWithValue("Data", data); command.ExecuteNonQuery(); } } // Everything is handled, commint transaction. transaction.Commit(); } catch { // Something went wrong, rollback transaction. transaction.Rollback(); throw; } } } }
public void Play(ISnapshot snapshot) { if (!Replaying) { return; } if (snapshot is AnimationSnapshot animation) { m_Animator.SetTrigger(snapshot.As <AnimationSnapshot>().Trigger); } else if (snapshot is CoinSnapshot coin) { Debug.Log($"{DateTime.Now.ToShortTimeString()}: playin"); var instance = Instantiate(objectToSpawn, coin.Position, coin.Quaternion); instance.GetComponentInChildren <Animator>().SetBool("forward", coin.Forward); } else { throw new Exception($"Unknown snapshot type: {snapshot.GetType()}"); } }
/// <summary> /// Creates the snapshot data object from the aggregate root. /// </summary> /// <param name="aggregateRoot">The aggregate root for which the snapshot is being created.</param> /// <returns>The snapshot data object.</returns> public static SnapshotDataObject CreateFromAggregateRoot(ISourcedAggregateRoot aggregateRoot) { ISnapshotSerializer serializer = null; ApworksConfigSection config = AppRuntime.Instance.CurrentApplication.ConfigSource.Config; if (config.Serializers == null || config.Serializers.SnapshotSerializer == null || string.IsNullOrEmpty(config.Serializers.SnapshotSerializer.Provider) || string.IsNullOrWhiteSpace(config.Serializers.SnapshotSerializer.Provider)) { serializer = new SnapshotXmlSerializer(); } else { string typeName = config.Serializers.SnapshotSerializer.Provider; Type serializerType = Type.GetType(typeName); if (serializerType == null) { throw new InfrastructureException("The serializer defined by type '{0}' doesn't exist.", typeName); } serializer = (ISnapshotSerializer)Activator.CreateInstance(serializerType); } ISnapshot snapshot = aggregateRoot.CreateSnapshot(); return(new SnapshotDataObject { AggregateRootID = aggregateRoot.ID, AggregateRootType = aggregateRoot.GetType().AssemblyQualifiedName, Version = aggregateRoot.Version, Branch = Constants.ApplicationRuntime.DefaultBranch, SnapshotType = snapshot.GetType().AssemblyQualifiedName, Timestamp = snapshot.Timestamp, SnapshotData = serializer.Serialize(snapshot) }); }
/// <summary> /// Saves a snapshot of the specified event source. /// </summary> public void SaveShapshot(ISnapshot snapshot) { using (var connection = new SqlConnection(_connectionString)) { // Open connection and begin a transaction so we can // commit or rollback all the changes that has been made. connection.Open(); using (SqlTransaction transaction = connection.BeginTransaction()) { try { using (var dataStream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(dataStream, snapshot); byte[] data = dataStream.ToArray(); using (var command = new SqlCommand(InsertSnapshot, transaction.Connection)) { command.Transaction = transaction; command.Parameters.AddWithValue("EventSourceId", snapshot.EventSourceId); command.Parameters.AddWithValue("Version", snapshot.EventSourceVersion); command.Parameters.AddWithValue("SnapshotType", snapshot.GetType().AssemblyQualifiedName); command.Parameters.AddWithValue("SnapshotData", data); command.ExecuteNonQuery(); } } // Everything is handled, commint transaction. transaction.Commit(); } catch { // Something went wrong, rollback transaction. transaction.Rollback(); throw; } } } }
ProjectionStream LoadProjectionStream(Type projectionType, ProjectionVersion projectionVersion, IBlobId projectionId, ISnapshot snapshot) { ISnapshot currentSnapshot = snapshot; string contractId = projectionVersion.ProjectionContractId; List <ProjectionCommit> projectionCommits = new List <ProjectionCommit>(); int snapshotMarker = snapshot.Revision; while (true) { snapshotMarker++; var loadedCommits = projectionStore.Load(projectionVersion, projectionId, snapshotMarker).ToList(); if (loadedCommits.Count > 1000) { log.Warn($"Potential memory leak. The system will be down fairly soon. The projection `{contractId}` for id={projectionId} loads a lot of projection commits ({loadedCommits.Count}) and snapshot `{snapshot.GetType().Name}` which puts a lot of CPU and RAM pressure. You can resolve this by enabling the Snapshots feature in the host which handles projection WRITES and READS using `.UseSnapshots(...)`."); } projectionCommits.AddRange(loadedCommits); bool isSnapshotable = typeof(IAmNotSnapshotable).IsAssignableFrom(projectionType) == false; if (isSnapshotable && snapshotStrategy.ShouldCreateSnapshot(projectionCommits, snapshot.Revision)) { ProjectionStream checkpointStream = new ProjectionStream(projectionId, projectionCommits, currentSnapshot); var projectionState = checkpointStream.RestoreFromHistory(projectionType).Projection.State; ISnapshot newSnapshot = new Snapshot(projectionId, contractId, projectionState, snapshot.Revision + 1); snapshotStore.Save(newSnapshot, projectionVersion); currentSnapshot = newSnapshot; projectionCommits.Clear(); } else if (loadedCommits.Count() < snapshotStrategy.EventsInSnapshot) { break; } } ProjectionStream stream = new ProjectionStream(projectionId, projectionCommits, currentSnapshot); return(stream); }
async Task <ProjectionStream> LoadProjectionStreamAsync(Type projectionType, ProjectionVersion version, IBlobId projectionId, ISnapshot snapshot) { Func <ISnapshot> loadSnapshot = () => snapshot; List <ProjectionCommit> projectionCommits = new List <ProjectionCommit>(); int snapshotMarker = snapshot.Revision; while (true) { snapshotMarker++; IEnumerable <ProjectionCommit> loadedProjectionCommits = await projectionStore.LoadAsync(version, projectionId, snapshotMarker); List <ProjectionCommit> loadedCommits = loadedProjectionCommits.ToList(); projectionCommits.AddRange(loadedCommits); if (projectionType.IsSnapshotable() && snapshotStrategy.ShouldCreateSnapshot(projectionCommits, snapshot.Revision)) { ProjectionStream checkpointStream = new ProjectionStream(projectionId, projectionCommits, loadSnapshot); var projectionState = checkpointStream.RestoreFromHistory(projectionType).State; ISnapshot newSnapshot = new Snapshot(projectionId, version.ProjectionName, projectionState, snapshot.Revision + 1); snapshotStore.Save(newSnapshot, version); loadSnapshot = () => newSnapshot; projectionCommits.Clear(); log.Debug(() => $"Snapshot created for projection `{version.ProjectionName}` with id={projectionId} where ({loadedCommits.Count}) were zipped. Snapshot: `{snapshot.GetType().Name}`"); } if (loadedCommits.Count < snapshotStrategy.EventsInSnapshot) { break; } if (loadedCommits.Count > snapshotStrategy.EventsInSnapshot * 1.5) { log.Warn(() => $"Potential memory leak. The system will be down fairly soon. The projection `{version.ProjectionName}` with id={projectionId} loads a lot of projection commits ({loadedCommits.Count}) and snapshot `{snapshot.GetType().Name}` which puts a lot of CPU and RAM pressure. You can resolve this by configuring the snapshot settings`."); } } ProjectionStream stream = new ProjectionStream(projectionId, projectionCommits, loadSnapshot); return(stream); }
ProjectionStream LoadProjectionStream(Type projectionType, ProjectionVersion projectionVersion, IBlobId projectionId, ISnapshot snapshot) { if (ReferenceEquals(null, projectionVersion)) { throw new ArgumentNullException(nameof(projectionVersion)); } if (ReferenceEquals(null, projectionId)) { throw new ArgumentNullException(nameof(projectionId)); } if (ReferenceEquals(null, snapshot)) { throw new ArgumentNullException(nameof(snapshot)); } ISnapshot currentSnapshot = snapshot; string contractId = projectionVersion.ProjectionName; List <ProjectionCommit> projectionCommits = new List <ProjectionCommit>(); int snapshotMarker = snapshot.Revision; while (true) { snapshotMarker++; var loadedCommits = projectionStore.Load(projectionVersion, projectionId, snapshotMarker).ToList(); projectionCommits.AddRange(loadedCommits); bool isSnapshotable = typeof(IAmNotSnapshotable).IsAssignableFrom(projectionType) == false; if (isSnapshotable && snapshotStrategy.ShouldCreateSnapshot(projectionCommits, snapshot.Revision)) { ProjectionStream checkpointStream = new ProjectionStream(projectionId, projectionCommits, currentSnapshot); var projectionState = checkpointStream.RestoreFromHistory(projectionType).Projection.State; ISnapshot newSnapshot = new Snapshot(projectionId, contractId, projectionState, snapshot.Revision + 1); snapshotStore.Save(newSnapshot, projectionVersion); currentSnapshot = newSnapshot; projectionCommits.Clear(); log.Debug(() => $"Snapshot created for projection `{contractId}` with id={projectionId} where ({loadedCommits.Count}) were zipped. Snapshot: `{snapshot.GetType().Name}`"); } else if (loadedCommits.Count() < snapshotStrategy.EventsInSnapshot) { break; } else { log.Warn($"Potential memory leak. The system will be down fairly soon. The projection `{contractId}` with id={projectionId} loads a lot of projection commits ({loadedCommits.Count}) and snapshot `{snapshot.GetType().Name}` which puts a lot of CPU and RAM pressure. You can resolve this by configuring the snapshot settings`."); } } ProjectionStream stream = new ProjectionStream(projectionId, projectionCommits, currentSnapshot); return(stream); }
public static bool IsImplement(ISnapshot snapshot) { return(snapshot != null && snapshot.GetType() == typeof(Snapshot)); }