/// <summary>
 /// Prepare this state for use in a live railway.
 /// Make sure all relevant connections to other state objects are resolved.
 /// Check the IsReadyForUse property afterwards if it has succeeded.
 /// </summary>
 internal void PrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
 {
     if (!readyForUse)
     {
         readyForUse = TryPrepareForUse(ui, statePersistence);
     }
 }
Beispiel #2
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            if (!base.TryPrepareForUse(ui, statePersistence))
            {
                return(false);
            }
            var splb = lb as SerialPortLocoBuffer;

            if (splb != null)
            {
                var portNames = SerialPort.GetPortNames();
                if (!portNames.Contains(splb.PortName))
                {
                    var portName = ui.ChooseComPortName(this);
                    if (portNames.Contains(portName))
                    {
                        // Now we have an available port name
                        splb.PortName = portName;
                    }
                    else
                    {
                        // No available port name provided, we cannot be used.
                        return(false);
                    }
                }
            }
            return(true);
        }
Beispiel #3
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            if (!base.TryPrepareForUse(ui, statePersistence))
            {
                return(false);
            }
            var portNames = SerialPort.GetPortNames();

            if (!portNames.Contains(Entity.ComPortName))
            {
                var portName = ui.ChooseComPortName(this);
                if (portNames.Contains(portName))
                {
                    // Now we have an available port name
                    client.PortName = portName;
                }
                else
                {
                    // No available port name provided, we cannot be used.
                    return(false);
                }
            }
            // Request for status, this triggers the open process.
            PostWorkerAction(() => client.Status());
            return(true);
        }
        /// <summary>
        /// Returns an instance of <see cref="Microsoft.ApplicationBlocks.UIProcess.IStatePersistence"/>
        /// for the given <see cref="Microsoft.ApplicationBlocks.UIProcess.StatePersistenceProviderSettings"/>.
        /// </summary>
        /// <param name="providerSettings">The settings for  state persistence.</param>
        /// <returns>The instance of IStatePersistence. It gets this from the internal cache, if possible.</returns>
        public static IStatePersistence Create(StatePersistenceProviderSettings providerSettings)
        {
            string            statePersistenceKey = providerSettings.Type + "," + providerSettings.Assembly;
            IStatePersistence spp = (IStatePersistence)_statePersistenceCache[statePersistenceKey];

            if (spp == null)
            {
                try
                {
                    //  now create instance based on that type info
                    spp = (IStatePersistence)GenericFactory.Create(providerSettings);

                    //  pass in parameters to spp init method.  this is where spp's find data they need such as
                    //  connection strings, etc.
                    spp.Init(providerSettings.AdditionalAttributes);
                }
                catch (Exception e)
                {
                    throw new UIPException(Resource.ResourceManager.FormatMessage(Resource.Exceptions.RES_ExceptionCantCreateStatePersistenceProvider, providerSettings.Type) + UIPException.GetFirstExceptionMessage(e), e);
                }

                //  lock collection
                lock (_statePersistenceCache.SyncRoot)
                    _statePersistenceCache[statePersistenceKey] = spp;
            }

            //  return it
            return(spp);
        }
Beispiel #5
0
        /// <summary>
        /// Loads the state for a given task identifier.
        /// </summary>
        /// <param name="taskId">The task identifier (a GUID associated with the task).</param>
        /// <returns>The state.</returns>
        public static State Load(Guid taskId)
        {
            State state = null;

            if (UIPConfiguration.Config.IsStateCacheEnabled)
            {
                state = StateCache.LoadFromCache(taskId);

                if (state == null)
                {
                    //State is not there in the cache, so a new state will be created here
                    IStatePersistence spp = StatePersistenceFactory.Create(  );
                    state = Load(spp, taskId);

                    StateCache.PutStateInCache(state, false);
                }
            }
            else
            {
                //The cache is disabled, so a new one is created
                IStatePersistence spp = StatePersistenceFactory.Create( );
                state = Load(spp, taskId);
            }

            return(state);
        }
