public virtual void EnsurePropertyIsLoaded(object obj, IPropertyMap propertyMap) { IObjectManager om = this.Context.ObjectManager; IPersistenceEngine pe = this.Context.PersistenceEngine; ObjectStatus objStatus; PropertyStatus propStatus; objStatus = om.GetObjectStatus(obj); if (objStatus != ObjectStatus.Deleted) { if (objStatus == ObjectStatus.NotLoaded) { pe.LoadObject(ref obj); if (pe == null) { throw new ObjectNotFoundException("Object not found!"); // do not localize } } propStatus = om.GetPropertyStatus(obj, propertyMap.Name); if (propStatus == PropertyStatus.NotLoaded) { pe.LoadProperty(obj, propertyMap.Name); } } else { //We really ought to throw an exception here... } }
public SyncEngine(IPersistenceEngine engine, IPersistenceEngine metadataEngine, IPersistenceEngine secondaryMetadataEngine, string clientId, SyncProvider provider) : base(engine, provider) { this.metadataEngine = metadataEngine; this.secondaryMetadataEngine = secondaryMetadataEngine; this.clientId = clientId; }
protected virtual async Task InitializeAsync() { persistenceEngine = config.WriteModel.GetPersistenceEngine(); await persistenceEngine.InitializeAsync(); serializer = persistenceEngine.Serializer; }
public RemoteController() { #if DEBUG _Delegator = XmlConfigLoader.LoadXmlConfig("..\\..\\test.engines.config").CreatePersistenceEngine(); #else _Delegator = XmlConfigLoader.LoadXmlConfig("engines.config").CreatePersistenceEngine(); #endif System.Diagnostics.Trace.WriteLine("Persistence engine : " + _Delegator.ToString()); }
public ShoppingCartsController(IReadRepository readRepository, IEventRepository repository, ICheckpointPersister checkpointPersister, IPersistenceEngine engine) { this.readRepository = readRepository ?? throw new ArgumentNullException(nameof(readRepository)); this.repository = repository ?? throw new ArgumentNullException(nameof(repository)); this.checkpointPersister = checkpointPersister ?? throw new ArgumentNullException(nameof(checkpointPersister)); this.engine = engine; }
/// <summary> /// Initializes information about the last transaction number /// </summary> /// <param name="engine"></param> private void InitializeInfo(IPersistenceEngine engine) { Entity e = new Entity(SyncUtils.INFO); e.SetValue(SyncUtils.TRANSACTION, 0); e.SetValue(SyncUtils.CLIENTID, String.Empty); Transaction t = new Transaction(engine.Factory.Model); t.Serialize(e); t.Commit(engine, false); }
public CacheManager(string name, IPersistenceEngine engine = null, ICacheManager masterCache = null) { CacheName = name; _cacheInfraestructure = new MemoryCache(CacheName); _persistenceEngine = engine; IsSlaveCache = masterCache != null; _masterCache = masterCache; LoadInitialCacheContent(); }
public virtual IPersistenceEngine GetPersistenceEngine(ISourceMap sourceMap) { if (sourceMap == null) { throw new ArgumentException("sourceMap"); } IPersistenceEngine persistenceEngine = (IPersistenceEngine)dataSourcePersistenceEngines[sourceMap]; if (persistenceEngine == null) { persistenceEngine = GetPersistenceEngine(sourceMap.PersistenceType); } return(persistenceEngine); }
public virtual void InvalidateProperty(object obj, IPropertyMap propertyMap) { IObjectManager om = this.Context.ObjectManager; IPersistenceEngine pe = this.Context.PersistenceEngine; ObjectStatus objStatus; PropertyStatus propStatus; objStatus = om.GetObjectStatus(obj); propStatus = om.GetPropertyStatus(obj, propertyMap.Name); if (propStatus == PropertyStatus.NotLoaded) { RemoveOriginalValues(obj, propertyMap.Name); //pe.LoadProperty(obj, propertyMap.Name); } }
public CatchUpProjector( TState state, ICheckpointPersister checkpointPersister, IPersistenceEngine engine, IStorageResetter storageResetter, IObserverFactory observerFactory ) : base(state) { this.checkpointPersister = checkpointPersister ?? throw new ArgumentNullException(nameof(checkpointPersister)); this.storageResetter = storageResetter ?? throw new ArgumentNullException(nameof(storageResetter)); this.engine = engine ?? throw new ArgumentNullException(nameof(engine)); this.observerFactory = observerFactory ?? throw new ArgumentNullException(nameof(observerFactory)); projectorIdentifier = checkpointPersister.GetProjectorIdentifier(typeof(TState)); }
public virtual void InvalidateProperty(object obj, IPropertyMap propertyMap, bool invalidateDirty) { if (propertyMap.IsIdentity) { throw new NPersistException("Identity properties can not be invalidated! Property: " + AssemblyManager.GetBaseType(obj).Name + "." + propertyMap.Name, obj, propertyMap.Name); } IObjectManager om = this.Context.ObjectManager; IPersistenceEngine pe = this.Context.PersistenceEngine; PropertyStatus propStatus; propStatus = om.GetPropertyStatus(obj, propertyMap.Name); if (!(propStatus == PropertyStatus.Dirty && invalidateDirty == false)) { RemoveOriginalValues(obj, propertyMap.Name); } }
protected virtual void NullifyUniReferences(object obj, IClassMap classMap, IList classMapsWithUniRefs) { if (classMapsWithUniRefs.Count < 1) { return; } IDomainMap domainMap = this.Context.DomainMap; IPersistenceEngine pe = this.Context.PersistenceEngine; IAssemblyManager am = this.Context.AssemblyManager; foreach (IClassMap classMapWithUniRef in classMapsWithUniRefs) { Type classWithUniRef = am.GetTypeFromClassMap(classMapWithUniRef); IList objectsWithUniRefs = pe.GetObjectsOfClassWithUniReferencesToObject(classWithUniRef, obj); IList uniRefPropertyMaps = classMapWithUniRef.GetUniDirectionalReferencesTo(classMap, true); foreach (object test in objectsWithUniRefs) { IClassMap testClassMap = domainMap.MustGetClassMap(test.GetType()); NullifyUniReferencesInObject(obj, classMap, test, testClassMap, uniRefPropertyMaps); } } }
public EventRepository(IInstanceProvider instanceProvider, IPersistenceEngine persistenceEngine, IRawStreamEntryFactory rawStreamEntryFactory) { this.instanceProvider = instanceProvider; this.persistenceEngine = persistenceEngine; this.rawStreamEntryFactory = rawStreamEntryFactory; }
/// <summary> /// Synchronizes the specified client. /// </summary> /// <param name="client">The client.</param> /// <param name="server">The server.</param> /// <param name="syncDirection">The sync direction.</param> /// <param name="clientId">The client id.</param> public void Synchronize(IPersistenceEngine client, IPersistenceEngine server, SyncDirection syncDirection, string clientId) { switch (syncDirection) { case SyncDirection.FullDownload: FullDownload(client, server, true); break; case SyncDirection.FullDownloadNoBulk: FullDownload(client, server, false); break; case SyncDirection.SmartDownload: SmartDownload(client, server as SyncEngine, clientId); break; case SyncDirection.SmartUpload: SmartUpload(client as SyncEngine, server); break; case SyncDirection.SmartUploadDownload: SmartUploadDownload(client as SyncEngine, server as SyncEngine); break; } }
public ToManyIsNotNull(IPersistenceEngine engine) { this.engine = engine; }
public void Synchronize(IPersistenceEngine client, IPersistenceEngine server, SyncDirection syncDirection) { Synchronize(client, server, syncDirection, ((SyncEngine)client).ClientId); }
protected virtual void InsertCreated(object forObj, int exceptionLimit) { this.Context.LogManager.Debug(this, "Inserting objects that are up for creation", ""); // do not localize try { long cnt; int cntStale = 0; bool noCheck = false; IList stillDirty = new ArrayList(); ArrayList insertObjects = new ArrayList(); cnt = m_listCreated.Count; IObjectManager om = this.Context.ObjectManager; IPersistenceEngine pe = this.Context.PersistenceEngine; while (cnt > 0) { try { insertObjects.Clear(); foreach (object obj in m_listCreated) { try { if (forObj != null) { if (obj == forObj) { insertObjects.Add(obj); } } else { if (noCheck) { if (MayInsert(obj, true, true)) { insertObjects.Add(obj); noCheck = false; } } else { if (MayInsert(obj, true, false)) { insertObjects.Add(obj); } } } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } foreach (object obj in insertObjects) { //this should be the only necessary try block in this //method (and it ought only to be around the call to the //persistence engine, at that) but we add the other tries //to ensure that some exception from the framework doesn't //ruin the beautiful concept with collecting exceptions :-) try { m_listCreated.Remove(obj); m_listInserted.Add(obj); stillDirty.Clear(); pe.InsertObject(obj, stillDirty); om.SetObjectStatus(obj, ObjectStatus.Clean); this.Context.LogManager.Debug(this, "Inserted object", "Type: " + obj.GetType().ToString() + " Still dirty: " + stillDirty.ToString()); // do not localize if (stillDirty.Count > 0) { IList cloneList = new ArrayList(); foreach (object clone in stillDirty) { cloneList.Add(clone); } m_hashStillDirty[obj] = cloneList; } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } if (m_listCreated.Count == cnt) { noCheck = true; cntStale++; if (cntStale > 1) { throw new NPersistException("Cyclic dependency among objects up for creation could not be resolved!"); // do not localize } } else { cntStale = 0; noCheck = false; } if (forObj != null) { cnt = 0; } else { cnt = m_listCreated.Count; } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } }
//[DebuggerStepThrough()] protected virtual void DoNotifyPropertySet(object obj, string propertyName, ref object value, object oldValue, bool hasOldValue, ref bool cancel) { IContext ctx = this.Context; IObjectManager om = ctx.ObjectManager; IPersistenceEngine pe = ctx.PersistenceEngine; PropertyCancelEventArgs e; if (hasOldValue) { e = new PropertyCancelEventArgs(obj, propertyName, value, oldValue, this.Context.ObjectManager.GetNullValueStatus(obj, propertyName)); } else { e = new PropertyCancelEventArgs(obj, propertyName, value, this.Context.ObjectManager.GetPropertyValue(obj, propertyName), this.Context.ObjectManager.GetNullValueStatus(obj, propertyName)); } this.Context.EventManager.OnWritingProperty(this, e); if (e.Cancel) { cancel = true; return; } value = e.NewValue; IClassMap classMap = ctx.DomainMap.MustGetClassMap(obj.GetType()); IPropertyMap propertyMap; string prevId; string newId; propertyMap = classMap.MustGetPropertyMap(propertyName); if (propertyMap.ReferenceType != ReferenceType.None && value != null) { if (propertyMap.ReferenceType == ReferenceType.OneToMany || propertyMap.ReferenceType == ReferenceType.OneToOne) { //parent object IInterceptable ivalue = value as IInterceptable; if (ivalue == null) { throw new NPersistException(string.Format("Object is not a NPersist managed object, do not use 'new' on Entities. (Property='{0}', Owner={1})", propertyName, obj)); } else { if (ivalue.GetInterceptor().Context != this.Context) { throw new NPersistException(string.Format("Object does not belong to the same context object as the property owner. (Property='{0}', Owner={1})", propertyName, obj)); } ObjectStatus valueObjectStatus = om.GetObjectStatus(value); if (valueObjectStatus == ObjectStatus.UpForDeletion || valueObjectStatus == ObjectStatus.Deleted) { throw new DeletedObjectException(string.Format("Object has been deleted. (Object={0})", value), value); } } } else if (propertyMap.ReferenceType == ReferenceType.ManyToOne || propertyMap.ReferenceType == ReferenceType.ManyToMany) { IInterceptableList ivalue = value as IInterceptableList; if (ivalue == null) { throw new NPersistException(string.Format("List is not a NPersist managed list, do not use 'new' to initialize lists, NPersist does this for you. (Property='{0}', Owner={1})", propertyName, obj)); } else if (ivalue.Interceptable.GetInterceptor().Context != this.Context) { throw new NPersistException(string.Format("List does not belong to the same context object as the property owner. (Property='{0}', Owner={1})", propertyName, obj)); } } } if (propertyMap.IsReadOnly) { //Let read-only inverse properties through if (!(propertyMap.ReferenceType != ReferenceType.None && propertyMap.Inverse.Length > 0 && propertyMap.NoInverseManagement == false)) { //Special - if someone forgot to make their ManyOne read-only, //why bug them about it? (so don't add an "else" with an exception...) if (propertyMap.ReferenceType != ReferenceType.ManyToOne) { throw new ReadOnlyException("Property '" + classMap.Name + "." + propertyName + "' is read-only!"); // do not localize } } } PropertyStatus propStatus = PropertyStatus.Clean; ObjectStatus objStatus = om.GetObjectStatus(obj); bool hasPropertyStatus = false; if (objStatus == ObjectStatus.Deleted) { throw new DeletedObjectException("The object has been deleted!", obj, propertyName); // do not localize } else if (objStatus == ObjectStatus.UpForDeletion) { throw new DeletedObjectException("The object has been registered as up for deletion!", obj, propertyName); // do not localize } this.Context.ObjectCloner.EnsureIsClonedIfEditing(obj); if (objStatus == ObjectStatus.UpForCreation) { } else if (objStatus == ObjectStatus.Clean) { propStatus = om.GetPropertyStatus(obj, propertyName); if (propStatus == PropertyStatus.NotLoaded) { pe.LoadProperty(obj, propertyName); } if (!(hasOldValue)) { if (!(om.ComparePropertyValues(obj, propertyName, value, om.GetPropertyValue(obj, propertyName)))) { this.Context.UnitOfWork.RegisterDirty(obj); } } } else if (objStatus == ObjectStatus.NotLoaded) { propertyMap = this.Context.DomainMap.MustGetClassMap(obj.GetType()).MustGetPropertyMap(propertyName); if (!(propertyMap.IsIdentity)) { propStatus = this.Context.ObjectManager.GetPropertyStatus(obj, propertyName); hasPropertyStatus = true; //it would be sweet to be able to determine beforehand if this property would be part of the span //that is loaded with LoadObject and only call LoadObject if that is the case.... if (propStatus == PropertyStatus.NotLoaded) { hasPropertyStatus = false; //this.Context.PersistenceEngine.LoadObject(ref obj); this.Context.IdentityMap.LoadObject(ref obj, true); if (obj == null) { throw new ObjectNotFoundException("Object not found!"); // do not localize } } if (!hasPropertyStatus) { propStatus = om.GetPropertyStatus(obj, propertyName); } if (propStatus == PropertyStatus.NotLoaded) { pe.LoadProperty(obj, propertyName); } } if (!(hasOldValue)) { if (!(om.ComparePropertyValues(obj, propertyName, value, om.GetPropertyValue(obj, propertyName)))) { this.Context.UnitOfWork.RegisterDirty(obj); } } } else if (objStatus == ObjectStatus.Dirty) { propStatus = om.GetPropertyStatus(obj, propertyName); if (propStatus == PropertyStatus.NotLoaded) { pe.LoadProperty(obj, propertyName); } } if (propertyMap.IsIdentity) { prevId = om.GetObjectIdentity(obj); newId = om.GetObjectIdentity(obj, propertyMap, value); if (prevId != newId) { ctx.IdentityMap.UpdateIdentity(obj, prevId, newId); } } om.SetNullValueStatus(obj, propertyName, false); om.SetUpdatedStatus(obj, propertyName, true); if (hasOldValue) { ctx.InverseManager.NotifyPropertySet(obj, propertyName, value, oldValue); ctx.UnitOfWork.RegisterDirty(obj); } else { ctx.InverseManager.NotifyPropertySet(obj, propertyName, value); } }
public EntityPropertyGetter(IPersistenceEngine engine) { model = engine.Factory.Model; }
public async Task Initialize() { persistenceEngine = config.WriteModel.GetPersistenceEngine(); await persistenceEngine.InitializeAsync().ConfigureAwait(false); }
private void SmartDownload(IPersistenceEngine client, SyncEngine server, string clientId) { if (client == null) throw new ArgumentException("The client engine must be not null"); if (server == null) throw new ArgumentException("The server engine must be not null and a SyncProvider"); Entity connection = GetConnection(clientId, server); int lastSync = connection.GetInt32(SyncUtils.TRANSACTION); Command[] commands = OptimizeCommands((SyncEngine)client, GetPeerMetadataEngine(server, Peer.Server).Load("from Evaluant.Uss.Sync.Command c where (c.ClientId!='" + client + "' || c.ClientId==null) and c.Transaction>" + lastSync.ToString() + " orderby c.Processed, c.Number", 1, 0) ); StringCollection dataToProcess = new StringCollection(); foreach (string filter in filters) foreach (Entity e in server.Load(filter)) dataToProcess.Add(string.Concat(e.Type, SEPARATOR, e.Id)); Transaction t = new Transaction(client.Factory.Model); foreach (Command c in commands) { string key = string.Empty; CompoundCreateCommand ccc = c as CompoundCreateCommand; if (ccc != null) key = string.Concat(ccc.Type, SEPARATOR, ccc.ParentId); CompoundUpdateCommand cuc = c as CompoundUpdateCommand; if (cuc != null) key = string.Concat(cuc.ParentType, SEPARATOR, cuc.ParentId); if (key != null && key != string.Empty && filters.Count > 0 && !dataToProcess.Contains(key)) continue; c.IgnoreMetadata = true; t.PushCommand(c); } t.Commit(client, false); Entity info = GetPeerMetadataEngine(server, Peer.Server).Load(SyncUtils.INFO)[0]; connection[SyncUtils.TRANSACTION].Value = info.GetInt32(SyncUtils.TRANSACTION); IPersistenceEngine peerMetadataEngine = GetPeerMetadataEngine(server, Peer.Server); t = new Transaction(peerMetadataEngine.Factory.Model); t.Serialize(connection); t.Commit(peerMetadataEngine, false); }
protected virtual void RemoveDeleted(object forObj, int exceptionLimit) { this.Context.LogManager.Debug(this, "Removing objects that are up for deletion", ""); // do not localize try { long cnt; long staleCnt = 0; bool tryForce = false; ArrayList removeObjects = new ArrayList(); cnt = m_listDeleted.Count; IObjectManager om = this.Context.ObjectManager; IPersistenceEngine pe = this.Context.PersistenceEngine; while (cnt > 0) { try { removeObjects.Clear(); foreach (object obj in m_listDeleted) { try { if (forObj != null) { if (obj == forObj) { removeObjects.Add(obj); } } else { if (tryForce) { if (MayForceDelete(obj)) { //Force an update all the referencing objects, which should have had their //references to our object set to null in advance during the delete operation. //This way all the references to our object should be set to null in the database. TopologicalNode node = (TopologicalNode)m_topologicalDelete.Graph[obj]; if (node != null) { foreach (TopologicalNode waitForNode in node.WaitFor) { IList dummyStillDirty = new ArrayList(); pe.UpdateObject(waitForNode.Obj, dummyStillDirty); AddSpeciallyUpdated(waitForNode.Obj); } } tryForce = false; removeObjects.Add(obj); } } else { if (MayRemove(obj)) { removeObjects.Add(obj); } } } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } foreach (object obj in removeObjects) { try { m_listDeleted.Remove(obj); m_listRemoved.Add(obj); m_topologicalDelete.RemoveNode(obj); pe.RemoveObject(obj); this.Context.LogManager.Debug(this, "Removed object", ""); // do not localize } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } if (m_listDeleted.Count == cnt) { if (staleCnt > 0) { throw new UnitOfWorkException("The objects that are up for deletion in the unit of work are arranged in an unresolvable graph!"); } else { tryForce = true; staleCnt++; } } else { staleCnt = 0; } if (forObj != null) { cnt = 0; } else { cnt = m_listDeleted.Count; } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } }
protected virtual void UpdateStillDirty(object forObj, int exceptionLimit) { this.Context.LogManager.Debug(this, "Updating still dirty objects", ""); // do not localize try { long cnt; bool noCheck = false; ArrayList updateObjects = new ArrayList(); IList stillDirty; cnt = m_hashStillDirty.Count; IObjectManager om = this.Context.ObjectManager; IPersistenceEngine pe = this.Context.PersistenceEngine; while (cnt > 0) { try { updateObjects.Clear(); foreach (object obj in m_hashStillDirty.Keys) { try { if (forObj != null) { if (obj == forObj) { updateObjects.Add(obj); } } else { if (noCheck || MayUpdate(obj)) { updateObjects.Add(obj); noCheck = false; } } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } foreach (object obj in updateObjects) { try { stillDirty = (IList)m_hashStillDirty[obj]; m_hashStillDirty.Remove(obj); pe.UpdateObject(obj, stillDirty); this.Context.LogManager.Debug(this, "Updated still dirty object", "Type: " + obj.GetType().ToString() + " Still dirty: " + stillDirty.Count.ToString()); // do not localize if (stillDirty.Count > 0) { IList cloneList = new ArrayList(); foreach (object clone in stillDirty) { cloneList.Add(clone); } m_hashStillDirty[obj] = cloneList; } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } if (m_hashStillDirty.Count == cnt) { noCheck = true; } if (forObj != null) { cnt = 0; } else { cnt = m_hashStillDirty.Count; } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } } } catch (Exception ex) { if (exceptionLimit > 0 && exceptions.Count >= exceptionLimit - 1) { throw ex; } exceptions.Add(ex); } }
public virtual void SetPersistenceEngine(ISourceMap sourceMap, IPersistenceEngine persistenceEngine) { dataSourcePersistenceEngines[sourceMap] = persistenceEngine; persistenceEngine.Context = this.Context; }
public ObjectContext(ObjectService factory, IPersistenceEngine engine) : base(factory, engine) { Resolver = new AnonymousTypeResolver(new EntityResolver(this)); }
private void FullDownload(IPersistenceEngine client, IPersistenceEngine server, bool bulk) { if (client is SyncEngine) { ((SyncEngine)client).IgnoreClientMetadata = true; } // Contains id translation table Hashtable translationTable = new Hashtable(); Hashtable reverseTable = new Hashtable(); Transaction t = new Transaction(client.Factory.Model); StringCollection queries = new StringCollection(); // Creates the list of items to load depending whether filters are set or not if (filters.Count > 0) { queries = filters; } else { foreach (Model.Entity entity in server.Factory.Model.Entities.Values) { // Process only root types as it will load all children if (entity.Inherit != String.Empty && entity.Inherit != null && server.Factory.Model.Entities.ContainsKey(entity.Inherit)) continue; queries.Add("from " + entity.Type + " e select e"); } } if (Progressed != null) { // Returns opaths.Count * 2 so that half the processed is reached once entities are processed Progressed(this, new ProgressEventArgs(0, "Synchronization started", queries.Count * 2)); } int position = 0; // Import all entities foreach (string filter in queries) { if (Progressed != null) { // Returns opaths.Count * 2 so that half the processed is reached once entities are processed ProgressEventArgs args = new ProgressEventArgs(position++, "Processing " + filter, queries.Count * 2); Progressed(this, args); if (args.Cancel) { return; } } int count = Convert.ToInt32(server.LoadScalar(String.Concat("(", filter, ").Count()"))); // System.Diagnostics.Trace.WriteLine("Processing " + opaths + "(" + count.ToString() + ")"); // Loads a set of entities (span) if (count > 0) { t = new Transaction(client.Factory.Model); IList<Entity> entities = server.Load(filter); foreach (Entity e in entities) { e.State = State.New; t.Serialize(e); } t.Commit(client, false); // Retrieves the translated ids foreach (KeyValuePair<string, string> de in t.NewIds) { translationTable.Add(String.Concat(entities[0].Type, ".", de.Key), de.Value); reverseTable.Add(String.Concat(entities[0].Type, ".", de.Value), de.Key); } } } if (bulk) { t = new Transaction(client.Factory.Model); } position = 0; // Import all relationships foreach (Model.Entity entity in client.Factory.Model.Entities.Values) { if (Progressed != null) { ProgressEventArgs args = new ProgressEventArgs(queries.Count + position++, "Processing " + entity.Type + " relationships", queries.Count + client.Factory.Model.Entities.Count); Progressed(this, args); if (args.Cancel) { return; } } // Process only root types as it will load all children if (entity.Inherit != String.Empty && entity.Inherit != null) continue; foreach (Entity parent in client.Load(entity.Type)) { foreach (Model.Reference reference in server.Factory.Model.GetInheritedReferences(parent.Type)) { string uniqueParentKey = String.Concat(entity.Type, ".", parent.Id); string reversedParentId = reverseTable.Contains(uniqueParentKey) ? reverseTable[uniqueParentKey].ToString() : parent.Id; string query = String.Concat(entity.Type, "[id('", reversedParentId, "')].", reference.Name); int count = Convert.ToInt32(server.LoadScalar(String.Concat("count(", query, ")"))); // Loads a set of entities (span) if (count > 0) { if (!bulk) { t = new Transaction(client.Factory.Model); } IList<Entity> entities = server.Load(query); foreach (Entity e in entities) { string uniqueChildKey = String.Concat(e.Type, ".", e.Id); string childId = translationTable.Contains(uniqueChildKey) ? translationTable[uniqueChildKey].ToString() : e.Id; t.PushCommand(new Commands.CreateReferenceCommand(reference, parent, e)); } if (!bulk) { t.Commit(client, false); } } } } } if (bulk) { t.Commit(client, false); } // Creates a Connection token if the providers permit it if (client is SyncEngine && server is SyncEngine) { Entity connection = GetConnection(((SyncEngine)client).ClientId, (SyncEngine)server); Transaction it; Entity info = null; IPersistenceEngine engine = GetPeerMetadataEngine((SyncEngine)server, Peer.Server); IList<Entity> infos = engine.Load("from " + SyncUtils.INFO + "i select i"); if (infos.Count > 0) { info = infos[0]; } else { info = new Entity(SyncUtils.INFO); info.SetValue(SyncUtils.TRANSACTION, 0); info.SetValue(SyncUtils.CLIENTID, String.Empty); it = new Transaction(engine.Factory.Model); it.Serialize(info); it.Commit(engine, false); } connection.SetValue(SyncUtils.TRANSACTION, info.GetInt32(SyncUtils.TRANSACTION)); it = new Transaction(engine.Factory.Model); it.Serialize(connection); it.Commit(engine, false); ((SyncEngine)client).IgnoreClientMetadata = false; } }
/// <summary> /// Generates a TimeStamp like number representing an ordered transaction number /// </summary> /// <param name="metadataengine"></param> private void GenerateTransactionId(IPersistenceEngine engine) { Entity info; string guid; IList<Entity> es = engine.Load(SyncUtils.INFO); if (es.Count == 0) { InitializeInfo(engine); es = engine.Load(SyncUtils.INFO); } info = es[0]; guid = Guid.NewGuid().ToString(); do { lastTransactionId = info.GetInt32(SyncUtils.TRANSACTION); info.SetValue(SyncUtils.TRANSACTION, ++lastTransactionId); info.SetValue(SyncUtils.CLIENTID, guid); Transaction t = new Transaction(engine.Factory.Model); t.Serialize(info); t.Commit(engine, false); es = engine.Load(SyncUtils.INFO); if (es.Count == 0) { InitializeInfo(engine); es = engine.Load(SyncUtils.INFO); } info = es[0]; } while (info.GetInt32(SyncUtils.TRANSACTION) != lastTransactionId || info.GetString(SyncUtils.CLIENTID) != guid); }
public virtual void SetPersistenceEngine(ISourceMap sourceMap, IPersistenceEngine persistenceEngine) { dataSourcePersistenceEngines[sourceMap] = persistenceEngine ; persistenceEngine.Context = this.Context; }
public PollingObserverFactory(IPersistenceEngine persistenceEngine, TimeSpan defaultInterval = default) { this.persistenceEngine = persistenceEngine ?? throw new ArgumentNullException(nameof(persistenceEngine)); this.defaultInterval = defaultInterval == default ? TimeSpan.FromMilliseconds(100) : defaultInterval; }
private void SmartUpload(SyncEngine client, IPersistenceEngine server) { if (server == null) throw new ArgumentException("The server engine must be not null"); if (client == null) throw new ArgumentException("The client engine must be not null and a SyncProvider"); IList<Entity> commands = GetPeerMetadataEngine(client, Peer.Client).Load("from " + SyncUtils.COMMAND + " c orderby c.Processed, c.Number select c", 1, 0); EntitySet commandsToRemove = ((EntitySet)commands).Clone(); Command[] optimized = OptimizeCommands(client, commands); Transaction t = new Transaction(client.MetadataEngine.Factory.Model); foreach (Command c in optimized) { c.ClientId = client.ClientId; CompoundCreateCommand ccc = c as CompoundCreateCommand; if (ccc != null) foreach (Command cmd in ccc.InnerCommands) cmd.ClientId = client.ClientId; t.PushCommand(c); } t.Commit(server, false); // Deletes the metadata once they are processed t = new Transaction(client.MetadataEngine.Factory.Model); t.Delete(commandsToRemove); t.Commit(client.MetadataEngine, false); }
public static async IAsyncEnumerable <AlmostOrderedArticlesState.ShoppingCartArticleRemovedInfo> AnalyseAlmostOrderedWithState(IPersistenceEngine engine = null) { engine = engine ?? Program.engine; var loadedMessages = await engine.LoadStreamEntriesAsync( 0, int.MaxValue, new[] { typeof(ShoppingCartCreated), typeof(ShoppingCartArticleRemoved), typeof(ShoppingCartOrdered), typeof(ShoppingCartCancelled) }) .Select(x => engine.Serializer.Deserialize(x.Payload)) .ToListAsync(); Console.WriteLine("Removed Articles: "); var almostOrderedState = AlmostOrderedArticlesState.LoadState((AlmostOrderedArticlesState)null, loadedMessages); var removedArticles = almostOrderedState .AlmostOrderedShoppingCartArticles .ToList(); var groupedByCustomer = removedArticles .GroupBy(x => x.CustomerName) .Select(x => new { CustomerName = x.Key, Articlenumbers = x.GroupBy(y => y.Articlenumber) .Select(y => new { Count = y.Count(), Articlenumber = y.Key }) .ToList() }) .ToList(); foreach (var item in groupedByCustomer) { Console.WriteLine($"{item.CustomerName}: {string.Join(", ", item.Articlenumbers.Select(x => "" + x.Count + "x " + x.Articlenumber))} "); } Console.WriteLine(); foreach (var item in removedArticles) { yield return(item); } }
public NHibernatePersistenceTransaction(IPersistenceEngine persistenceEngine, ILogProvider logProvider, IUserInfo userInfo) { _persistenceEngine = persistenceEngine; _logger = logProvider.GetLogger("NHibernatePersistenceTransaction"); _userInfo = userInfo; }
protected override async Task BeforeFixtureTransactionAsync() { engine = config.WriteModel.GetPersistenceEngine(); await base.BeforeFixtureTransactionAsync(); }
public override async Task CleanupWriteDatabaseAsync() { persistenceEngine = null; }