public TypeRepresentation(InstanceState state, int numExportsBoundToInstance, int numStepsToRootType, JST.Expression keyField, JST.Expression typeClassifier, bool undefininedIsNotNull) { State = state; NumExportsBoundToInstance = numExportsBoundToInstance; NumStepsToRootType = numStepsToRootType; KeyField = keyField; TypeClassifier = typeClassifier; UndefininedIsNotNull = undefininedIsNotNull; }
/// <summary> /// Stop subsystem. /// </summary> public void Stop() { if (_state == InstanceState.Started) { OnStop(); _state = InstanceState.Stopped; // ReSharper disable PolymorphicFieldLikeEventInvocation Stopped(this); // ReSharper restore PolymorphicFieldLikeEventInvocation Logger.InfoFormat("Subsystem '{0}' stopped successfully.", GetType().Name); } }
public void Stop() { Debug.Assert(_isCreated == true); if (_isCreated == false) { return; } _state = InstanceState.Ended; _stateChangeEvent.Set(); this.OnStateChanged(); if (Diag.IsAttached == true) { Diag.Instance.OnInstanceStopped(); } this.Destroy(); }
internal static InstanceHistoryBuilder ForExistingInstance( ulong instanceId, InstanceLocator reference, ImageLocator image, InstanceState state, DateTime lastSeen, Tenancies tenancy) { Debug.Assert(!tenancy.IsFlagCombination()); Debug.Assert(state != InstanceState.Deleted); return(new InstanceHistoryBuilder( instanceId, reference, image, state, lastSeen, tenancy)); }
public static HostStatus ToStatus(this InstanceState state) { switch (state.Name) { case "pending": return(Pending); case "running": return(Running); case "shutting-down": return(Terminating); case "terminated": return(Terminated); case "stopping": return(Stopping); case "stopped": return(Stopped); default: throw new Exception("unexpected state:" + state.Name); } }
public static InstanceState Postfix(InstanceState state, ref MoveableBuilding __instance) { List <InstanceState> subSubStates = new List <InstanceState>(); BuildingState buildingState = (BuildingState)state; if (buildingState.subStates != null) { foreach (InstanceState subState in buildingState.subStates) { if (subState != null) { if (subState is BuildingState subBuildingState) { if (subBuildingState.instance != null && subBuildingState.instance.isValid) { BuildingState ss = (BuildingState)subState; MoveableBuilding subInstance = (MoveableBuilding)subBuildingState.instance; subSubStates.Clear(); ushort parent = buildingBuffer[subInstance.id.Building].m_parentBuilding; // Hack to get around Move It's single layer check buildingBuffer[subInstance.id.Building].m_parentBuilding = 0; foreach (Instance subSubInstance in subInstance.subInstances) { if (subSubInstance != null && subSubInstance.isValid) { subSubStates.Add(subSubInstance.GetState()); } } buildingBuffer[subInstance.id.Building].m_parentBuilding = parent; if (subSubStates.Count > 0) { ss.subStates = subSubStates.ToArray(); } } } } } } return(state); }
public void OnSlice() { if (m_Fighters.Count == 0) { FreeInstance(); return; } if (m_State == InstanceState.Fighting && m_Boss.Deleted) { if (m_KickTimer != null) { m_KickTimer.Stop(); } m_KickTimer = Timer.DelayCall(TimeSpan.FromMinutes(15.0), new TimerCallback(Kick)); State = InstanceState.Looting; } }
public void Start(bool debugging) { if (_isCreated == false) { this.Create(); } switch (_state) { case InstanceState.Running: return; case InstanceState.Paused: this.Resume(); return; case InstanceState.Debugging: // TODO: debugger hook on Start() return; case InstanceState.Crashed: // Tried to start after crashing? Should not be allowed! Debug.WriteLine("Tried to Start() after crashing; calling Restart() instead"); this.Restart(); return; case InstanceState.Ended: this.Restart(); return; } if (debugging == true) { //Diag.Instance.WaitUntilAttached(); Diag.Instance.OnInstanceStarted(); } _state = InstanceState.Running; _stateChangeEvent.Set(); this.OnStateChanged(); }
public void AddExistingInstance( ulong instanceId, InstanceLocator reference, ImageLocator image, InstanceState state, DateTime lastSeen, Tenancies tenancy, string serverId, NodeTypeLocator nodeType) { Debug.Assert(!tenancy.IsFlagCombination()); this.instanceBuilders[instanceId] = InstanceHistoryBuilder.ForExistingInstance( instanceId, reference, image, state, lastSeen, tenancy, serverId, nodeType); }
/// <summary> /// Loads the state from the actor. Should be invoked from a context with an actor lock. /// </summary> /// <returns></returns> public async Task LoadAsync() { var state = await host.Actor.StateManager.TryGetStateAsync <ActivityActorState>(STATE_NAME); if (state.HasValue) { instanceOwnerId = state.Value.InstanceOwnerId; instanceId = state.Value.InstanceId; instanceState = state.Value.InstanceState; instanceData = state.Value.InstanceData.ToImmutableDictionary(); instanceMetadata = state.Value.InstanceMetadata.ToImmutableDictionary(); } else { instanceOwnerId = Guid.Empty; instanceId = Guid.Empty; instanceState = InstanceState.Unknown; instanceData = ImmutableDictionary <XName, object> .Empty; instanceMetadata = ImmutableDictionary <XName, object> .Empty; } }
//public ChatNetAdapter chatNetAdapter; public ChatNetAdapterServer() { netServer = new NetworkServer(this); serverChatManager = new ChatManager("server"); InstanceState state = netServer.Launch( NetworkConfig.Instance(). AddressFamily(AddressFamily.InterNetwork). SocketType(SocketType.Stream). Protocol(ProtocolType.Tcp). IP(NetworkConfig.ExtranetServerIPConfigAdress). Port(8324). TimeoutSend(100000). TimeoutRecive(100000). BackLog(100) ).state; Console.WriteLine((state == InstanceState.launch) ? "启动成功,本机IP:" + netServer.sReception.LocalEndPoint.ToString() : "启动失败"); //chatNetAdapter = new ChatNetAdapter(); }
public ChatNetAdapter() { netClient = new NetworkClient(this); chatManager = new ChatManager(NetworkConfig.GetIPAdress); InstanceState state = netClient.Launch( NetworkConfig.Instance(). AddressFamily(AddressFamily.InterNetwork). SocketType(SocketType.Stream). Protocol(ProtocolType.Tcp). IP(NetworkConfig.GetIPAdress). Port(8324). TimeoutSend(1000). TimeoutRecive(1000) ).state; if (netClient.state == InstanceState.launch) { chatManager.user = netClient.clientSocket.LocalEndPoint.ToString(); } Console.WriteLine((state == InstanceState.launch)?"启动成功":"启动失败"); }
public override void LoadFromState(InstanceState state) { if (!(state is SegmentState segmentState)) { return; } ushort segment = id.NetSegment; segmentBuffer[segment].m_startDirection = segmentState.startDirection; segmentBuffer[segment].m_endDirection = segmentState.endDirection; UpdateSegmentBlocks(segment, ref segmentBuffer[segment]); netManager.UpdateNode(segmentBuffer[segment].m_startNode); netManager.UpdateNode(segmentBuffer[segment].m_endNode); treeInfo = segmentState.treeInfo; MoveItTool.NS.SetSegmentModifiers(segment, segmentState); }
public void Destroy() { Debug.Assert(_isCreated == true); if (_isCreated == false) { return; } // Destroy thread _shutDown = true; _stateChangeEvent.Set(); _thread.Interrupt(); _cpu.Stop(); if (_thread.Join(1000) == false) { // Failed to wait, so kill _thread.Abort(); } while (_thread.IsAlive == true) { Thread.Sleep(10); } _thread = null; // Destroy all the components foreach (IComponentInstance component in _instances) { component.Cleanup(); } _instances.Clear(); _audio = null; _bios = null; _cpu = null; _io.Clear(); _video = null; _isCreated = false; _state = InstanceState.Idle; this.OnStateChanged(); }
private void FreeInstance() { if (m_Boss != null) { m_Boss.Delete(); m_Boss = null; } if (m_SliceTimer != null) { m_SliceTimer.Stop(); } if (m_KickTimer != null) { m_KickTimer.Stop(); } State = InstanceState.Available; m_Owner.OnFreeInstance(this); }
public Instance(string i_ID, InstanceState i_State) { //查找元素 Instance tem_instance = null; foreach (Instance tem in GameValue.Instances) { if (i_ID == tem.ID) { tem_instance = tem; break; } } //属性赋值 ID = i_ID; Name = tem_instance.Name; AppendMonster = tem_instance.AppendMonster; State = i_State; MonsterAppendTotal = tem_instance.MonsterAppendTotal; Info = tem_instance.Info; PP = tem_instance.PP; }
private InstanceState GetInstanceState() { BinaryFormatter formatter = new BinaryFormatter(); InstanceState returnedInstanceState = new InstanceState(true, null); bool stateFileNotExists = true; using (FileStream fStream = new FileStream(_stateFilePath, FileMode.OpenOrCreate)) { if (fStream.Length != 0 && formatter.Deserialize(fStream) is InstanceState) { fStream.Position = 0; returnedInstanceState = formatter.Deserialize(fStream) as InstanceState; stateFileNotExists = false; } } if (stateFileNotExists) { SaveInstanceState(); } return(returnedInstanceState); }
//--------------------------------------------------------------------- // Ctor //--------------------------------------------------------------------- private InstanceHistoryBuilder( ulong instanceId, InstanceLocator reference, ImageLocator image, InstanceState state, DateTime?lastSeen, Tenancies tenancy, string serverId, NodeTypeLocator nodeType) { Debug.Assert(!tenancy.IsFlagCombination()); Debug.Assert(tenancy == Tenancies.SoleTenant || (serverId == null && nodeType == null)); if (instanceId == 0) { throw new ArgumentException("Instance ID cannot be 0"); } this.InstanceId = instanceId; this.reference = reference; this.image = image; this.lastStoppedOn = lastSeen; if (state == InstanceState.Running) { Debug.Assert(tenancy != Tenancies.Unknown); Debug.Assert(lastSeen != null); AddPlacement(new InstancePlacement( tenancy, serverId, nodeType, lastSeen.Value, lastSeen.Value)); } }
public static void Postfix(InstanceState state, MoveableBuilding __instance) { if (!(state is BuildingState buildingState)) { return; } //Debug.Log($"SS0 - {buildingState.subStates}"); if (buildingState.subStates != null) { foreach (InstanceState subState in buildingState.subStates) { if (subState != null) { if (subState is BuildingState subBuildingState) { if (subBuildingState.instance != null && subBuildingState.instance.isValid) { BuildingState ss = (BuildingState)subState; MoveableBuilding subInstance = (MoveableBuilding)subBuildingState.instance; if (ss.subStates != null) { foreach (InstanceState subSubState in ss.subStates) { if (subSubState != null) { subSubState.instance.SetState(subSubState); } } } } } } } } }
public async Task <IActionResult> PostHerosLocations([FromBody] PassedGameData <int?> passedData) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } DateTime now = DateTime.UtcNow; if (passedData.UserToken == null || passedData.ActionToken == null) { return(BadRequest(new DataError("securityErr", "No authorization controll."))); } UserToken dbtoken = Security.CheckUserToken(this._context, passedData.UserToken); if (dbtoken == null) { return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change."))); } else { if (!dbtoken.IsTimeValid(now)) { return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required."))); } else { dbtoken.UpdateToken(now); } } Heros hero = _context.Heros.FirstOrDefault(e => e.Name == passedData.ActionToken.HeroName); ActionToken gametoken = Security.CheckActionToken(_context, passedData.ActionToken, hero.HeroId); if (gametoken == null) { return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change."))); } else { if (!gametoken.IsTimeValid(now)) { return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required."))); } else { gametoken.UpdateToken(now); } } try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { return(BadRequest(new DataError("databaseErr", "Failed to update tokens."))); } // can load location status - update status -> function (?) var location = _context.HerosLocations.FirstOrDefault(e => (e.HeroId == hero.HeroId) && (e.LocationIdentifier == hero.CurrentLocation)); if (location == null) { return(BadRequest(new DataError("LocationErr", "Location is not available."))); } var descr = _context.LocationsDb.FirstOrDefault(e => e.LocationIdentifier == location.LocationIdentifier); if (descr == null) { return(BadRequest(new DataError("LocationErr", "LocationData is not available."))); } try { // TODO check location type -> vitual class or what? int LocationType = descr.LocationGlobalType; if (LocationType != 2) { LocationDescription description = JsonConvert.DeserializeObject <LocationDescription>(descr.Sketch); LocationState state = JsonConvert.DeserializeObject <LocationState>(location.Description); description.LocationGlobalType = LocationType; if (hero.Status == 1) { Traveling travel = _context.Traveling.FirstOrDefault(e => e.HeroId == hero.HeroId); if (travel == null) { throw new Exception("Traveling hero without travel in DB."); } if (travel.HasEnded(now)) { state = description.MoveTo(travel.UpdatedLocationID(), state); hero.Status = 0; location.Description = JsonConvert.SerializeObject(state); _context.Traveling.Remove(travel); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { return(BadRequest(new DataError("databaseErr", "Failed to remove travel."))); } LocationResult <MainNodeResult> locationResult = description.GenLocalForm(state); return(Ok(new { success = true, location = locationResult })); } else { return(BadRequest(new DataError("LocationErr", "Travel is not finished"))); } } else { return(BadRequest(new DataError("LocationErr", "Hero is not in travel mode"))); } } else { InstanceDescription description = JsonConvert.DeserializeObject <InstanceDescription>(descr.Sketch); InstanceState state = JsonConvert.DeserializeObject <InstanceState>(location.Description); description.LocationGlobalType = LocationType; if (hero.Status == 1) { Traveling travel = _context.Traveling.FirstOrDefault(e => e.HeroId == hero.HeroId); if (travel == null) { throw new Exception("Traveling hero without travel in DB."); } if (travel.HasEnded(now)) { state = description.MoveTo(travel.UpdatedLocationID(), state); hero.Status = 0; location.Description = JsonConvert.SerializeObject(state); _context.Traveling.Remove(travel); try { await _context.SaveChangesAsync(); } catch (DbUpdateException) { return(BadRequest(new DataError("databaseErr", "Failed to remove travel."))); } LocationResult <InstanceNodeResult> locationResult = description.GenLocalForm(state); return(Ok(new { success = true, location = locationResult })); } else { return(BadRequest(new DataError("LocationErr", "Travel is not finished"))); } } else { return(BadRequest(new DataError("LocationErr", "Hero is not in travel mode"))); } } } catch { return(BadRequest(new DataError("LocationErr", "Location is not available."))); } }
protected override void PaintModel(IPaintbrush pb) { repainter.NotifyRepainted(); LayoutModel layoutModel = this.Layout; LayoutSimulation layoutSim = this.LayoutSim; if (layoutModel == null) { return; } if (layoutSim.LayoutModel != layoutModel) { Console.Error.WriteLine("layoutSim and layoutModel do not match"); return; } ComponentPainter ip = new ComponentPainter(pb, null); bool noHidden = hidden.Count == 0; Transaction xn = new Transaction(); ISimulationAccess sim = xn.RequestReadAccess(layoutSim.SimulationModel); ILayoutAccess layout = xn.RequestReadAccess(layoutModel); using (xn.Start()) { using (IPaintbrush pbSub = pb.Create()) { pbSub.StrokeWidth = Constants.WIRE_WIDTH; foreach (WireSegment wire in layout.Wires) { Value val0 = layoutSim.GetValueAt(layout, sim, wire.End0); pbSub.Color = Constants.GetColorFor(val0); pbSub.StrokeLine(wire.End0.X, wire.End0.Y, wire.End1.X, wire.End1.Y); } } InstanceState state = new InstanceState(sim, null); ip.InstanceState = state; foreach (Component component in layout.Components) { if (noHidden || !hidden.Contains(component)) { Location loc = component.GetLocation(layout); using (IPaintbrush pbSub = pb.Create()) { pbSub.TranslateCoordinates(loc.X, loc.Y); ip.Paintbrush = pbSub; state.Instance = layoutSim.GetInstance(layout, component); component.Paint(ip); } } } using (IPaintbrush pbSub = pb.Create()) { foreach (Location loc in WiringPoints.SolderPoints) { Value val = layoutSim.GetValueAt(layout, sim, loc); pbSub.Color = Constants.GetColorFor(val); if (noHidden || WiringPoints.IsSolderPoint(loc, hidden)) { pbSub.FillCircle(loc.X, loc.Y, Constants.SOLDER_RADIUS); } } } } }
public void Activate() { State = InstanceState.Reserved; Timer.DelayCall( TimeSpan.FromMinutes( 1.0 ), new TimerCallback( StartFight ) ); }
public void OnDescendantUpdated(IInstanceBuilderContext context, ViewNode viewNode, ViewNode child, InstanceState childState) { this.builder.OnDescendantUpdated(context, viewNode, child, childState); }
public void LoadedInstance(InstanceState state, IDictionary<XName, InstanceValue> instanceData, IDictionary<XName, InstanceValue> instanceMetadata, IDictionary<Guid, IDictionary<XName, InstanceValue>> associatedInstanceKeyMetadata, IDictionary<Guid, IDictionary<XName, InstanceValue>> completedInstanceKeyMetadata) { if (state == InstanceState.Uninitialized) { if (instanceData != null && instanceData.Count > 0) { throw Fx.Exception.AsError(new InvalidOperationException(SRCore.UninitializedCannotHaveData)); } } else if (state == InstanceState.Completed) { if (associatedInstanceKeyMetadata != null && associatedInstanceKeyMetadata.Count > 0) { throw Fx.Exception.AsError(new InvalidOperationException(SRCore.CompletedMustNotHaveAssociatedKeys)); } } else if (state != InstanceState.Initialized) { throw Fx.Exception.Argument("state", SRCore.InvalidInstanceState); } ThrowIfNoInstance(); ThrowIfNotActive("PersistedInstance"); InstanceValueConsistency consistency = InstanceView.IsBoundToLock || state == InstanceState.Completed ? InstanceValueConsistency.None : InstanceValueConsistency.InDoubt; ReadOnlyDictionaryInternal<XName, InstanceValue> instanceDataCopy = instanceData.ReadOnlyCopy(false); ReadOnlyDictionaryInternal<XName, InstanceValue> instanceMetadataCopy = instanceMetadata.ReadOnlyCopy(false); Dictionary<Guid, InstanceKeyView> keysCopy = null; int totalKeys = (associatedInstanceKeyMetadata != null ? associatedInstanceKeyMetadata.Count : 0) + (completedInstanceKeyMetadata != null ? completedInstanceKeyMetadata.Count : 0); if (totalKeys > 0) { keysCopy = new Dictionary<Guid, InstanceKeyView>(totalKeys); } if (associatedInstanceKeyMetadata != null && associatedInstanceKeyMetadata.Count > 0) { foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> keyMetadata in associatedInstanceKeyMetadata) { InstanceKeyView view = new InstanceKeyView(keyMetadata.Key); view.InstanceKeyState = InstanceKeyState.Associated; view.InstanceKeyMetadata = keyMetadata.Value.ReadOnlyCopy(false); view.InstanceKeyMetadataConsistency = InstanceView.IsBoundToLock ? InstanceValueConsistency.None : InstanceValueConsistency.InDoubt; keysCopy.Add(view.InstanceKey, view); } } if (completedInstanceKeyMetadata != null && completedInstanceKeyMetadata.Count > 0) { foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> keyMetadata in completedInstanceKeyMetadata) { InstanceKeyView view = new InstanceKeyView(keyMetadata.Key); view.InstanceKeyState = InstanceKeyState.Completed; view.InstanceKeyMetadata = keyMetadata.Value.ReadOnlyCopy(false); view.InstanceKeyMetadataConsistency = consistency; keysCopy.Add(view.InstanceKey, view); } } InstanceView.InstanceState = state; InstanceView.InstanceData = instanceDataCopy; InstanceView.InstanceDataConsistency = consistency; InstanceView.InstanceMetadata = instanceMetadataCopy; InstanceView.InstanceMetadataConsistency = consistency; InstanceView.InstanceKeys = keysCopy == null ? null : new ReadOnlyDictionaryInternal<Guid, InstanceKeyView>(keysCopy); InstanceView.InstanceKeysConsistency = consistency; }
public bool Create() { Debug.Assert(_isCreated == false); if (_isCreated == true) { return(true); } _shutDown = false; _state = InstanceState.Idle; // Try to create all the components Debug.Assert(_params.BiosComponent != null); Debug.Assert(_params.CpuComponent != null); if (_params.AudioComponent != null) { _audio = _params.AudioComponent.CreateInstance(this, _params[_params.AudioComponent]) as IAudioDriver; _instances.Add(( IComponentInstance )_audio); } _cpu = _params.CpuComponent.CreateInstance(this, _params[_params.CpuComponent]) as ICpu; _instances.Add(( IComponentInstance )_cpu); _bios = _params.BiosComponent.CreateInstance(this, _params[_params.BiosComponent]) as IBios; _instances.Add(( IComponentInstance )_bios); foreach (IComponent component in _params.IOComponents) { IIODriver driver = component.CreateInstance(this, _params[component]) as IIODriver; _io.Add(driver); _instances.Add(( IComponentInstance )driver); } if (_params.InputComponent != null) { _input = _params.InputComponent.CreateInstance(this, _params[_params.InputComponent]) as IInputDevice; _instances.Add(_input); //_input.WindowHandle = _host.Player.Handle; } if (_params.UmdComponent != null) { _umd = _params.UmdComponent.CreateInstance(this, _params[_params.UmdComponent]) as IUmdDevice; _instances.Add(_umd); } if (_params.MemoryStickComponent != null) { _memoryStick = _params.MemoryStickComponent.CreateInstance(this, _params[_params.MemoryStickComponent]) as IMemoryStickDevice; _instances.Add(_memoryStick); } if (_params.VideoComponent != null) { _video = _params.VideoComponent.CreateInstance(this, _params[_params.VideoComponent]) as IVideoDriver; //_video.ControlHandle = _host.Player.ControlHandle; _instances.Add(( IComponentInstance )_video); } // Create thread _thread = new Thread(new ThreadStart(this.RuntimeThread)); _thread.Name = "Host runtime thread"; _thread.IsBackground = true; _thread.Start(); _isCreated = true; return(true); }
protected virtual void Initialize() { State = InstanceState.Available; m_Fighters = new List<Mobile>(); m_Region = new InstanceRegion( this ); }
public void Resume() { Debug.Assert( _isCreated == true ); if( _isCreated == false ) return; if( _state != InstanceState.Paused ) return; _state = InstanceState.Running; _stateChangeEvent.Set(); this.OnStateChanged(); }
public void Stop() { Debug.Assert( _isCreated == true ); if( _isCreated == false ) return; _state = InstanceState.Ended; _stateChangeEvent.Set(); this.OnStateChanged(); if( Diag.IsAttached == true ) Diag.Instance.OnInstanceStopped(); this.Destroy(); }
public bool Create() { Debug.Assert( _isCreated == false ); if( _isCreated == true ) return true; _shutDown = false; _state = InstanceState.Idle; // Try to create all the components Debug.Assert( _params.BiosComponent != null ); Debug.Assert( _params.CpuComponent != null ); if( _params.AudioComponent != null ) { _audio = _params.AudioComponent.CreateInstance( this, _params[ _params.AudioComponent ] ) as IAudioDriver; _instances.Add( ( IComponentInstance )_audio ); } _cpu = _params.CpuComponent.CreateInstance( this, _params[ _params.CpuComponent ] ) as ICpu; _instances.Add( ( IComponentInstance )_cpu ); _bios = _params.BiosComponent.CreateInstance( this, _params[ _params.BiosComponent ] ) as IBios; _instances.Add( ( IComponentInstance )_bios ); foreach( IComponent component in _params.IOComponents ) { IIODriver driver = component.CreateInstance( this, _params[ component ] ) as IIODriver; _io.Add( driver ); _instances.Add( ( IComponentInstance )driver ); } if( _params.InputComponent != null ) { _input = _params.InputComponent.CreateInstance( this, _params[ _params.InputComponent ] ) as IInputDevice; _instances.Add( _input ); _input.WindowHandle = _host.Player.Handle; } if( _params.UmdComponent != null ) { _umd = _params.UmdComponent.CreateInstance( this, _params[ _params.UmdComponent ] ) as IUmdDevice; _instances.Add( _umd ); } if( _params.MemoryStickComponent != null ) { _memoryStick = _params.MemoryStickComponent.CreateInstance( this, _params[ _params.MemoryStickComponent ] ) as IMemoryStickDevice; _instances.Add( _memoryStick ); } if( _params.VideoComponent != null ) { _video = _params.VideoComponent.CreateInstance( this, _params[ _params.VideoComponent ] ) as IVideoDriver; _video.ControlHandle = _host.Player.ControlHandle; _instances.Add( ( IComponentInstance )_video ); } #if XMB _xmb = new CrossMediaBar.Manager( this, _host.Player.Handle, _host.Player.ControlHandle ); #else #endif // Create thread _thread = new Thread( new ThreadStart( this.RuntimeThread ) ); _thread.Name = "Host runtime thread"; _thread.IsBackground = true; _thread.Start(); _isCreated = true; return true; }
private void EmitImporterExporter(Seq<JST.Statement> body, JST.Expression lhs, InstanceState state) { if (!(state == InstanceState.ManagedOnly && TypeCompEnv.Type.Style is CST.ClassTypeStyle)) { body.Add(JST.Statement.DotAssignment(lhs, Constants.TypeImport, TypeImporterFunction(state))); body.Add(JST.Statement.DotAssignment(lhs, Constants.TypeExport, TypeExporterFunction(state))); } // else: default importer/exporter for 'ManagedOnly' reference types is ok }
private JST.Expression TypeExporterFunction(InstanceState state) { var s = TypeCompEnv.Type.Style; if (s is CST.VoidTypeStyle) return JST.Expression.DotCall(RootId.ToE(), Constants.RootInvalidExporter, TypeId.ToE()); else if (s is CST.NullableTypeStyle) return JST.Expression.DotCall(RootId.ToE(), Constants.RootNullableExporter, TypeId.ToE()); else if (s is CST.ManagedPointerTypeStyle) return JST.Expression.DotCall(RootId.ToE(), Constants.RootPointerExporter, TypeId.ToE()); else if (s is CST.ArrayTypeStyle) return JST.Expression.DotCall(RootId.ToE(), Constants.RootArrayExporter, TypeId.ToE()); else if (s is CST.DelegateTypeStyle) return DelegateImporterExporter(false); else if (s is CST.HandleTypeStyle) return Identity(); else if (s is CST.ValueTypeStyle) return JST.Expression.DotCall(RootId.ToE(), Constants.RootValueExporter, TypeId.ToE()); else { switch (state) { case InstanceState.ManagedOnly: return JST.Expression.DotCall(RootId.ToE(), Constants.RootManagedOnlyExporter, TypeId.ToE()); case InstanceState.ManagedAndJavaScript: return JST.Expression.DotCall (RootId.ToE(), Constants.RootManagedAndJavaScriptExporter, TypeId.ToE()); case InstanceState.JavaScriptOnly: return JST.Expression.DotCall(RootId.ToE(), Constants.RootJavaScriptOnlyExporter, TypeId.ToE()); case InstanceState.Merged: return JST.Expression.DotCall(RootId.ToE(), Constants.RootMergedExporter, TypeId.ToE()); default: throw new ArgumentOutOfRangeException(); } } }
public void Init() { _instanceState = InstanceState.Initializing; var targetSystemEventsTriggersList = _triggersResolver.ResolveSystemEventsTriggersList(KindOfSystemEventOfInlineTrigger.Init, Name, _localCodeExecutionContext, ResolverOptions.GetDefaultOptions()); #if DEBUG //Log($"targetSystemEventsTriggersList = {targetSystemEventsTriggersList.WriteListToString()}"); #endif if (targetSystemEventsTriggersList.Any()) { targetSystemEventsTriggersList.Reverse(); var processInitialInfoList = new List <ProcessInitialInfo>(); foreach (var targetTrigger in targetSystemEventsTriggersList) { var localCodeExecutionContext = new LocalCodeExecutionContext(); var localStorageSettings = RealStorageSettingsHelper.Create(_context, _storage); localCodeExecutionContext.Storage = new LocalStorage(localStorageSettings); localCodeExecutionContext.Holder = Name; var processInitialInfo = new ProcessInitialInfo(); processInitialInfo.CompiledFunctionBody = targetTrigger.ResultItem.CompiledFunctionBody; processInitialInfo.LocalContext = localCodeExecutionContext; processInitialInfo.Metadata = targetTrigger.ResultItem.CodeEntity; processInitialInfoList.Add(processInitialInfo); } #if DEBUG //Log($"processInitialInfoList = {processInitialInfoList.WriteListToString()}"); #endif var taskValue = _context.CodeExecutor.ExecuteBatchAsync(processInitialInfoList); #if DEBUG //Log($"taskValue = {taskValue}"); #endif } var targetLogicConditionalTriggersList = _triggersResolver.ResolveLogicConditionalTriggersList(Name, _localCodeExecutionContext, ResolverOptions.GetDefaultOptions()); #if DEBUG //Log($"targetLogicConditionalTriggersList = {targetLogicConditionalTriggersList.WriteListToString()}"); #endif if (targetLogicConditionalTriggersList.Any()) { foreach (var targetTrigger in targetLogicConditionalTriggersList) { #if DEBUG //Log($"targetTrigger = {targetTrigger}"); #endif var triggerInstanceInfo = new LogicConditionalTriggerInstanceInfo(targetTrigger.ResultItem, this, _context, _storage); _logicConditionalTriggersList.Add(triggerInstanceInfo); } } _instanceState = InstanceState.Initialized; }
public void LoadedInstance(InstanceState state, IDictionary<XName, InstanceValue> instanceData, IDictionary<XName, InstanceValue> instanceMetadata, IDictionary<Guid, IDictionary<XName, InstanceValue>> associatedInstanceKeyMetadata, IDictionary<Guid, IDictionary<XName, InstanceValue>> completedInstanceKeyMetadata) { if (state == InstanceState.Uninitialized) { if ((instanceData != null) && (instanceData.Count > 0)) { throw Fx.Exception.AsError(new InvalidOperationException(SRCore.UninitializedCannotHaveData)); } } else if (state == InstanceState.Completed) { if ((associatedInstanceKeyMetadata != null) && (associatedInstanceKeyMetadata.Count > 0)) { throw Fx.Exception.AsError(new InvalidOperationException(SRCore.CompletedMustNotHaveAssociatedKeys)); } } else if (state != InstanceState.Initialized) { throw Fx.Exception.Argument("state", SRCore.InvalidInstanceState); } this.ThrowIfNoInstance(); this.ThrowIfNotActive("PersistedInstance"); InstanceValueConsistency consistency = (this.InstanceView.IsBoundToLock || (state == InstanceState.Completed)) ? InstanceValueConsistency.None : InstanceValueConsistency.InDoubt; ReadOnlyDictionary<XName, InstanceValue> dictionary = instanceData.ReadOnlyCopy(false); ReadOnlyDictionary<XName, InstanceValue> dictionary2 = instanceMetadata.ReadOnlyCopy(false); Dictionary<Guid, InstanceKeyView> dictionary3 = null; int capacity = ((associatedInstanceKeyMetadata != null) ? associatedInstanceKeyMetadata.Count : 0) + ((completedInstanceKeyMetadata != null) ? completedInstanceKeyMetadata.Count : 0); if (capacity > 0) { dictionary3 = new Dictionary<Guid, InstanceKeyView>(capacity); } if ((associatedInstanceKeyMetadata != null) && (associatedInstanceKeyMetadata.Count > 0)) { foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> pair in associatedInstanceKeyMetadata) { InstanceKeyView view = new InstanceKeyView(pair.Key) { InstanceKeyState = InstanceKeyState.Associated, InstanceKeyMetadata = pair.Value.ReadOnlyCopy(false), InstanceKeyMetadataConsistency = this.InstanceView.IsBoundToLock ? InstanceValueConsistency.None : InstanceValueConsistency.InDoubt }; dictionary3.Add(view.InstanceKey, view); } } if ((completedInstanceKeyMetadata != null) && (completedInstanceKeyMetadata.Count > 0)) { foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> pair2 in completedInstanceKeyMetadata) { InstanceKeyView view2 = new InstanceKeyView(pair2.Key) { InstanceKeyState = InstanceKeyState.Completed, InstanceKeyMetadata = pair2.Value.ReadOnlyCopy(false), InstanceKeyMetadataConsistency = consistency }; dictionary3.Add(view2.InstanceKey, view2); } } this.InstanceView.InstanceState = state; this.InstanceView.InstanceData = dictionary; this.InstanceView.InstanceDataConsistency = consistency; this.InstanceView.InstanceMetadata = dictionary2; this.InstanceView.InstanceMetadataConsistency = consistency; this.InstanceView.InstanceKeys = (dictionary3 == null) ? null : new ReadOnlyDictionary<Guid, InstanceKeyView>(dictionary3, false); this.InstanceView.InstanceKeysConsistency = consistency; }
/// <summary> /// Set the instance state /// </summary> /// <param name="instanceId">Instance Id</param> /// <param name="userId">User Id</param> /// <param name="instanceState">Instance state</param> /// <returns></returns> private async Task <Instance> SetInstanceState(string instanceId, string userId, InstanceState instanceState) { logger.LogDebug($"Searching the instance by Id {instanceId}, userId {userId} and NOT in terminated state"); Instance instance = instanceDbContext.Instances .Where(i => i.Id == instanceId && i.UserId == userId && i.InstanceState != InstanceState.TERMINATED) .FirstOrDefault(); if (instance == null) { throw new InstanceException($"Cannot find instance {instanceId}"); } logger.LogDebug($"Try to set the state {instanceState} to the instance {instanceId}"); instance.InstanceState = instanceState; await instanceDbContext.SaveChangesAsync(); logger.LogDebug($"instance state {instanceState} successfully changed for {instanceId}"); return(instance); }
public void SetInstanceActivityGrid() { GrdActivity.EditIndex = -1; bool isPrint = false; if (Page.Request.Path.IndexOf("Print", StringComparison.CurrentCultureIgnoreCase) > 0) { //print mode isPrint = true; } InstanceProcessTemplate instanceTemplate = new InstanceProcessTemplate(); DataSet ds = instanceTemplate.GetInstanceProcess(ApplicationID, ProcessID, InstanceID, DBSetting.MultiLanguageSuffix); InstanceProcess instprocess = new InstanceProcess(ApplicationID, ProcessID, InstanceID); CurrentStateID = instprocess.GetCurrentStateID(); InstanceState ins = new InstanceState(ApplicationID, InstanceID); RM rm = new RM(ResourceFile.Msg); //int EditIndex = -1; int assignTo = instanceTemplate.GetAssignTo(ApplicationID, InstanceID); GrdActivity.DataSource = ds; if (!isPrint) { //以下部分需要判断是否是处在用户自定义流程状态,如果是,则只允许在未定义流程管理页面进行操作 //但需要注意,如果当前状态是用户自定义流程状态,有可能被Hold了,此时在未定义流程管理页面也不允许进行流程操作, //也不需要添加指示未定义流程操作的行 if (instprocess.CheckActionPermission(CurrentUser.UserID)) { DataRow[] drs = ds.Tables[0].Select("P_Level=1"); if (drs.Length > 0) { if (Fn.ToInt(drs[0]["from_state_id"]) != CurrentStateID) { throw new Exception("State error. Please contact with administrator."); } GrdActivity.EditIndex = ds.Tables[0].Rows.IndexOf(drs[0]); //if (CurrentStateID == State.GetStateID(UserDefineProcess.RedefineStateCode)) //{ // drs[0]["Operator_name"] = rm["ToBeRedefine"]; // EditIndex = GrdActivity.EditIndex; // GrdActivity.EditIndex = -1; //} } } //if (CurrentStateID == State.GetStateID(UserDefineProcess.RedefineStateCode)) //{ // if (assignTo == 0) //刚执行了用户重定义流程操作 // { // DataRow dr = ds.Tables[0].NewRow(); // dr["Operator_name"] = rm["ToBeRedefine"]; // ds.Tables[0].Rows.Add(dr); // if (IsAdminPage) // { // GrdActivity.EditIndex = ds.Tables[0].Rows.Count - 1; // } // } // else if (assignTo > 0) // { // if (EditIndex != -1) // { // if (IsAdminPage) // { // GrdActivity.EditIndex = EditIndex; // } // } // else // { // ds.Tables[0].Rows[ds.Tables[0].Rows.Count - 1]["Operator_name"] = rm["ToBeRedefine"]; // } // } //} } GrdActivity.DataBind(); if (GrdActivity.EditIndex > -1) { SetOperationRadioList(); } }
public void Destroy() { Debug.Assert( _isCreated == true ); if( _isCreated == false ) return; // Destroy thread _shutDown = true; _stateChangeEvent.Set(); _thread.Interrupt(); _cpu.Stop(); if( _thread.Join( 1000 ) == false ) { // Failed to wait, so kill _thread.Abort(); } while( _thread.IsAlive == true ) Thread.Sleep( 10 ); _thread = null; #if XMB // Destroy XMB _xmb.Cleanup(); _xmb = null; #else #endif // Destroy all the components foreach( IComponentInstance component in _instances ) { if( component != null ) component.Cleanup(); } _instances.Clear(); _audio = null; _bios = null; _cpu = null; _io.Clear(); _video = null; _isCreated = false; _state = InstanceState.Idle; this.OnStateChanged(); }
/// <summary> /// Call made by the job execution to broadcast an update of state and item progress. /// </summary> /// <param name="state">The state of the job.</param> /// <param name="categories">The progress of the job.</param> public Task UpdateState(InstanceState state, params ItemProgress[] categories) => SendPriorityAsync(nameof(UpdateState), state, (IEnumerable <ItemProgress>)categories);
public void Start( bool debugging ) { if( _isCreated == false ) this.Create(); switch( _state ) { case InstanceState.Running: return; case InstanceState.Paused: this.Resume(); return; case InstanceState.Debugging: // TODO: debugger hook on Start() return; case InstanceState.Crashed: // Tried to start after crashing? Should not be allowed! Debug.WriteLine( "Tried to Start() after crashing; calling Restart() instead" ); this.Restart(); return; case InstanceState.Ended: this.Restart(); return; } if( debugging == true ) { //Diag.Instance.WaitUntilAttached(); Diag.Instance.OnInstanceStarted(); } _state = InstanceState.Running; _stateChangeEvent.Set(); this.OnStateChanged(); }
public void LoadedInstance(InstanceState state, IDictionary <XName, InstanceValue> instanceData, IDictionary <XName, InstanceValue> instanceMetadata, IDictionary <Guid, IDictionary <XName, InstanceValue> > associatedInstanceKeyMetadata, IDictionary <Guid, IDictionary <XName, InstanceValue> > completedInstanceKeyMetadata) { throw new NotImplementedException(); }
private void Init() { _state = GetInstanceState(); }
private void StartFight() { State = InstanceState.Fighting; m_Boss = Activator.CreateInstance( m_Owner.BossType ) as Mobile; m_Boss.OnBeforeSpawn( m_BossSpawnLocation, m_Owner.Map ); m_Boss.MoveToWorld( m_BossSpawnLocation, m_Owner.Map ); m_SliceTimer = new SliceTimer( this ); m_SliceTimer.Start(); m_KickTimer = Timer.DelayCall( TimeSpan.FromHours( 2.0 ), new TimerCallback( Kick ) ); }
/// <summary> /// Query the Visual Studio setup API to get instances of Visual Studio installed /// on the machine. Will not include anything before Visual Studio "15". /// </summary> /// <returns>Enumerable list of Visual Studio instances</returns> internal static IList <VisualStudioInstance> GetInstances() { var validInstances = new List <VisualStudioInstance>(); try { // This code is not obvious. See the sample (link above) for reference. var query = (ISetupConfiguration2)GetQuery(); var e = query.EnumAllInstances(); int fetched; var instances = new ISetupInstance[1]; do { // Call e.Next to query for the next instance (single item or nothing returned). e.Next(1, instances, out fetched); if (fetched <= 0) { continue; } var instance = (ISetupInstance2)instances[0]; InstanceState state = instance.GetState(); if (!Version.TryParse(instance.GetInstallationVersion(), out Version version)) { continue; } // If the install was complete and a valid version, consider it. if (state == InstanceState.Complete || (state.HasFlag(InstanceState.Registered) && state.HasFlag(InstanceState.NoRebootRequired))) { bool instanceHasMSBuild = false; foreach (ISetupPackageReference package in instance.GetPackages()) { if (string.Equals(package.GetId(), "Microsoft.Component.MSBuild", StringComparison.OrdinalIgnoreCase)) { instanceHasMSBuild = true; break; } } if (instanceHasMSBuild) { validInstances.Add(new VisualStudioInstance( instance.GetDisplayName(), instance.GetInstallationPath(), version, DiscoveryType.VisualStudioSetup)); } } } while (fetched > 0); } catch (COMException) { } catch (DllNotFoundException) { // This is OK, VS "15" or greater likely not installed. } return(validInstances); }
private void FreeInstance() { if ( m_Boss != null ) { m_Boss.Delete(); m_Boss = null; } if ( m_SliceTimer != null ) m_SliceTimer.Stop(); if ( m_KickTimer != null ) m_KickTimer.Stop(); State = InstanceState.Available; m_Owner.OnFreeInstance( this ); }
// NOTE: May be called on invalid definitions // See also: InlinedMethodCache::PrimIsInlinable public bool IsInlinable(CST.AssemblyDef assemblyDef, CST.TypeDef typeDef, CST.MethodDef methodDef, InstanceState state) { if (!env.InlinedMethods.CouldBeInlinableBasedOnHeaderAlone(assemblyDef, typeDef, methodDef)) return false; if (methodDef.IsStatic && methodDef.IsConstructor) // Static constructors are invoked by type initializers return false; if (!IsImported(assemblyDef, typeDef, methodDef)) // Not an imported method return false; if (!methodDef.IsStatic && methodDef.IsConstructor) { // Instance constructors need too much surrounding logic to be worth inlining, // but constructors for 'Merged' types must be inlined return state == InstanceState.Merged; } var outer = typeDef.OuterPropertyOrEvent(methodDef.MethodSignature); if (outer != null && outer.Flavor == CST.MemberDefFlavor.Event) // Event adders/removers need too much surrounding logic to be worth inlining return false; var isInline = default(bool); if (env.AttributeHelper.GetValueFromMethod (assemblyDef, typeDef, methodDef, env.AttributeHelper.InlineAttributeRef, env.AttributeHelper.TheIsInlinedProperty, true, false, ref isInline)) // User has specified whether or not to inline, which overrides size-based determination return isInline; var script = default(JST.Expression); attributeHelper.GetValueFromMethod (assemblyDef, typeDef, methodDef, attributeHelper.ImportAttributeRef, attributeHelper.TheScriptProperty, true, false, ref script); // Use script size, even though actual function size may be a bit larger after adjusting for // various import flavors return script == null || script.Size <= env.ImportInlineThreshold; }
public void OnSlice() { if ( m_Fighters.Count == 0 ) { FreeInstance(); return; } if ( m_State == InstanceState.Fighting && m_Boss.Deleted ) { if ( m_KickTimer != null ) m_KickTimer.Stop(); m_KickTimer = Timer.DelayCall( TimeSpan.FromMinutes( 15.0 ), new TimerCallback( Kick ) ); State = InstanceState.Looting; } }
public void Activate() { State = InstanceState.Reserved; Timer.DelayCall(TimeSpan.FromMinutes(1.0), new TimerCallback(StartFight)); }
public virtual NetworkInstance Launch(NetworkConfig config) { state = InstanceState.launch; dataConfig = config; return(this); }
/// <summary> /// Call made by the job execution to broadcast an update of state and item progress. /// </summary> /// <param name="state">The state of the job.</param> /// <param name="categories">The progress of the job.</param> public Task UpdateState(InstanceState state, IEnumerable <ItemProgress> categories) => SendPriorityAsync(nameof(UpdateState), state, categories.ToArray());
public void LoadedInstance (InstanceState state, IDictionary<XName, InstanceValue> instanceData, IDictionary<XName, InstanceValue> instanceMetadata, IDictionary<Guid, IDictionary<XName, InstanceValue>> associatedInstanceKeyMetadata, IDictionary<Guid, IDictionary<XName, InstanceValue>> completedInstanceKeyMetadata) { throw new NotImplementedException (); }