Beispiel #6
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            if (!base.TryPrepareForUse(ui, statePersistence))
            {
                return(false);
            }
            try
            {
                client = new MqttClient(Entity.HostName);
                client.MqttMsgPublishReceived += onMqttMsgPublishReceived;
                client.MqttMsgPublished       += onMqttMsgPublished;
                client.ConnectionClosed       += onMqttConnectionClosed;

                // Power on
                client.Connect(clientID);

                // Subscribe to topics
                var topics = getSubscribeTopics();
                var qos    = topics.Select(x => MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE).ToArray();
                client.Subscribe(topics, qos);
            }
            catch (Exception ex)
            {
                Log.Error("Failed to connect to MQTT server: " + ex);
                return(false);
            }
            return(true);
        }
Beispiel #7
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            // Resolve command station
            var cs = RailwayState.SelectCommandStation(Entity);

            if (cs == null)
            {
                return(false);
            }
            cs.AddInput(this);

            // Resolve destination blocks
            var routes = RailwayState.RouteStates.Where(x => x.Contains(this));

            destinationBlocks = routes.Select(x => x.To).ToList();
            if (Entity.Block != null)
            {
                var blockState = RailwayState.BlockStates[Entity.Block];
                if ((blockState != null) && (!destinationBlocks.Contains(blockState)))
                {
                    destinationBlocks.Add(blockState);
                }
            }

            return(true);
        }
Beispiel #8
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            // Do not change the order of initialization
            commandStationStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            locStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            junctionStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            signalStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            blockStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            blockGroupStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            routeStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            sensorStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));
            outputStates.Cast <EntityState>().Foreach(x => x.PrepareForUse(ui, statePersistence));

            // Wrap up
            blockStates.Cast <BlockState>().Foreach(x => x.FinalizePrepare());
            routeStates.Cast <RouteState>().Foreach(x => x.FinalizePrepare());

            // Attach power event
            foreach (var csState in commandStationStates)
            {
                csState.Power.ActualChanged += (s, _) => power.OnActualChanged();
            }

            return(true);
        }
 /// <summary>
 /// Prepare this state for use in a live railway.
 /// Make sure all relevant connections to other state objects are resolved.
 /// </summary>
 /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
 protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
 {
     if (!base.TryPrepareForUse(ui, statePersistence))
     {
         return(false);
     }
     return(true);
 }
Beispiel #10
0
 /// <summary>
 /// Prepare this state for use in a live railway.
 /// Make sure all relevant connections to other state objects are resolved.
 /// </summary>
 /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
 protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
 {
     if (!base.TryPrepareForUse(ui, statePersistence))
     {
         return(false);
     }
     RailwayState.ModelTime.ActualChanged += (s, _) => OnTimeChanged();
     return(true);
 }
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            blocks.Clear();
            var myBlockEntities = Entity.Module.Blocks.Where(x => x.BlockGroup == Entity);

            blocks.AddRange(myBlockEntities.Select(x => RailwayState.BlockStates[x]));

            return(true);
        }
Beispiel #12
0
 /// <summary>
 /// Prepare this state for use in a live railway.
 /// Make sure all relevant connections to other state objects are resolved.
 /// </summary>
 /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
 protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
 {
     if (!base.TryPrepareForUse(ui, statePersistence))
     {
         return(false);
     }
     CommandStation.AddInput(busyInput);
     return(true);
 }
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            var stream = Entity.Sound;

            if (stream != null)
            {
                sound = ui.SoundPlayer.Create(stream);
            }
            return(true);
        }
Beispiel #14
0
        /// <summary>
        /// Default ctor
        /// </summary>
        internal AppState(IStateUserInterface ui, MainForm mainForm)
        {
            Application.ThreadException += (s, x) => OnErrorPowerDown(x.Exception);
            Application.Idle            += (s, x) => OnApplicationIdle();
            this.ui       = ui;
            this.mainForm = mainForm;
            var persistence = new StatePersistence();

            statePersistence = persistence;
            server           = new Core.Server.Impl.Server();
        }
 /// <summary>
 /// Prepare this state for use in a live railway.
 /// Make sure all relevant connections to other state objects are resolved.
 /// </summary>
 /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
 protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
 {
     if (Entity.Loc != null)
     {
         loc = RailwayState.LocStates[Entity.Loc];
         if (loc == null)
         {
             return(false);
         }
     }
     return(true);
 }
