public StateInstanceAccessor(object owner, IStateStorage allStorages,
     IStateAccessorFactory accessorFactory) : base(owner, allStorages)
 {
     if (accessorFactory == null) throw new ArgumentNullException("accessorFactory");
     _allStorages = allStorages;
     _accessorFactory = accessorFactory;
 }
 public void Init()
 {
     _fixture = new Fixture().Customize(new AutoRhinoMockCustomization());
     _storage = _fixture.Create<IStateStorage>();
     _accessorFactory = _fixture.Create<IStateAccessorFactory>();
     _sut = new StateService(_storage);
 }
예제 #3
0
 private async ValueTask <IStateStorage <S, K> > GetStateStore()
 {
     if (_StateStore == null)
     {
         _StateStore = await ServiceProvider.GetService <IStorageContainer>().GetStateStorage <K, S>(GetType(), this);
     }
     return(_StateStore);
 }
 public StateAccessor(object owner, IStateStorage allStorages)
 {
     if (owner == null) throw new ArgumentNullException("owner");
     if (allStorages == null) throw new ArgumentNullException("allStorages");
     OwnerIdentity = RuntimeHelpers.GetHashCode(owner);
     Owner = owner;
     _ownerStateStorage = allStorages.GetStorage(OwnerIdentity);
 }
예제 #5
0
 public Store(IReducer <TState> rootReducer, IActionResolver actionResolver, IStateStorage storage, INavigationTracker <TState> navigationTracker, IDevToolsInterop devToolsInterop)
 {
     _rootReducer       = rootReducer;
     _actionResolver    = actionResolver;
     _storage           = storage;
     _navigationTracker = navigationTracker;
     _devToolsInterop   = devToolsInterop;
 }
        public void Ctor_NullStorage_ShouldThrowException()
        {
            // Arrange
            _storage = null;

            // Act
            _sut = new StateService(_storage, _accessorFactory);
        }
예제 #7
0
 protected virtual async ValueTask <IStateStorage <S, K> > GetStateStorage()
 {
     if (_stateStorage == null)
     {
         _stateStorage = await ServiceProvider.GetService <IStorageContainer>().GetStateStorage <K, S>(GetType(), this);
     }
     return(_stateStorage);
 }
예제 #8
0
        public UnitOfWorkManager(IStateStorage stateStorage, IUnitOfWorkTransactionManager transactionManager, ILogger <UnitOfWorkManager> logger,
                                 IServiceProvider serviceProvider)
        {
            _stateStorage = stateStorage;

            _logger          = logger;
            _serviceProvider = serviceProvider;
            this.SetTransactionManagerProvider(() => transactionManager);
        }
        public void Init()
        {
            _fixture = new Fixture().Customize(new AutoRhinoMockCustomization());
            _storage = _fixture.Create<IStateStorage>();
            _target = _fixture.Create<object>();
            var targetIdentity = RuntimeHelpers.GetHashCode(_target);
            _storage.Stub(x => x.GetStorage(targetIdentity)).Return(new Dictionary<string, object>());

            _sut = new StateAccessor(_target, _storage);
        }
예제 #10
0
 public Converter(string root, ISvnReader reader, IGitWriter writer, IStateStorage storage, State state, string prefix, string descriptionSuffix, bool ignoreBranches, bool master)
 {
     _root              = root;
     _reader            = reader;
     _writer            = writer;
     _storage           = storage;
     _state             = state;
     _prefix            = prefix;
     _descriptionSuffix = descriptionSuffix;
     _ignoreBranches    = ignoreBranches;
     _master            = master;
 }
예제 #11
0
        public SessionStateManager(IStateStorage stateStorage)
        {
            _stateStorage = stateStorage ?? throw new ArgumentNullException(nameof(stateStorage));

            _registeredOrganisations.Add("ef269f3d-8f1d-4693-bbc1-06dce4956d8ef03c21aa-4b58-4636-b1e5-e1533c15a5a4", new OrganisationRegistration {
                OrganisationName = "Blazor MealService"
            });
            _registeredRecipes.Add("ef269f3d-8f1d-4693-bbc1-06dce4956d8ef03c21aa-4b58-4636-b1e5-e1533c15a5a4", new List <RecipeRegistration> {
                new RecipeRegistration {
                    RecipeName = "Burger and Fries"
                }
            });
        }
예제 #12
0
        public StateStorageIntegrationTests()
        {
            var readConfig = new ConfigurationBuilder().AddJsonFile("appSettings.json").Build();
            var config     = new ServicePrincipleConfig
            {
                InstanceName   = readConfig.GetValue <string>("InstanceName"),
                TenantId       = readConfig.GetValue <string>("TenantId"),
                SubscriptionId = readConfig.GetValue <string>("SubscriptionId"),
                AppId          = readConfig.GetValue <string>("AppId"),
                AppSecret      = readConfig.GetValue <string>("AppSecret"),
            };

            _tableStorage = new TableStorage(config);
            _tableStorage.CreateTable(_tableStorage.StateStorageTableName).GetAwaiter().GetResult();
            _stateStorage = _tableStorage;
        }
