///------------------------------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="store"> /// The store. /// </param> /// <param name="index"> /// Zero-based index of the. /// </param> ///------------------------------------------------------------------------------------------------- public IndexWrapper(IHyperstore store, IIndex index) { DebugContract.Requires(store); DebugContract.Requires(index); _store = store; _index = index; }
private void Serialize(Stream stream, IEnumerable <IModelEntity> entities, IEnumerable <IModelRelationship> relationships, HashSet <Identity> deletedEntities = null, HashSet <Identity> deletedRelationShips = null) { ISession session = null; if (Session.Current != null) { Session.Current.SetMode(SessionMode.Serializing); } else { IHyperstore store = _domain.Store; SessionConfiguration sessionConfiguration = new SessionConfiguration(); sessionConfiguration.Mode = SessionMode.Serializing; session = store.BeginSession(sessionConfiguration); } try { _monikers = new Dictionary <Identity, MonikerEntry>(); SerializeEntities(entities, deletedEntities); SerializeRelationships(relationships, deletedRelationShips); _writer.Save(stream, _monikers.Values); } finally { if (session != null) { session.AcceptChanges(); session.Dispose(); } _monikers = null; _monikerSequence = 0; } }
// [Fact] public async Task BenchWithConstraints() { long nb = 0; store = await StoreBuilder.New().CreateAsync(); schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var domain = await store.DomainModels.New().CreateAsync("Test"); var sw = new Stopwatch(); // Ajout de 100 contraintes var nbc = 100; for (int i = 0; i < nbc; i++) schema.Definition.XExtendsBaseClass.AddImplicitConstraint( self => System.Threading.Interlocked.Increment(ref nb) > 0, "OK"); sw.Start(); var mx = 10000; AddElement(domain, mx); UpdateElement(mx); ReadElement(mx); RemoveElement(mx); sw.Stop(); Assert.Equal(mx * nbc * 2, nb); // Nbre de fois la contrainte est appelée (sur le add et le update) Assert.True(sw.ElapsedMilliseconds < 4000, String.Format("ElapsedTime = {0}", sw.ElapsedMilliseconds)); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="UndoManager" /> class. /// </summary> /// <param name="store"> /// The store. /// </param> /// <param name="capacity"> /// (Optional) /// </param> ///------------------------------------------------------------------------------------------------- public UndoManager(IHyperstore store, int capacity = 100) { Contract.Requires(store, "store"); Contract.Requires(capacity > 0, "capacity"); _store = store; _domainModels = new Dictionary <string, DomainInfo>(StringComparer.OrdinalIgnoreCase); _undos = new RecursiveStack <SessionEvents>(capacity); _redos = new RecursiveStack <SessionEvents>(capacity); Capacity = capacity; }
/// <summary> /// Constructeur interne. Il est appelé par le store quand il crée la session /// </summary> /// <param name="store">The store.</param> /// <param name="cfg">The CFG.</param> internal Session(IHyperstore store, SessionConfiguration cfg) { DebugContract.Requires(store, "store"); if (SessionIndex == null) { SessionIndex = s_sessionSequences.GetFirstFreeValue(); } _trace = store.Trace; var ctx = SessionDataContext; if (ctx == null) { // _statSessionCount.Incr(); // Nouvelle session ctx = new SessionDataContext // TODO optimize memory size { TrackingData = new SessionTrackingData(this), SessionIsolationLevel = cfg.IsolationLevel, Locks = new List <ILockInfo>(), ReadOnly = cfg.Readonly, ReadOnlyStatus = cfg.Readonly, Current = this, OriginStoreId = cfg.Origin ?? store.Id, Mode = cfg.Mode, SessionId = cfg.SessionId != 0 ? cfg.SessionId : Interlocked.Increment(ref s_sessionIdSequences), Store = store, CancellationToken = cfg.CancellationToken, Enlistment = new List <ISessionEnlistmentNotification>(), SessionInfos = new Stack <SessionLocalInfo>(), TopLevelSession = this, DefaultDomainModel = cfg.DefaultDomainModel, }; SessionDataContext = ctx; _scope = Hyperstore.Modeling.Platform.PlatformServices.Current.CreateTransactionScope(this, cfg); } else if (ctx.SessionInfos.Count == 0) { throw new HyperstoreException(ExceptionMessages.CannotCreateNestedSessionInDisposingSession); } ctx.SessionInfos.Push(new SessionLocalInfo { DefaultDomainModel = cfg.DefaultDomainModel ?? ctx.DefaultDomainModel, Mode = cfg.Mode | ctx.Mode, OriginStoreId = cfg.Origin ?? ctx.OriginStoreId }); }
void IDisposable.Dispose() { lock (_sync) { foreach (var dm in _scopes) { dm.Dispose(); } _scopeByNames.Clear(); _scopes = null; } Store = null; }
private async Task CreateDomain() { store = await StoreBuilder.New().EnableScoping().CreateAsync(); schema = await store.Schemas .New <LibraryDefinition>() .CreateAsync(); domain = await store.DomainModels .New() .UsingIdGenerator(r => new LongIdGenerator()) .CreateAsync("lib"); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Méthode appelée dans le processus de création que celle ci soit faite par new ou par /// sérialisation. /// </summary> /// <param name="schemaElement"> /// The schema container. /// </param> /// <param name="domainModel"> /// The domain model. /// </param> ///------------------------------------------------------------------------------------------------- protected virtual void Initialize(ISchemaElement schemaElement, IDomainModel domainModel) { Contract.Requires(schemaElement, "schemaElement"); Contract.Requires(domainModel, "domainModel"); //DebugContract.Requires(Session.Current); _sequence = Interlocked.Increment(ref _globalSequence); _calculatedProperties = new Lazy <Dictionary <string, CalculatedProperty> >(() => new Dictionary <string, CalculatedProperty>()); _store = domainModel.Store; _domainModel = domainModel; _schema = schemaElement; SubscribeOnPropertyChangedEvent(); }
public async Task Bench() { store = await StoreBuilder.New().CreateAsync(); schema = await store.Schemas.New<TestDomainDefinition>().CreateAsync(); var domain = await store.DomainModels.New().CreateAsync("Test"); var sw = new Stopwatch(); sw.Start(); var mx = 100; AddElement(domain, mx); UpdateElement(mx); ReadElement(mx); RemoveElement(mx); sw.Stop(); Trace.WriteLine("Bench : " + sw.ElapsedMilliseconds.ToString()); Assert.True(sw.ElapsedMilliseconds < 2000); }
///------------------------------------------------------------------------------------------------- /// <summary> /// An IHyperstore extension method that creates a relationship. /// </summary> /// <exception cref="SessionRequiredException"> /// Thrown when a Session Required error condition occurs. /// </exception> /// <param name="store"> /// The store to act on. /// </param> /// <param name="schema"> /// The schema. /// </param> /// <param name="start"> /// The start. /// </param> /// <param name="end"> /// The end. /// </param> /// <param name="id"> /// (Optional) the identifier. /// </param> /// <returns> /// The new relationship. /// </returns> ///------------------------------------------------------------------------------------------------- public static IModelRelationship CreateRelationship(this IHyperstore store, ISchemaRelationship schema, IModelElement start, IModelElement end, Identity id = null) { Contract.Requires(store != null, "store"); Contract.Requires(schema != null, "schema"); Contract.Requires(start != null, "start"); Contract.Requires(end != null, "end"); if (Session.Current == null) { throw new SessionRequiredException(); } var domain = start.DomainModel; var cmd = new AddRelationshipCommand(schema, start, end, id); Session.Current.Execute(cmd); return(cmd.Relationship); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Releases the unmanaged resources used by the Hyperstore.Modeling.ModelElement and optionally /// releases the managed resources. /// </summary> /// <param name="disposing"> /// true to release both managed and unmanaged resources; false to release only unmanaged /// resources. /// </param> ///------------------------------------------------------------------------------------------------- protected virtual void Dispose(bool disposing) { // Le finalizer existe pour être certain qu'une instance d'un élément sera bien déréférencée du gestionnaire d'événements, // comme cela a été fait, ce n'est plus la peine de l'appeler. GC.SuppressFinalize(this); try { var domainModelDisposed = _domainModel != null && _domainModel.IsDisposed; if (this is INotifyPropertyChanged) { if (!domainModelDisposed && _domainModel.Events != null) { _domainModel.Events.UnregisterForAttributeChangedEvent(this); } } } catch { // Domain already disposed } DisableDataErrorsNotification(); if (_calculatedProperties != null && _calculatedProperties.IsValueCreated) { foreach (var p in _calculatedProperties.Value.Values) { var disposable = p as IDisposable; if (disposable != null) { disposable.Dispose(); } } } OnDisposing(); _errorsChangedEventHandler = null; _calculatedProperties = null; _status = ModelElementStatus.Disposed; _domainModel = null; _store = null; }
private async Task <IDomainModel> InitializeStore() { // Create a store store = await StoreBuilder .New() // This optional step is used to include the command interceptor .ComposeWith(this.GetType().Assembly) .CreateAsync(); // Load the library schema await store.Schemas.New <MyLibraryDefinition>().CreateAsync(); // And instanciate a domain to manage all the elements of the domain var domain = await store.DomainModels.New().CreateAsync("MyLib"); // Set as default domain store.DefaultSessionConfiguration.DefaultDomainModel = domain; return(domain); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="services"> /// The services. /// </param> ///------------------------------------------------------------------------------------------------- public EventBus(IServicesContainer services) { DebugContract.Requires(services); _store = services.Resolve <IHyperstore>(); DefaultEventDispatcher = services.Resolve <IEventDispatcher>(); }
public ScopeManager(IHyperstore store) { Contract.Requires(store, "store"); Store = store; _scopes = ImmutableList.Create <T>(); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="store"> /// The store. /// </param> ///------------------------------------------------------------------------------------------------- public ExtendedScopeManager(IHyperstore store) { Contract.Requires(store, "store"); Store = store; }
public ScopeControler(IHyperstore store) { Store = store; }
public async Task BenchWithConstraints(int cx) { var collects = Enumerable.Range(0, 3).Select(i => GC.CollectionCount(i)).ToArray(); long nb = 0; store = await StoreBuilder.New().CreateAsync(); schema = await store.Schemas.New <TestDomainDefinition>().CreateAsync(); var domain = await store.DomainModels .New() .UsingIdGenerator(services => new Hyperstore.Modeling.Domain.LongIdGenerator()) .CreateAsync("Test"); var sw = new Stopwatch(); var mx = 10000; Console.WriteLine("Benchmark manipulating {0} elements...", mx); // Adding 100 constraints on each element var nbc = 100; if (cx % 2 == 1) { Console.WriteLine("Adding 100 implicit constraints on each element."); for (int i = 0; i < nbc; i++) { schema.Definition.XExtendsBaseClass.AddImplicitConstraint(self => System.Threading.Interlocked.Increment(ref nb) > 0, "OK").Register(); } } Console.WriteLine("Running..."); sw.Start(); AddElement(domain, mx); Console.WriteLine("Added in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); UpdateElement(mx); Console.WriteLine("Updated in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); ReadElement(mx); Console.WriteLine("Read in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); RemoveElement(mx); Console.WriteLine("Removed in {0}ms ", sw.ElapsedMilliseconds); sw.Restart(); sw.Stop(); Console.WriteLine("Expected {0} Value {1}", mx * nbc * 2, nb); domain = null; store.Dispose(); ids.Clear(); for (int i = 0; i < 3; i++) { Console.WriteLine("GC collection {0} : {1}", i, GC.CollectionCount(i) - collects[i]); } //Console.WriteLine(); GC.Collect(); GC.WaitForPendingFinalizers(); //Assert.AreEqual(mx * nbc * 2, nb); // Nbre de fois la contrainte est appelée (sur le add et le update) //Assert.IsTrue(sw.ElapsedMilliseconds < 3000, String.Format("ElapsedTime = {0}", sw.ElapsedMilliseconds)); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="CommandProcessor{T}" /> class. /// </summary> /// <param name="store"> /// The store. /// </param> ///------------------------------------------------------------------------------------------------- public CommandProcessor(IHyperstore store) { DebugContract.Requires(store); }
private async Task<IDomainModel> InitializeStore() { // Create a store store = await StoreBuilder .New() // This optional step is used to include the command interceptor .ComposeWith(this.GetType().Assembly) .CreateAsync(); // Load the library schema await store.Schemas.New<MyLibraryDefinition>().CreateAsync(); // And instanciate a domain to manage all the elements of the domain var domain = await store.DomainModels.New().CreateAsync("MyLib"); // Set as default domain store.DefaultSessionConfiguration.DefaultDomainModel = domain; return domain; }
internal EventsProcessor(IHyperstore store) { DebugContract.Requires(store); _processes = PlatformServices.Current.CreateConcurrentQueue <ProcessInfo>(); _store = store; }
public async Task SerializatonBench(int cx) { store = await StoreBuilder.New().CreateAsync(); await store.Schemas.New <LibraryDefinition>().CreateAsync(); var domain = await store.DomainModels .New() .UsingIdGenerator(services => new Hyperstore.Modeling.Domain.LongIdGenerator()) .CreateAsync("Test"); var sw = new Stopwatch(); Console.WriteLine("Benchmark serializing {0} elements...", cx * 2); Library lib; using (var session = store.BeginSession()) { lib = new Library(domain); lib.Name = "Lib1"; session.AcceptChanges(); } Parallel.For(0, cx, (i) => { using (var session = store.BeginSession()) { var b = new Book(domain); b.Title = "Book \"book\" " + i.ToString(); b.Copies = i + 1; lib.Books.Add(b); var m = new Member(domain); m.Name = "Book " + i.ToString(); lib.Members.Add(m); session.AcceptChanges(); } }); // Console.ReadKey(); //Console.Write("xml ..."); //sw.Start(); //using (var stream = File.Open("test.xml",FileMode.Create)) //{ // HyperstoreSerializer.Serialize(stream, domain); //} //Console.WriteLine(" : serialize {1:n}bytes in {0}ms ", sw.ElapsedMilliseconds, new FileInfo("test.xml").Length); //Console.Write("json ..."); sw.Restart(); using (var stream = File.Open("test.json", FileMode.Create)) { HyperstoreSerializer.Serialize(stream, domain, new SerializationSettings { Options = SerializationOptions.Json | SerializationOptions.CompressSchema }); } // Console.WriteLine(" : serialize {1:n}bytes in {0}ms ", sw.ElapsedMilliseconds, new FileInfo("test.json").Length); //Console.Write("old xml ..."); //sw.Restart(); //using (var stream = File.Open("test2.xml", FileMode.Create)) //{ // var ser = new XmlDomainModelSerializer(); // await ser.Serialize(domain, stream, XmlSerializationOptions.Elements); //} //Console.WriteLine(" : serialize {1:n}bytes in {0}ms ", sw.ElapsedMilliseconds, new FileInfo("test2.xml").Length); // Console.ReadKey(); }
///------------------------------------------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="EventDispatcher" /> class. /// </summary> /// <param name="services"> /// The store. /// </param> /// <param name="initializeWithDefaultHandlers"> /// (Optional) if set to <c>true</c> [initialize with default handlers]. /// </param> ///------------------------------------------------------------------------------------------------- public EventDispatcher(IServicesContainer services, bool initializeWithDefaultHandlers = true) { Contract.Requires(services, "services"); _store = services.Resolve <IHyperstore>(); _initializeWithDefaultHandlers = initializeWithDefaultHandlers; }