Beispiel #16
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            if (!base.TryPrepareForUse(ui, statePersistence))
            {
                return(false);
            }
            try
            {
                discoveryBroadcaster.Start();
            }
            catch (Exception ex)
            {
                Log.Error("Failed to start discovery broadcaster: " + ex);
                return(false);
            }
            try
            {
                localWorkerService = new LocalWorkerServiceImpl(this, Log);
                grpcServer         = new Server
                {
                    Services = { LocalWorkerService.BindService(localWorkerService) },
                    Ports    = { new ServerPort("0.0.0.0", Entity.APIPort, ServerCredentials.Insecure) }
                };
                grpcServer.Start();
            }
            catch (Exception ex)
            {
                Log.Error("Failed to start GRPC server: " + ex);
                return(false);
            }

            try
            {
                client = new MqttClient(Entity.HostName);
                client.MqttMsgPublishReceived += onMqttMsgPublishReceived;
                client.MqttMsgPublished       += onMqttMsgPublished;
                client.ConnectionClosed       += onMqttConnectionClosed;

                // Power on
                client.Connect(clientID);

                // Subscribe to topics
                var topics = getSubscribeTopics();
                var qos    = topics.Select(x => MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE).ToArray();
                client.Subscribe(topics, qos);
            }
            catch (Exception ex)
            {
                Log.Error("Failed to connect to MQTT server: " + ex);
                return(false);
            }
            return(true);
        }
Beispiel #17
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            var cs = RailwayState.SelectCommandStation(Entity);

            if (cs == null)
            {
                return(false);
            }
            this.statePersistence = statePersistence;
            cs.AddLoc(this);
            commandStation = cs;
            return(true);
        }
Beispiel #18
0
        /// <summary>
        /// Creates the default State object, loading it from the persistence provider.
        /// </summary>
        /// <returns>Default state instance of type specified in the configuration file.</returns>
        public static State Create()
        {
            IStatePersistence  spp          = StatePersistenceFactory.Create();
            ObjectTypeSettings typeSettings = UIPConfiguration.Config.DefaultState;

            State state = Create(spp, typeSettings);

            if (UIPConfiguration.Config.IsStateCacheEnabled)
            {
                StateCache.PutStateInCache(state, true);
            }

            return(state);
        }
Beispiel #19
0
        /// <summary>
        /// Uses the task ID to explicitly load the state from the provided IStatePersistence instance.
        /// Note that this overload does not attempt to fetch from the cache.
        /// </summary>
        /// <param name="statePersistenceProvider"></param>
        /// <param name="taskId"></param>
        /// <returns></returns>
        internal static State Load(IStatePersistence statePersistenceProvider, Guid taskId)
        {
            State state = statePersistenceProvider.Load(taskId);

            if (state != null)
            {
                state.Accept(statePersistenceProvider);
            }
            else
            {
                throw new UIPException(Resource.ResourceManager.FormatMessage(Resource.Exceptions.RES_ExceptionTaskNotFound, taskId));
            }

            return(state);
        }
Beispiel #20
0
        /// <summary>
        /// Creates a State object, loading it from persistence provider.
        /// </summary>
        /// <param name="navigatorName">Name of the navigator.</param>
        /// <returns>State instance of the type specified in the configuration file.</returns>
        public static State Create(string navigatorName)
        {
            //  Create a State persistence provider to be used by the state object
            IStatePersistence  spp          = StatePersistenceFactory.Create(navigatorName);
            ObjectTypeSettings typeSettings = UIPConfiguration.Config.GetStateSettings(navigatorName);

            State state = Create(spp, typeSettings);

            //Check if the cache is enabled
            if (UIPConfiguration.Config.IsStateCacheEnabled)
            {
                StateCache.PutStateInCache(state, navigatorName, true);
            }

            return(state);
        }