예제 #13
0
        public async Task <IEventSourcing <TState, TStateKey> > Init(TStateKey stateKey)
        {
            this.StateId         = stateKey;
            this._storageFactory = new StorageFactory(this._serviceProvider, this.Options.StorageOptions);
            this._eventStorage   = await this._storageFactory.GetEventStorage(this.Options.EventSourceName, this.StateId.ToString());

            string bufferKey = "es" + this.Options.EventSourceName + this.Options.StorageOptions.StorageProvider;

            this._eventBufferBlock = this._serviceProvider.GetRequiredService <IDataflowBufferBlockFactory>().Create <EventStorageModel>(bufferKey, this.LazySaveAsync);

            //Get snapshot storage information
            if (this.Options.SnapshotOptions.SnapshotType != SnapshotType.NoSnapshot)
            {
                IStorageFactory snapshotStorageFactory = new StorageFactory(this._serviceProvider, this.Options.SnapshotOptions);
                this._snapshotStorage = await snapshotStorageFactory.GetStateStorage(this.Options.EventSourceName, StorageType.EventSourceSnapshot, this.StateId.ToString());

                this.SnapshotTable = await snapshotStorageFactory.GetTable(this.Options.EventSourceName, StorageType.EventSourceSnapshot, this.StateId.ToString());
            }
            return(this);
        }
예제 #14
0
        public TraficLightStateMachine(IStateStorage <TraficLightStates> stateStorage)
            : base(stateStorage: stateStorage)
        {
            AddTransition(TraficLightStates.Off, TraficLightEvents.Start, TraficLightStates.On);
            AddTransition(TraficLightStates.On, TraficLightEvents.Stop, TraficLightStates.Off);
            AddTransition(TraficLightStates.Red, TraficLightEvents.TimeEvent, TraficLightStates.RedYellow);
            AddTransition(TraficLightStates.RedYellow, TraficLightEvents.TimeEvent, TraficLightStates.Green);
            AddTransition(TraficLightStates.Green, TraficLightEvents.TimeEvent, TraficLightStates.Yellow);
            AddTransition(TraficLightStates.Yellow, TraficLightEvents.TimeEvent, TraficLightStates.Red);

            SetupSubstates(TraficLightStates.On, HistoryType.None, TraficLightStates.Red,
                           TraficLightStates.RedYellow, TraficLightStates.Green, TraficLightStates.Yellow);

            this[TraficLightStates.On].EntryHandler += start;
            this[TraficLightStates.On].ExitHandler  += stop;

            m_timer = new Timer(s => Send(TraficLightEvents.TimeEvent));

            Initialize();
        }
예제 #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PassiveStateMachine{TState, TEvent,TArgs}"/> class.
 /// </summary>
 /// <param name="comparer"> </param>
 /// <param name="stateStorage">The state storage.</param>
 protected PassiveStateMachine(IEqualityComparer <TEvent> comparer = null, IStateStorage <TState> stateStorage = null)
     : base(comparer, stateStorage)
 {
     Synchronized = false;
 }
예제 #16
0
 public LogContext(string logType, IStateStorage storage)
 {
     LogType = logType;
     Storage = storage;
 }
		public AppState(IStateStorage storage)
       {
			Favorites = new ObservableCollection<Photo> ();
			_storage = storage;
			CurrentPhotos = new ObservableCollection<Photo> ();
       }
 public IStateInstanceAccessor CreateInstanceAccessor(object target, IStateStorage allStorages,
     IStateAccessorFactory accessorFactory)
 {
     return new StateInstanceAccessor(target, allStorages, accessorFactory);
 }