Beispiel #21
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            if (!base.TryPrepareForUse(ui, statePersistence))
            {
                return(false);
            }
            var cs = SelectCommandStation();

            if (cs == null)
            {
                return(false);
            }
            cs.AddJunction(this);
            commandStation = cs;
            RailwayState.Power.ActualChanged += OnPowerActualChanged;
            return(true);
        }
        public void StartAndStopRunner()
        {
            WindsorContainer windsorContainer = new WindsorContainer(@"SampleConfigurations\ProjectPilot.config.xml");

            windsorContainer.Kernel.ComponentCreated      += new Castle.MicroKernel.ComponentInstanceDelegate(Kernel_ComponentCreated);
            windsorContainer.Kernel.ComponentModelCreated += new Castle.MicroKernel.ComponentModelDelegate(Kernel_ComponentModelCreated);
            windsorContainer.Kernel.ComponentRegistered   += new Castle.MicroKernel.ComponentDataDelegate(Kernel_ComponentRegistered);
            windsorContainer.Kernel.DependencyResolving   += new Castle.MicroKernel.DependencyDelegate(Kernel_DependencyResolving);
            windsorContainer.Kernel.HandlerRegistered     += new Castle.MicroKernel.HandlerDelegate(Kernel_HandlerRegistered);

            WindsorContainerGraphs.GenerateDependencyGraph(windsorContainer, "graph.dot");

            IStatePersistence mockStatePersistence = MockRepository.GenerateMock <IStatePersistence>();

            // prepare test history data
            RevisionControlHistoryData data;

            using (Stream stream = File.OpenRead(@"..\..\..\Data\Samples\svn-log.xml"))
            {
                data = SubversionHistoryFacility.LoadHistory(stream);
            }

            IRevisionControlHistoryFacility mockRcsHistoryFacility = MockRepository.GenerateMock <IRevisionControlHistoryFacility>();

            mockRcsHistoryFacility.Stub(action => action.FetchHistory()).Return(data);

            windsorContainer.Kernel.AddComponentInstance("RcsHistoryFacility", typeof(IRevisionControlHistoryFacility), mockRcsHistoryFacility);

            using (IRunner runner = windsorContainer.Resolve <IRunner>())
            {
                Project[] projects = windsorContainer.Kernel.ResolveServices <Project>();

                IProjectRegistry projectRegistry = windsorContainer.Resolve <IProjectRegistry>();
                Assert.AreEqual(1, projectRegistry.ProjectsCount);

                Project project = projectRegistry.GetProject("projectpilot");
                Assert.IsNotNull(project);

                Assert.AreEqual(1, project.ModulesCount);
                IProjectModule module = project.GetModule("RevisionControlStats");

                runner.Start();
                Thread.Sleep(5000);
            }
        }
Beispiel #23
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            var index = 0;

            while (index < actions.Count)
            {
                var x = (EntityState)actions[index];
                x.PrepareForUse(ui, statePersistence);
                if (!x.IsReadyForUse)
                {
                    actions.RemoveAt(index);
                }
                else
                {
                    index++;
                }
            }
            return(actions.Any());
        }
Beispiel #24
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            // Load state
            this.statePersistence = statePersistence;
            bool closed;

            if (statePersistence.TryGetBlockState(RailwayState, this, out closed))
            {
                Closed.Requested = closed;
            }
            junctions.Clear();
            var myJunctionEntities = Entity.Module.Junctions.Where(x => x.Block == Entity);

            junctions.AddRange(myJunctionEntities.Select(x => RailwayState.JunctionStates[x]));

            var groupEntity = Entity.BlockGroup;

            blockGroup = (groupEntity != null) ? RailwayState.BlockGroupStates[groupEntity] : null;

            return(true);
        }
Beispiel #25
0
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            var fromBlock = routes[0].From as IBlock;

            if (fromBlock == null)
            {
                return(false);
            }
            from = RailwayState.BlockStates[fromBlock];
            var lastRoute = routes[routes.Length - 1];
            var toBlock   = lastRoute.To as IBlock;

            if (toBlock == null)
            {
                return(false);
            }
            to = RailwayState.BlockStates[toBlock];
            destinationReachedTrigger.PrepareForUse(ui, statePersistence);

            foreach (var route in routes)
            {
                foreach (var item in route.CrossingJunctions)
                {
                    var junctionState = RailwayState.JunctionStates[item.Junction];
                    var state         = item.Accept(Default <JunctionWithStateBuilder> .Instance, junctionState);
                    if (state == null)
                    {
                        return(false);
                    }
                    crossingJunctions.Add(state);
                    hasNonStraightSwitches |= state.IsNonStraight;
                }
            }

            events.ForEach(x => x.PrepareForUse(ui, statePersistence));
            permissions.PrepareForUse(ui, statePersistence);


            return(true);
        }
Beispiel #26
0
        /// <summary>
        /// Creates a State object, loading it from persistence provider.
        /// </summary>
        /// <param name="spp">The state persistence provider.</param>
        /// <param name="typeSettings">The state settings.</param>
        /// <returns>A state instance of the type specified in the configuration file.</returns>
        internal static State Create(IStatePersistence spp, ObjectTypeSettings typeSettings)
        {
            State state  = null;
            Guid  taskId = Guid.Empty;

            if (typeSettings == null)
            {
                throw new UIPException(Resource.ResourceManager.FormatMessage(Resource.Exceptions.RES_ExceptionStateConfigNotFound, ""));
            }

            //  set the arguments used by the State object constructor
            object[] args = { spp };


            try
            {
                //  pass to Base class' reflection code
                //  DON'T look for this State in Cache, "CREATE" semantics in this class
                //  demand that we create it freshly...
                //  UNLIKE other Factories, State is stateful and we don't recycle in Create;
                //  instead if the consuming class wishes a Cached entry, they might get it
                //  from Load() methods instead...
                state = (State)GenericFactory.Create(typeSettings, args);
            }
            catch (Exception e)
            {
                throw new ConfigurationException(Resource.ResourceManager.FormatMessage(Resource.Exceptions.RES_ExceptionCantCreateState, typeSettings.Type), e);
            }

            //  create a new Task id
            taskId = Guid.NewGuid();

            //  store the task id into the state object
            state.TaskId = taskId;

            //  return it
            return(state);
        }
Beispiel #27
0
        /// <summary>
        /// Initialize all items
        /// </summary>
        /// <returns>True if there are assignment options</returns>
        internal bool Initialize(IRailwayState railwayState, IStatePersistence statePersistence)
        {
            this.railwayState = railwayState;

            lvLocs.BeginUpdate();
            lvLocs.Items.Clear();

            foreach (var locState in railwayState.LocStates.Where(x => (x.CurrentBlock.Actual == null)).OrderBy(x => x.Description))
            {
                BlockSide    currentBlockEnterSide;
                IBlockState  blockState;
                LocDirection locDirection;
                if (statePersistence.TryGetLocState(railwayState, locState, out blockState, out currentBlockEnterSide, out locDirection))
                {
                    var item = new Item(locState, blockState, currentBlockEnterSide, locDirection);
                    lvLocs.Items.Add(item);
                }
            }

            lvLocs.EndUpdate();
            UpdateButtonState();
            return(lvLocs.Items.Count > 0);
        }
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            // Resolve block.
            var entity = Entity;

            block = (entity.Block != null) ? RailwayState.BlockStates[entity.Block] : null;
            if (block == null)
            {
                return(false);
            }

            // Resolve command station
            var cs = RailwayState.SelectCommandStation(Entity);

            if (cs == null)
            {
                return(false);
            }

            commandStation = cs;
            commandStation.AddSignal(this);
            return(true);
        }
        /// <summary>
        /// Prepare this state for use in a live railway.
        /// Make sure all relevant connections to other state objects are resolved.
        /// </summary>
        /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
        protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
        {
            if (!base.TryPrepareForUse(ui, statePersistence))
            {
                return(false);
            }

            /*var portNames = SerialPort.GetPortNames();
             * if (!portNames.Contains(Entity.ComPortName))
             * {
             *  var portName = ui.ChooseComPortName(this);
             *  if (portNames.Contains(portName))
             *  {
             *      // Now we have an available port name
             *      sender.PortName = portName;
             *  }
             *  else
             *  {
             *      // No available port name provided, we cannot be used.
             *      return false;
             *  }
             * }*/
            return(true);
        }
 /// <summary>
 /// Prepare this state for use in a live railway.
 /// Make sure all relevant connections to other state objects are resolved.
 /// </summary>
 /// <returns>True if the entity is now ready for use in a live railway, false otherwise.</returns>
 protected override bool TryPrepareForUse(IStateUserInterface ui, IStatePersistence statePersistence)
 {
     return(true);
 }