예제 #19
0
        /// <see cref="IMiddleware.InitializeAsync(IStore)"/>
        public override async Task InitializeAsync(IStore store)
        {
            Store = store;

            store.SubscribeToAction <ResetAllStatesAction>(this, action =>
            {
                string ErrMsg = "";
                foreach (IFeature feature in Store.Features.Values.OrderBy(x => x.GetName()))
                {
                    if (!Options.ShouldPersistState(feature.GetName()))
                    {
                        Logger?.LogDebug($"Don't reset {feature.GetName()} state");
                    }
                    else
                    {
                        try
                        {
                            var GetInitialState = feature.GetType().GetMethod("GetInitialState", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                                                                              null,
                                                                              CallingConventions.Any,
                                                                              new Type[] { },
                                                                              null);
                            var obj = GetInitialState.Invoke(feature, null);
                            feature.RestoreState(obj);
                        }
                        catch (Exception ex)
                        {
                            ErrMsg += ex.ToString() + "\r\n";
                        }
                        if (Store == null || IsInsideMiddlewareChange)
                        {
                            ErrMsg += "Store is null or inside middleware change\r\n";
                        }
                    }
                }
                if (ErrMsg == "")
                {
                    Store.Dispatch(new ResetAllStatesResultSuccessAction());
                }
                else
                {
                    Store.Dispatch(new ResetAllStatesResultFailAction()
                    {
                        ErrorMessage = ErrMsg
                    });
                }
            });

            store.SubscribeToAction <InitializePersistMiddlewareAction>(this, async(action) =>
            {
                localStorage = action.StorageService;
                if (action.RehydrateStatesFromStorage)
                {
                    foreach (IFeature feature in Store.Features.Values.OrderBy(x => x.GetName()))
                    {
                        if (!Options.ShouldPersistState(feature.GetName()))
                        {
                            Logger?.LogDebug($"Don't persist {feature.GetName()} state");
                        }
                        else
                        {
                            Logger?.LogDebug($"Rehydrating state {feature.GetName()}");
                            string json = await localStorage.GetStateJsonAsync(feature.GetName());
                            if (json == null)
                            {
                                Logger?.LogDebug($"No saved state for {feature.GetName()}, skipping");
                            }
                            else
                            {
                                ////Logger?.LogDebug($"Deserializing type {feature.GetStateType().ToString()} from json {json}");
                                Logger?.LogDebug($"Deserializing type {feature.GetStateType().ToString()}");
                                try
                                {
                                    object stronglyTypedFeatureState = JsonSerializer.Deserialize(
                                        json,
                                        feature.GetStateType());
                                    if (stronglyTypedFeatureState == null)
                                    {
                                        Logger?.LogError($"Deserialize returned null");
                                    }
                                    else
                                    {
                                        // Now set the feature's state to the deserialized object
                                        feature.RestoreState(stronglyTypedFeatureState);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger?.LogError("Failed to deserialize state. Skipping. Error:" + ex.ToString());
                                }
                            }
                        }
                    }
                }
                //Logger?.LogDebug("Initialized Persist Middleware");
                if (Store != null && !IsInsideMiddlewareChange)
                {
                    Store.Dispatch(new InitializePersistMiddlewareResultSuccessAction());
                }
                else
                {
                    Store.Dispatch(new InitializePersistMiddlewareResultFailAction());
                }
            });

            await base.InitializeAsync(store);

            foreach (IFeature feature in Store.Features.Values.OrderBy(x => x.GetName()))
            {
                Logger?.LogDebug($"Wiring up event for feature {feature.GetName()}");
                feature.StateChanged += Feature_StateChanged;
            }
        }
 public IStateAccessor CreateAccessor(object target, IStateStorage allStorages)
 {
     return new StateAccessor(target, allStorages);
 }
예제 #21
0
 public CategoryCriterion(IStateStorage stateStorage, IContentLoader contentLoader, ICategoryContentLoader categoryContentLoader)
 {
     _stateStorage          = stateStorage;
     _contentLoader         = contentLoader;
     _categoryContentLoader = categoryContentLoader;
 }
예제 #22
0
 public LogContext(string logType, IStateStorage storage)
 {
     LogType = logType;
     Storage = storage;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ActiveStateMachine{TState,TEvent,TArgs}"/> class.
 /// </summary>
 protected ActiveStateMachine(IEqualityComparer <TEvent> comparer = null, IStateStorage <TState> stateStorage = null)
     : this(defaultSynchronizationContext, comparer, stateStorage)
 {
 }
예제 #24
0
 public StateMachine(IEqualityComparer <TEvent> comparer = null, IStateStorage <TState> stateStorage = null)
 {
     states         = new StateMap(comparer);
     m_stateStorage = stateStorage ?? new InternalStateStorage <TState>();
 }
예제 #25
0
 public MyObjectThatUsesSession(IStateStorage storage)
 {
     _storage = storage ?? new SessionStorage();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ActiveStateMachine{TState,TEvent,TArgs}"/> class.
 /// </summary>
 /// <param name="syncContext">The synchronization context.</param>
 /// <param name="comparer"> </param>
 /// <param name="stateStorage"> </param>
 protected ActiveStateMachine(SynchronizationContext syncContext, IEqualityComparer <TEvent> comparer = null, IStateStorage <TState> stateStorage = null)
     : base(comparer, stateStorage)
 {
     SyncContext            = syncContext;
     queue                  = new DelegateQueue();
     queue.PostCompleted   += raiseExceptionEventOnError;
     queue.InvokeCompleted += raiseExceptionEventOnError;
 }