Beispiel #31
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="statePersistenceProvider">A valid state persistence provider.</param>
 public State(IStatePersistence statePersistenceProvider)
 {
     this.Accept(statePersistenceProvider);
 }
Beispiel #32
0
 /// <summary>
 /// The visitor pattern for StatePersistence.
 /// </summary>
 /// <param name="statePersistence">A valid state persistence provider object.</param>
 public void Accept(IStatePersistence statePersistence)
 {
     this._stateVisitor = statePersistence;
 }
Beispiel #33
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="taskId">A task identifier (a GUID associated with the task).</param>
 /// <param name="navigationGraph">A valid navigation graph name.</param>
 /// <param name="currentView">The current view in the navigation graph.</param>
 /// <param name="navigateValue">Used by the controller to determine which view is next.</param>
 /// <param name="statePersistence">A valid state persistence provider.</param>
 public State(Guid taskId, string navigationGraph, string currentView, string navigateValue, IStatePersistence statePersistence)
 {
     this._taskId = taskId;
     this._navigationGraph = navigationGraph;
     this._currentView = currentView;
     this._navigateValue = navigateValue;
     this.Accept(statePersistence);
 }
Beispiel #34
0
        /// <summary>
        /// Creates a State object, loading it from persistence provider.
        /// </summary>
        /// <param name="spp">The state persistence provider.</param>
        /// <param name="typeSettings">The state settings.</param>
        /// <returns>A state instance of the type specified in the configuration file.</returns>
        internal static State Create(IStatePersistence spp, ObjectTypeSettings typeSettings)
        {
            State state = null;
            Guid taskId = Guid.Empty;

            if (typeSettings == null)
                throw new Exception(string.Format("ExceptionStateConfigNotFound"));

            //  set the arguments used by the State object constructor
            object[] args = { spp };

            try
            {
                //  pass to Base class' reflection code
                //  DON'T look for this State in Cache, "CREATE" semantics in this class
                //  demand that we create it freshly...
                //  UNLIKE other Factories, State is stateful and we don't recycle in Create;
                //  instead if the consuming class wishes a Cached entry, they might get it
                //  from Load() methods instead...
                state = (State)GenericFactory.Create(typeSettings, args);
            }
            catch (Exception e)
            {
                throw new ConfigurationErrorsException(string.Format("ExceptionCantCreateState: {0} - {1}.",
                                                                     typeSettings.Type, e.Message));
            }

            //  create a new Task id
            taskId = Guid.NewGuid();

            //  store the task id into the state object
            state.TaskId = taskId;

            //  return it
            return state;
        }
Beispiel #35
0
        /// <summary>
        /// Uses the task ID to explicitly load the state from the provided IStatePersistence instance.
        /// Note that this overload does not attempt to fetch from the cache.
        /// </summary>
        /// <param name="statePersistenceProvider"></param>
        /// <param name="taskId"></param>
        /// <returns></returns>
        internal static State Load(IStatePersistence statePersistenceProvider, Guid taskId)
        {
            State state = statePersistenceProvider.Load(taskId);

            if (state != null)
                state.Accept(statePersistenceProvider);
            else
                throw new Exception(string.Format("ExceptionTaskNotFound: {0}.", taskId));

            return state;
        }