public SessionInfo() { id = 0; lapsTotal = 0; lapsComplete = 0; leadChanges = 0; cautions = 0; cautionLaps = 0; fastestlap = 0; fastestdriver = new DriverInfo(); fastestlapnum = 0; time = 0; sessiontimeremaining = 0; sessionlength = 0; sessionstarttime = -1; sessionstartpos = 0; finishline = Int32.MaxValue; type = SessionTypes.none; state = SessionStates.invalid; flag = SessionFlags.invalid; startlight = SessionStartLights.off; standings = new ObservableCollection <StandingsItem>(); followedDriver = new StandingsItem(); }
internal bool Connect() { bool result = false; SessionStates state = this.m_currentSessionState.Connect(); if (state == SessionStates.CONNECTED) { result = true; } this.SetState(state); if (this.m_SessionData.LogonEnabled) { this.SetState(SessionStates.LOGON); } else if (this.m_SessionData.EnterGameEnabled) { this.SetState(SessionStates.ENTERING_GAME); } else if (this.m_SessionData.MummyScriptEnabled) { this.SetState(SessionStates.MummyScript); } return(result); }
protected virtual void OnStateChanged(SessionStates targetSessionState) { var sessionState = SessionState; SessionState = targetSessionState; StateChanged?.Invoke(this, new SessionStateChangedEventArgs(sessionState, targetSessionState)); }
public SessionData() { ElapsedTime = 0; SessionState = SessionStates.Idle; Breaks = new List <BreakData>(); Processes = new List <ProcessData>(); }
public FormMain() { InitializeComponent(); CurrentSettings = new MapSettings(); CurrentState = SessionStates.Waiting; }
// private methods /// @brief private constructor /// /// This is part of the singleton pattern, a protected constructor cannot be called externally (although /// it can be inherited for extensions. In which case the extender should also replace the singleton! private NIHandControl() { m_sessionState = SessionStates.NotInSession; NINITECheckVersion.Instance.ValidatePrerequisite(); m_internalNodes = new List <ProductionNode>(); m_sessionManager = null; }
private void OnPitEntry(SdkWrapper.TelemetryUpdatedEventArgs e, bool inPits, SessionStates sessionState) { var oldInPits = m_inPits; m_inPits = inPits; if (!oldInPits) { // Entering pit, send off command to set fuel. m_logger.Debug("Entering Pits"); m_logger.Debug("\t- Current fuel: {0}", e.TelemetryInfo.FuelLevel); if (m_sessionRemainingTime > 0 && sessionState == SessionStates.Racing && m_fuelToAdd > 0.0) { m_logger.Debug("\t- Adding {0} litres of fuel", m_fuelToAdd); if (m_autoFuel) { m_logger.Debug("\t- AutoFuel enabled."); m_wrapper.PitCommands.AddFuel(m_fuelToAdd); } else { m_logger.Debug("\t- AutoFuel disabled."); } } } }
private void btnGenerate_Click(object sender, EventArgs e) { if (CurrentState == SessionStates.GeneratingMap) { return; } CurrentState = SessionStates.GeneratingMap; Cursor.Current = Cursors.WaitCursor; Output("Generating map..."); int seed = GetSeedFromTextBox(); CurrentMap = new Map(seed, pMap.ClientRectangle); // apply any parameters before generating... ApplySettings(CurrentMap, CurrentSettings); CurrentMap.OnLog += CurrentMap_OnLog; CurrentMap.GenerateMap(); Output("Generating map done, drawing..."); this.pMap.Refresh(); Output("Drawing map done"); Cursor.Current = Cursors.Default; CurrentState = SessionStates.Waiting; }
/// <summary> /// The HandleConnect_Entrypoint method is the asynchronous /// entrypoint for the session's connect handling logic. /// </summary> /// <param name="state"> /// Ignored parameter; required for the method to meet the /// required signature for use with the sequencer. /// </param> private void HandleConnect_Entrypoint(object state) { // REC: Transition the session to the active state so // that it can begin handling messages: _currentState = SessionStates.Session_Pending; // REC: Reset the receive timestamp: this._lastRxTicks = DateTime.Now.Ticks; // REC: Reset the transmit timestamp: this._lastTxTicks = DateTime.Now.Ticks; // REC: Acquire the session's persisted session // state from the database: if (_fixDatabase != null) { _sessionRecord = _fixDatabase.AcquireSession(_sessionId); } // REC: The session's timer is started in order // to drive the heartbeat and timeout logic: this._fixTimer.Start(); _handler.OnSessionOpened(this); // REC: The client session needs to dispatch a logon // message to the peer as soon as it connects: FixMessage msgLogon = _fixAssembler.CreateMessage(_sxVersion, _axVersion, "A"); if (msgLogon != null) { Dispatch_AdmMessage(msgLogon); } }
internal void StopProcessing(string viewerID) { SessionStates[viewerID].FfmpegProcess.StandardInput.Flush(); SessionStates[viewerID].FfmpegProcess.StandardInput.Close(); SessionStates[viewerID].FfmpegProcess.Close(); SessionStates.TryRemove(viewerID, out _); }
//---------------------------------BUTTONS public void OnSessionButtonHit() { //Debug.Log("Session Planning Begin"); c_SessionState = SessionStates.ProfileChoose; //tell the profile manager to Spawn the Profile cards so they can choose which profile to meditate under ProfileManager.instance.OnProfilePhaseEnter (); SessionStateSwitch (c_SessionState); }
//---------------------------------BUTTONS public void OnSessionButtonHit() { //Debug.Log("Session Planning Begin"); c_SessionState = SessionStates.ProfileChoose; //tell the profile manager to Spawn the Profile cards so they can choose which profile to meditate under ProfileManager.instance.OnProfilePhaseEnter(); SessionStateSwitch(c_SessionState); }
internal void StartProcessing() { lock (LockObject) { try { while (FrameQueue.Count > 0) { if (FrameQueue.TryDequeue(out var frame)) { var saveDir = Directory.CreateDirectory(GetSaveFolder(frame)); var saveFile = Path.Combine(saveDir.FullName, $"Recording.mp4"); if (!SessionStates.ContainsKey(frame.ViewerID)) { SessionStates[frame.ViewerID] = new RecordingSessionState() { CumulativeFrame = new Bitmap(frame.Width, frame.Height) }; var ffmpegProc = new Process(); SessionStates[frame.ViewerID].FfmpegProcess = ffmpegProc; ffmpegProc.StartInfo.FileName = "ffmpeg.exe"; ffmpegProc.StartInfo.Arguments = $"-y -f image2pipe -i pipe:.jpg -r 5 \"{saveFile}\""; ffmpegProc.StartInfo.UseShellExecute = false; ffmpegProc.StartInfo.RedirectStandardInput = true; ffmpegProc.Start(); } var bitmap = SessionStates[frame.ViewerID].CumulativeFrame; using (var graphics = Graphics.FromImage(bitmap)) { using (var ms = new MemoryStream(frame.FrameBytes)) { using (var saveImage = Image.FromStream(ms)) { graphics.DrawImage(saveImage, frame.Left, frame.Top); } } } bitmap.Save(SessionStates[frame.ViewerID].FfmpegProcess.StandardInput.BaseStream, ImageFormat.Jpeg); } } } catch (Exception ex) { DataService.WriteEvent(ex); } finally { IsProcessing = false; } } }
public SessionStatusMessage(BufRef reader) : base(ProtocolMessageType.SessionStatus) { reader.Seek(4); if ((ProtocolMessageType)reader.Read8() != MessageType) { throw new ArgumentException("SessionStatusMessage( reader ) Wrong message type."); } SessionId = reader.Read16(); SessionState = (SessionStates)reader.Read8(); }
/// <summary> /// Ends session, i.e. stores content of the $_SESSION array to the <c>HttpContext.Session</c> collection. /// </summary> /// <param name="abandon">Whether to abandon the session without persisting variables.</param> /// <exception cref="SessionException">Session state not available.</exception> public void EndSession(bool abandon) { // checks and changes session state: if (disposed || sessionState != SessionStates.Started) { return; } sessionState = SessionStates.Closing; if (httpContext.Session == null) { throw new SessionException(CoreResources.GetString("session_state_unavailable")); } GlobalConfiguration global = Configuration.Global; PhpArray variables = PhpReference.AsPhpArray(scriptContext.AutoGlobals.Session); if (variables == null) { variables = new PhpArray(); } try { if (!abandon) { scriptContext.Config.Session.Handler.Persist(variables, scriptContext, httpContext); } else { scriptContext.Config.Session.Handler.Abandoning(scriptContext, httpContext); } } finally { if (!abandon) { // if ASP.NET session state is empty then adds a dump item to preserve the session: if (httpContext.Session.Count == 0) { httpContext.Session.Add(AspNetSessionHandler.PhpNetSessionVars, AspNetSessionHandler.DummySessionItem); } } else { // abandons ASP.NET session: httpContext.Session.Abandon(); } sessionState = SessionStates.Closed; } }
internal bool Disconnect() { bool result = false; SessionStates state = this.m_currentSessionState.Disconnect(); if (state == SessionStates.OFFLINE) { result = true; } this.SetState(state); return(result); }
public void Logout() { try { _commandHandler.LogoutFromServer(); State = SessionStates.AUTHORIZATION; } catch (Exception e) { Console.WriteLine(e); throw; } }
public void Login(string username, string password) { try { _commandHandler.LoginToServer(username, password); State = SessionStates.TRANSACTION; } catch (Exception e) { Console.WriteLine(e); throw; } }
//-----------------------------------------------------switches public void SessionStateSwitch(SessionStates toState) { c_SessionState = toState; switch (toState) { case SessionStates.ProfileChoose: CheckProgressionAvailability(); break; case SessionStates.TimeChoose: SessionTime_minutes = 5; Object_time.SetActive(true); Object_theme.SetActive(false); CheckProgressionAvailability(); break; case SessionStates.ThemeChoose: sessionTheme = ThemeStates.Classic; Object_theme.SetActive(true); Object_time.SetActive(false); CheckProgressionAvailability(); break; case SessionStates.Pre: break; case SessionStates.Intra: break; case SessionStates.Post: break; case SessionStates.None: profileAmout = 0; Object_time.SetActive(false); Object_theme.SetActive(false); ProfileManager.instance.profileExportList.Clear(); break; } }
public static bool CommandValidInState(this Commands self, SessionStates state) { switch (self) { case Commands.QUIT: return(true); case Commands.USER: case Commands.PASS: return(state == SessionStates.AUTHORIZATION); } return(state == SessionStates.TRANSACTION); }
/// <summary> /// The HandleDisconnect_Entrypoint method is the asynchronous /// entrypoint for the session's disconnection handling code. /// </summary> /// <param name="state"> /// Ignored parameter; required for the method to match the /// signature needed for use with the task sequencer. /// </param> private void HandleDisconnect_Entrypoint(object state) { // REC: If the session is currently established, then // the session record needs to be released: if (IsSessionEstablished() == true) { _fixDatabase.ReleaseSession(_sessionId); } // REC: Transition to the shutdown state: _currentState = SessionStates.Session_Shutdown; // REC: Notify the session handler: _handler.OnSessionClosed(this); }
/// <summary> /// The HandleSession_Logon method is invoked to handle /// a logon message that has been received from the peer /// session that this session is communicating with. /// </summary> /// <param name="msg"> /// The FIX logon message received from the peer. /// </param> private void HandleSession_Logon(FixMessage msg) { // REC: Ensure that we're in the appropriate state // to handle a logon message: if (_currentState == SessionStates.Session_Pending || _currentState == SessionStates.Session_Closed) { // REC: Retrieve the FIX SenderCompID of the peer // from the logon message: FixField fldSenderCompID = msg.Header.GetField(49); if (fldSenderCompID != null) { string rxSenderCompID = fldSenderCompID.Content; if (string.IsNullOrEmpty(rxSenderCompID)) { // HELP: Should the session send a reject message // in this case, given that the peer didn't send // its FIX SenderCompID, or should this throw an // argument exception? } // REC: Transition to the opened state: _currentState = SessionStates.Session_Opened; // REC: Notify the session's owner that the session // has received the logon response from the server: _handler.OnSessionLogon(this, msg); } else { // REC: Throw an exception since the session has not // yet been established and there will be no handler // at the application level that can deal with this: throw new ArgumentException("Logon message missing required field - SenderCompID."); } } else { // REC: Notify the session handler that an // administrative message has been received // from the peer session: _handler.OnSessionRxAdmMessage(this, msg); // REC: Throw an exception that indicates the // session is not in the appropriate state to // handle the received message: throw new InvalidOperationException("Session state invalid for received message."); } }
/// <summary> /// Starts session if not already started. Loads session variables from <c>HttpContext.Session</c>. /// </summary> /// <para> /// Session state (<c>HttpContext.Session</c>) has to be available at the time of the call. /// Otherwise, an exception occurs. /// </para> /// <para> /// Starting the session inheres in importing session variables from the session data store. /// The store is specific to the current PHP session handler /// defined by configuration option <see cref="LocalConfiguration.SessionSection.Handler"/>. /// In the case the ASP.NET handler is active, values from <c>HttpContext.Session</c> are imported to /// <c>$_SESSION</c> PHP auto-global variable. Hence, items added to the <c>HttpContext.Session</c> by /// non-PHP code after the start of the session will not be visible to PHP code. The <c>$_SESSION</c> variable /// has to be updated directly (see <c>ScriptContext.AutoGlobals</c>) to make these items visible to PHP. /// </para> /// <exception cref="SessionException">Session state not available.</exception> public void StartSession() { // checks and changes session state: if (disposed || sessionState != SessionStates.Closed) { return; } sessionState = SessionStates.Starting; if (httpContext.Session == null) { throw new SessionException(CoreResources.GetString("session_state_unavailable")); } EnsureSessionId(); GlobalConfiguration global = Configuration.Global; PhpArray variables = null; // removes dummy item keeping the session alive: if (httpContext.Session[AspNetSessionHandler.PhpNetSessionVars] as string == AspNetSessionHandler.DummySessionItem) { httpContext.Session.Remove(AspNetSessionHandler.PhpNetSessionVars); } // loads an array of session variables using the current session handler: variables = scriptContext.Config.Session.Handler.Load(scriptContext, httpContext); // variables cannot be null: if (variables == null) { variables = new PhpArray(); } // sets the auto-global variable (the previous content of $_SESSION array is discarded): PhpReference.SetValue(ref scriptContext.AutoGlobals.Session, variables); // copies session variables to $GLOBALS array if necessary: if (global.GlobalVariables.RegisterGlobals) { scriptContext.RegisterSessionGlobals(); } // adds a SID constant: UpdateSID(); sessionState = SessionStates.Started; }
public void Start() { if (SessionState == SessionStates.Stopped) { Reset(); SessionState = SessionStates.Active; SessionStart = DateTime.UtcNow; return; } if (SessionState == SessionStates.Idle) { SessionState = SessionStates.Active; SessionStart = DateTime.UtcNow; } else { throw new InvalidOperationException("Can not start from a non idle state"); } }
/// <summary> /// The HandleShutdown_Entrypoint method is the asynchronous /// entry point for the session's shutdown logic. /// </summary> /// <param name="state"> /// Ignored parameter - required for the method to match the /// needed signature for use with the sequencer. /// </param> private void HandleShutdown_Entrypoint(object state) { // REC: If the session is currently logged on, we need // to dispatch a logout message to the peer: if (_currentState == SessionStates.Session_Opened) { // REC: Transition to the closing state: _currentState = SessionStates.Session_Closing; FixMessage msgResponse = _fixAssembler.CreateMessage(_sxVersion, _axVersion, "5"); if (msgResponse != null) { // REC: Dispatch the logout message to the // peer session. The shutdown process will // complete when the peer responds with an // acknowledgment of the logout: Dispatch_AdmMessage(msgResponse); } } else if (_currentState == SessionStates.Session_Pending) { // REC: Transition to the shutdown state: _currentState = SessionStates.Session_Shutdown; // REC: Dispatch the shutdown notification // to the session's handler: _handler.OnSessionClosed(this); } else if (_currentState == SessionStates.Session_Closed) { // REC: Transition to the shutdown state: _currentState = SessionStates.Session_Shutdown; // REC: Release the session record: _fixDatabase.ReleaseSession(_sessionId, _sessionRecord); // REC: Dispatch the shutdown notification // to the session's handler: _handler.OnSessionClosed(this); } }
private void OnNewLap(SdkWrapper.TelemetryUpdatedEventArgs e, bool inPits, SessionStates sessionState) { var fuelLevel = e.TelemetryInfo.FuelLevel.Value; var laptime = m_wrapper.GetTelemetryValue <float>("LapLastLapTime").Value; m_telemLaps = m_wrapper.GetTelemetryValue <int>("SessionLapsRemain").Value; m_logger.Debug("Lap Completed {0}", m_lastLapCompleted); m_logger.Debug("\t- Time: {0}", laptime); m_logger.Debug("\t- Fuel Level: {0}", fuelLevel); if (m_lastFuelLevel >= fuelLevel && !inPits) { var fuelDelta = m_lastFuelLevel - fuelLevel; if (!cbOnlyGreen.Checked || (cbOnlyGreen.Checked && sessionState == SessionStates.Racing && m_isGreen)) { m_lapTimes.Add(laptime); m_fuelUsages.Add(fuelDelta); m_fuelUsages.Sort(); m_lapTimes.Sort(); } m_fuelLastLap = fuelDelta; m_averageLapTime = GetAvg(m_lapTimes.Where(l => l > 0.0)); m_fuelPerLap = GetAvg(m_fuelUsages); m_logger.Debug("\t- Fuel Delta: {0}", fuelDelta); m_logger.Debug("\t- Avg Laptime: {0}", m_averageLapTime); m_logger.Debug("\t- Avg Fuel Delta: {0}", m_fuelPerLap); m_logger.Debug("\t- Estimated Laps Remaining: {0}", m_estimatedLaps); m_logger.Debug("\t- Telemetry Laps Remaining: {0}", m_telemLaps); m_logger.Debug("\t- Total Fuel Required: {0}", m_totalFuelRequired); m_logger.Debug("\t- Stops Remaining: {0}", m_estimatedStops); } m_lastFuelLevel = fuelLevel; }
public void ValidateSession() { var abosulteUri = new Uri(uriHelperService.GetAbsoluteUri()); var isLoggedIn = jsInProcessRuntimeService.Invoke <bool>("isLoggedIn", null); if (!isLoggedIn && !abosulteUri.Query.Contains("code")) { if (clientSettings.LoginRequired) { uriHelperService.NavigateTo(BuildAuthorizeUrl()); } else { SessionState = SessionStates.Inactive; InvokeOnSessionStateChanged(); } } else { jsInProcessRuntimeService.Invoke <object>("drawAuth0Iframe", new DotNetObjectRef(this), $"{BuildAuthorizeUrl()}&response_mode=web_message&prompt=none"); } }
public async Task SetStateAsync(byte[] strongKey, string clientPrivateKey, string clientPublicKey, string serverPublicKey, string acessToken) { var sessionState = await SessionStates.Find(new BsonDocument()) .FirstOrDefaultAsync(); sessionState = new SessionState(); bool isNewSession = false; if (sessionState == null) { sessionState = new SessionState(); isNewSession = true; } sessionState.StrongKey = strongKey; sessionState.ClientPrivateKey = clientPrivateKey; sessionState.ClientPublicKey = clientPublicKey; sessionState.ServerPublicKey = serverPublicKey; sessionState.AcessToken = acessToken; if (isNewSession) { await SessionStates.InsertOneAsync(sessionState); } else { await SessionStates.UpdateOneAsync(new BsonDocument(), Builders <SessionState> .Update.Set(x => x.StrongKey, strongKey) .Set(x => x.ClientPrivateKey, clientPrivateKey) .Set(x => x.ClientPublicKey, clientPublicKey) .Set(x => x.ServerPublicKey, serverPublicKey) .Set(x => x.AcessToken, acessToken)); } }
/// <summary> /// The HandleConnect_Entrypoint method is the asynchronous /// entrypoint for the session's connection handling code. /// </summary> /// <param name="state"> /// Ignored parameter; required for the method to match the /// signature needed for use with the task sequencer. /// </param> private void HandleConnect_Entrypoint(object state) { // REC: Transition the session to the active state so // that it can begin handling messages: _currentState = SessionStates.Session_Pending; // REC: Reset the receive timestamp: this._lastRxTicks = DateTime.Now.Ticks; // REC: Reset the transmit timestamp: this._lastTxTicks = DateTime.Now.Ticks; // REC: Note that the persisted session information // cannot be retrieved here, as it is in the client // session implementations. The server will resolve // that information once the client logs on... // REC: The session's timer is started in order // to drive the heartbeat and timeout logic: this._fixTimer.Start(); // REC: Notify the handler: _handler.OnSessionOpened(this); }
//-----------------------------------------------------switches public void SessionStateSwitch(SessionStates toState) { c_SessionState = toState; switch (toState) { case SessionStates.ProfileChoose: CheckProgressionAvailability (); break; case SessionStates.TimeChoose: SessionTime_minutes = 5; Object_time.SetActive (true); Object_theme.SetActive (false); CheckProgressionAvailability (); break; case SessionStates.ThemeChoose: sessionTheme = ThemeStates.Classic; Object_theme.SetActive (true); Object_time.SetActive (false); CheckProgressionAvailability (); break; case SessionStates.Pre: break; case SessionStates.Intra: break; case SessionStates.Post: break; case SessionStates.None: profileAmout = 0; Object_time.SetActive (false); Object_theme.SetActive (false); ProfileManager.instance.profileExportList.Clear (); break; } }
public void UpdateState(SessionStates state) { this.State = state; this.IsFinished = state == SessionStates.CoolDown; this.IsCheckered = (state == SessionStates.CoolDown || state == SessionStates.Checkered); }
private void RaiseSessionStateChanged(ExchangeBoard board, SessionStates state) { SessionStateChanged?.Invoke(board, state); }
/// <summary> /// Changes the state of this view, so it can change its user interface /// accordingly. /// </summary> /// <param name="state">The new state.</param> private void SetState(SessionStates state) { Logger.InfoFormat("State changed to {0}", state); OnStateChanged(new StateChangedEventArgs(state)); switch(state) { case SessionStates.Disconnected: this.ChangeStatus(TranslationUtil.GetString(ApplicationUtil.LanguageResources, "StatusDisconnected"), false, false); break; case SessionStates.Connecting: this.ChangeStatus(TranslationUtil.GetString(ApplicationUtil.LanguageResources, "StatusConnecting"), true, false); break; case SessionStates.Connected: this.ChangeStatus(TranslationUtil.GetString(ApplicationUtil.LanguageResources, "StatusConnected"), false, false); break; case SessionStates.AwaitingConnection: this.ChangeStatus(TranslationUtil.GetString(ApplicationUtil.LanguageResources, "StatusAwaiting"), true, true); break; } // If we're not disconnected, we have to uncollapse the right panel if(state == SessionStates.Disconnected) { splitContainer.Panel2Collapsed = true; } else { splitContainer.Panel2MinSize = 0; splitContainer.Panel2Collapsed = false; } UpdateGuiState(); }
public SessionInfo() { id = 0; lapsTotal = 0; lapsComplete = 0; leadChanges = 0; cautions = 0; cautionLaps = 0; fastestlap = 0; fastestdriver = new DriverInfo(); fastestlapnum = 0; time = 0; sessiontimeremaining = 0; sessionlength = 0; sessionstarttime = -1; sessionstartpos = 0; finishline = Int32.MaxValue; type = SessionTypes.none; state = SessionStates.invalid; flag = SessionFlags.invalid; startlight = SessionStartLights.off; standings = new ObservableCollection<StandingsItem>(); followedDriver = new StandingsItem(); }
/// <summary> /// The HandleShutdown_Entrypoint method is the asynchronous /// entry point for the session's shutdown logic. /// </summary> /// <param name="state"></param> private void HandleShutdown_Entrypoint(object state) { // REC: If the session is currently logged on, we need // to dispatch a logout message to the peer: if (_currentState == SessionStates.Session_Opened) { // REC: Transition to the closing state: _currentState = SessionStates.Session_Closing; FixMessage msgResponse = _fixAssembler.CreateMessage(_sxVersion, _axVersion, "5"); if (msgResponse != null) { // REC: Dispatch the logout message to the // peer session. The shutdown process will // complete when the peer responds with an // acknowledgment of the logout: Dispatch_AdmMessage(msgResponse); } } else if (_currentState == SessionStates.Session_Pending) { // REC: Transition to the shutdown state: _currentState = SessionStates.Session_Shutdown; // REC: Dispatch the shutdown notification // to the session's handler: _handler.OnSessionClosed(this); } else if (_currentState == SessionStates.Session_Closed) { // REC: Transition to the shutdown state: _currentState = SessionStates.Session_Shutdown; // REC: Release the session record: _fixDatabase.ReleaseSession(_sessionId, _sessionRecord); // REC: Dispatch the shutdown notification // to the session's handler: _handler.OnSessionClosed(this); } }
private void InnerExecute() { if ((this.oRequest == null) || (this.oResponse == null)) { return; } if (!this._executeObtainRequest()) { return; } if (this.HTTPMethodIs("CONNECT")) { this.isTunnel = true; if (this.oFlags.ContainsKey("x-replywithtunnel")) { this._ReturnSelfGeneratedCONNECTTunnel(this.hostname); return; } } if (this.m_state >= SessionStates.ReadingResponse) { if (this.isAnyFlagSet(SessionFlags.ResponseGeneratedByFiddler)) { FiddlerApplication.DoResponseHeadersAvailable(this); } goto Label_057A; } if (this.oFlags.ContainsKey("x-replywithfile")) { this.oResponse = new ServerChatter(this, "HTTP/1.1 200 OK\r\nServer: Fiddler\r\n\r\n"); if (this.LoadResponseFromFile(this.oFlags["x-replywithfile"]) && this.isAnyFlagSet(SessionFlags.ResponseGeneratedByFiddler)) { FiddlerApplication.DoResponseHeadersAvailable(this); } this.oFlags["x-repliedwithfile"] = this.oFlags["x-replywithfile"]; this.oFlags.Remove("x-replywithfile"); goto Label_057A; } if ((this.port < 0) || (this.port > 0xffff)) { FiddlerApplication.HandleHTTPError(this, SessionFlags.ProtocolViolationInRequest, true, false, "HTTP Request specified an invalid port number."); } if (this._isDirectRequestToFiddler()) { if (this.oRequest.headers.RequestPath.OICEndsWith(".pac")) { if (CONFIG.bHookWithPAC && this.oRequest.headers.RequestPath.OICEndsWith("/proxy.pac")) { this._returnPACFileResponse(); return; } if (this.oRequest.headers.RequestPath.OICEndsWith("/UpstreamProxy.pac")) { this._returnUpstreamPACFileResponse(); return; } } if (this.oRequest.headers.RequestPath.OICEndsWith("/fiddlerroot.cer")) { _returnRootCert(this); return; } if (CONFIG.iReverseProxyForPort == 0) { this._returnEchoServiceResponse(); return; } this.oFlags.Add("X-ReverseProxy", "1"); this.host = string.Format("{0}:{1}", CONFIG.sReverseProxyHostname, CONFIG.iReverseProxyForPort); } Label_01F5: this.state = SessionStates.SendingRequest; if (!this.oResponse.ResendRequest()) { this.CloseSessionPipes(true); this.state = SessionStates.Aborted; return; } if (this.isAnyFlagSet(SessionFlags.RequestStreamed)) { bool bStreamResponse = false; GenericTunnel.CreateTunnel(this, bStreamResponse); if (bStreamResponse) { return; } } this.Timers.ServerGotRequest = DateTime.Now; this.state = SessionStates.ReadingResponse; if (this.HTTPMethodIs("CONNECT") && !this.oResponse._bWasForwarded) { this.SetBitFlag(SessionFlags.ResponseGeneratedByFiddler, true); this.oResponse.headers = new HTTPResponseHeaders(); this.oResponse.headers.HTTPVersion = this.oRequest.headers.HTTPVersion; this.oResponse.headers.HTTPResponseCode = 200; this.oResponse.headers.HTTPResponseStatus = "200 Connection Established"; this.oResponse.headers.Add("FiddlerGateway", "Direct"); this.oResponse.headers.Add("StartTime", DateTime.Now.ToString("HH:mm:ss.fff")); this.oResponse.headers.Add("Connection", "close"); this.responseBodyBytes = Utilities.emptyByteArray; } else { if (!this.oResponse.ReadResponse()) { if (!this.oResponse.bServerSocketReused || (this.state == SessionStates.Aborted)) { FiddlerApplication.DebugSpew("Failed to read server response. Aborting."); if (this.state != SessionStates.Aborted) { string str = string.Empty; if (!Utilities.IsNullOrEmpty(this.responseBodyBytes)) { str = Encoding.UTF8.GetString(this.responseBodyBytes); } str = string.Format("Server returned {0} bytes.{1}", this.oResponse.m_responseTotalDataCount, str); this.oRequest.FailSession(0x1f8, "Fiddler - Receive Failure", string.Format("[Fiddler] ReadResponse() failed: The server did not return a response for this request.{0}", str)); } this.CloseSessionPipes(true); this.state = SessionStates.Aborted; return; } FiddlerApplication.DebugSpew("[" + this.id.ToString() + "] ServerSocket Reuse failed. Restarting fresh."); this.oResponse.Initialize(true); goto Label_01F5; } if ((200 == this.responseCode) && this.isAnyFlagSet(SessionFlags.RequestStreamed)) { this.responseBodyBytes = this.oResponse.TakeEntity(); try { this.oRequest.pipeClient.Send(this.oResponse.headers.ToByteArray(true, true)); this.oRequest.pipeClient.Send(this.responseBodyBytes); (this.__oTunnel as GenericTunnel).BeginResponseStreaming(); } catch (Exception exception) { FiddlerApplication.Log.LogFormat("Failed to create RPC Tunnel {0}", new object[] { Utilities.DescribeException(exception) }); } return; } if (this.isAnyFlagSet(SessionFlags.ResponseBodyDropped)) { this.responseBodyBytes = Utilities.emptyByteArray; this.oResponse.FreeResponseDataBuffer(); } else { long num; this.responseBodyBytes = this.oResponse.TakeEntity(); if ((this.oResponse.headers.Exists("Content-Length") && !this.HTTPMethodIs("HEAD")) && (long.TryParse(this.oResponse.headers["Content-Length"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out num) && (num != this.responseBodyBytes.LongLength))) { FiddlerApplication.HandleHTTPError(this, SessionFlags.ProtocolViolationInResponse, true, true, string.Format("Content-Length mismatch: Response Header indicated {0:N0} bytes, but server sent {1:N0} bytes.", num, this.responseBodyBytes.LongLength)); } } } Label_057A: this.oFlags["x-ResponseBodyTransferLength"] = (this.responseBodyBytes == null) ? "0" : this.responseBodyBytes.LongLength.ToString(); this.state = SessionStates.AutoTamperResponseBefore; FiddlerApplication.DoBeforeResponse(this); if (!this._handledAsAutomaticRedirect() && !this._handledAsAutomaticAuth()) { bool flag3 = false; if ((this.m_state >= SessionStates.Done) || this.isFlagSet(SessionFlags.ResponseStreamed)) { this.FinishUISession(this.isFlagSet(SessionFlags.ResponseStreamed)); if (this.isFlagSet(SessionFlags.ResponseStreamed) && this.oFlags.ContainsKey("log-drop-response-body")) { this.SetBitFlag(SessionFlags.ResponseBodyDropped, true); this.responseBodyBytes = Utilities.emptyByteArray; } flag3 = true; } if (flag3) { if (this.m_state < SessionStates.Done) { this.m_state = SessionStates.Done; } FiddlerApplication.DoAfterSessionComplete(this); } else { if (this.oFlags.ContainsKey("x-replywithfile")) { this.LoadResponseFromFile(this.oFlags["x-replywithfile"]); this.oFlags["x-replacedwithfile"] = this.oFlags["x-replywithfile"]; this.oFlags.Remove("x-replywithfile"); } this.state = SessionStates.AutoTamperResponseAfter; } bool bForceClientServerPipeAffinity = false; if (this._isResponseMultiStageAuthChallenge()) { bForceClientServerPipeAffinity = this._isNTLMType2(); } if (this.m_state >= SessionStates.Done) { this.FinishUISession(); flag3 = true; } if (!flag3) { this.ReturnResponse(bForceClientServerPipeAffinity); } if (flag3 && (this.oRequest.pipeClient != null)) { if (bForceClientServerPipeAffinity || this._MayReuseMyClientPipe()) { this._createNextSession(bForceClientServerPipeAffinity); } else { this.oRequest.pipeClient.End(); } this.oRequest.pipeClient = null; } this.oResponse.releaseServerPipe(); } }
public bool LoadMetadata(Stream strmMetadata) { string str = XmlConvert.ToString(true); SessionFlags none = SessionFlags.None; string str2 = null; try { XmlTextReader reader = new XmlTextReader(strmMetadata) { WhitespaceHandling = WhitespaceHandling.None }; while (reader.Read()) { long num; string str4; if ((reader.NodeType == XmlNodeType.Element) && ((str4 = reader.Name) != null)) { if (!(str4 == "Session")) { if (str4 == "SessionFlag") { goto Label_00F1; } if (str4 == "SessionTimers") { goto Label_0117; } if (str4 == "TunnelInfo") { goto Label_0328; } if (str4 == "PipeInfo") { goto Label_0372; } } else { if (reader.GetAttribute("Aborted") != null) { this.m_state = SessionStates.Aborted; } if (reader.GetAttribute("BitFlags") != null) { this.BitFlags = (SessionFlags) uint.Parse(reader.GetAttribute("BitFlags"), NumberStyles.HexNumber); } if (reader.GetAttribute("SID") != null) { str2 = reader.GetAttribute("SID"); } } } continue; Label_00F1: this.oFlags.Add(reader.GetAttribute("N"), reader.GetAttribute("V")); continue; Label_0117: this.Timers.ClientConnected = XmlConvert.ToDateTime(reader.GetAttribute("ClientConnected"), XmlDateTimeSerializationMode.RoundtripKind); string attribute = reader.GetAttribute("ClientBeginRequest"); if (attribute != null) { this.Timers.ClientBeginRequest = XmlConvert.ToDateTime(attribute, XmlDateTimeSerializationMode.RoundtripKind); } attribute = reader.GetAttribute("GotRequestHeaders"); if (attribute != null) { this.Timers.FiddlerGotRequestHeaders = XmlConvert.ToDateTime(attribute, XmlDateTimeSerializationMode.RoundtripKind); } this.Timers.ClientDoneRequest = XmlConvert.ToDateTime(reader.GetAttribute("ClientDoneRequest"), XmlDateTimeSerializationMode.RoundtripKind); attribute = reader.GetAttribute("GatewayTime"); if (attribute != null) { this.Timers.GatewayDeterminationTime = XmlConvert.ToInt32(attribute); } attribute = reader.GetAttribute("DNSTime"); if (attribute != null) { this.Timers.DNSTime = XmlConvert.ToInt32(attribute); } attribute = reader.GetAttribute("TCPConnectTime"); if (attribute != null) { this.Timers.TCPConnectTime = XmlConvert.ToInt32(attribute); } attribute = reader.GetAttribute("HTTPSHandshakeTime"); if (attribute != null) { this.Timers.HTTPSHandshakeTime = XmlConvert.ToInt32(attribute); } attribute = reader.GetAttribute("ServerConnected"); if (attribute != null) { this.Timers.ServerConnected = XmlConvert.ToDateTime(attribute, XmlDateTimeSerializationMode.RoundtripKind); } attribute = reader.GetAttribute("FiddlerBeginRequest"); if (attribute != null) { this.Timers.FiddlerBeginRequest = XmlConvert.ToDateTime(attribute, XmlDateTimeSerializationMode.RoundtripKind); } this.Timers.ServerGotRequest = XmlConvert.ToDateTime(reader.GetAttribute("ServerGotRequest"), XmlDateTimeSerializationMode.RoundtripKind); attribute = reader.GetAttribute("ServerBeginResponse"); if (attribute != null) { this.Timers.ServerBeginResponse = XmlConvert.ToDateTime(attribute, XmlDateTimeSerializationMode.RoundtripKind); } attribute = reader.GetAttribute("GotResponseHeaders"); if (attribute != null) { this.Timers.FiddlerGotResponseHeaders = XmlConvert.ToDateTime(attribute, XmlDateTimeSerializationMode.RoundtripKind); } this.Timers.ServerDoneResponse = XmlConvert.ToDateTime(reader.GetAttribute("ServerDoneResponse"), XmlDateTimeSerializationMode.RoundtripKind); this.Timers.ClientBeginResponse = XmlConvert.ToDateTime(reader.GetAttribute("ClientBeginResponse"), XmlDateTimeSerializationMode.RoundtripKind); this.Timers.ClientDoneResponse = XmlConvert.ToDateTime(reader.GetAttribute("ClientDoneResponse"), XmlDateTimeSerializationMode.RoundtripKind); continue; Label_0328: num = 0L; long result = 0L; if (long.TryParse(reader.GetAttribute("BytesEgress"), out num) && long.TryParse(reader.GetAttribute("BytesIngress"), out result)) { this.__oTunnel = new MockTunnel(num, result); } continue; Label_0372: this.bBufferResponse = str != reader.GetAttribute("Streamed"); if (!this.bBufferResponse) { none |= SessionFlags.ResponseStreamed; } if (str == reader.GetAttribute("CltReuse")) { none |= SessionFlags.ClientPipeReused; } if (str == reader.GetAttribute("Reused")) { none |= SessionFlags.ServerPipeReused; } if (this.oResponse != null) { this.oResponse._bWasForwarded = str == reader.GetAttribute("Forwarded"); if (this.oResponse._bWasForwarded) { none |= SessionFlags.SentToGateway; } } } if (this.BitFlags == SessionFlags.None) { this.BitFlags = none; } if (this.Timers.ClientBeginRequest.Ticks < 1L) { this.Timers.ClientBeginRequest = this.Timers.ClientConnected; } if (this.Timers.FiddlerBeginRequest.Ticks < 1L) { this.Timers.FiddlerBeginRequest = this.Timers.ServerGotRequest; } if (this.Timers.FiddlerGotRequestHeaders.Ticks < 1L) { this.Timers.FiddlerGotRequestHeaders = this.Timers.ClientBeginRequest; } if (this.Timers.FiddlerGotResponseHeaders.Ticks < 1L) { this.Timers.FiddlerGotResponseHeaders = this.Timers.ServerBeginResponse; } if ((this.m_clientPort == 0) && this.oFlags.ContainsKey("X-ClientPort")) { int.TryParse(this.oFlags["X-ClientPort"], out this.m_clientPort); } if (str2 != null) { if (this.oFlags.ContainsKey("ui-comments")) { this.oFlags["x-OriginalSessionID"] = str2; } else { this.oFlags["ui-comments"] = string.Format("[#{0}] {1}", str2, this.oFlags["ui-comments"]); } } reader.Close(); return true; } catch (Exception exception) { FiddlerApplication.ReportException(exception); return false; } }
internal StateChangeEventArgs(SessionStates ssOld, SessionStates ssNew) { this.oldState = ssOld; this.newState = ssNew; }
/// <summary> /// Initializes a new instance of the StateChangedEventArgs with /// the state it now is in. /// </summary> /// <param name="state">See <see cref="State" />.</param> public StateChangedEventArgs(SessionStates state) { State = state; }
public Session(HTTPRequestHeaders oRequestHeaders, byte[] arrRequestBody) { EventHandler<StateChangeEventArgs> handler = null; this.bBufferResponse = FiddlerApplication.Prefs.GetBoolPref("fiddler.ui.rules.bufferresponses", false); this.Timers = new SessionTimers(); this._bAllowClientPipeReuse = true; this.oFlags = new StringDictionary(); if (oRequestHeaders == null) { throw new ArgumentNullException("oRequestHeaders", "oRequestHeaders must not be null when creating a new Session."); } if (arrRequestBody == null) { arrRequestBody = Utilities.emptyByteArray; } if (CONFIG.bDebugSpew) { if (handler == null) { handler = (s, ea) => FiddlerApplication.DebugSpew(string.Format("onstatechange>#{0} moving from state '{1}' to '{2}' {3}", new object[] { this.id.ToString(), ea.oldState, ea.newState, Environment.StackTrace })); } this.OnStateChanged += handler; } this.Timers.ClientConnected = this.Timers.ClientBeginRequest = this.Timers.FiddlerGotRequestHeaders = DateTime.Now; this.m_clientIP = null; this.m_clientPort = 0; this.oFlags["x-clientIP"] = this.m_clientIP; this.oFlags["x-clientport"] = this.m_clientPort.ToString(); this.oResponse = new ServerChatter(this); this.oRequest = new ClientChatter(this); this.oRequest.pipeClient = null; this.oResponse.pipeServer = null; this.oRequest.headers = oRequestHeaders; this.requestBodyBytes = arrRequestBody; this.m_state = SessionStates.AutoTamperRequestBefore; }
/// <summary> /// Ends session, i.e. stores content of the $_SESSION array to the <c>HttpContext.Session</c> collection. /// </summary> /// <param name="abandon">Whether to abandon the session without persisting variables.</param> /// <exception cref="SessionException">Session state not available.</exception> public void EndSession(bool abandon) { // checks and changes session state: if (disposed || sessionState != SessionStates.Started) return; sessionState = SessionStates.Closing; if (httpContext.Session == null) throw new SessionException(CoreResources.GetString("session_state_unavailable")); GlobalConfiguration global = Configuration.Global; PhpArray variables = PhpReference.AsPhpArray(scriptContext.AutoGlobals.Session); if (variables == null) variables = new PhpArray(); try { if (!abandon) scriptContext.Config.Session.Handler.Persist(variables, scriptContext, httpContext); else scriptContext.Config.Session.Handler.Abandoning(scriptContext, httpContext); } finally { if (!abandon) { // if ASP.NET session state is empty then adds a dump item to preserve the session: if (httpContext.Session.Count == 0) httpContext.Session.Add(AspNetSessionHandler.PhpNetSessionVars, AspNetSessionHandler.DummySessionItem); } else { // abandons ASP.NET session: httpContext.Session.Abandon(); } sessionState = SessionStates.Closed; } }
/// <summary> /// Starts session if not already started. Loads session variables from <c>HttpContext.Session</c>. /// </summary> /// <para> /// Session state (<c>HttpContext.Session</c>) has to be available at the time of the call. /// Otherwise, an exception occurs. /// </para> /// <para> /// Starting the session inheres in importing session variables from the session data store. /// The store is specific to the current PHP session handler /// defined by configuration option <see cref="LocalConfiguration.SessionSection.Handler"/>. /// In the case the ASP.NET handler is active, values from <c>HttpContext.Session</c> are imported to /// <c>$_SESSION</c> PHP auto-global variable. Hence, items added to the <c>HttpContext.Session</c> by /// non-PHP code after the start of the session will not be visible to PHP code. The <c>$_SESSION</c> variable /// has to be updated directly (see <c>ScriptContext.AutoGlobals</c>) to make these items visible to PHP. /// </para> /// <exception cref="SessionException">Session state not available.</exception> public void StartSession() { // checks and changes session state: if (disposed || sessionState != SessionStates.Closed) return; sessionState = SessionStates.Starting; if (httpContext.Session == null) throw new SessionException(CoreResources.GetString("session_state_unavailable")); EnsureSessionId(); GlobalConfiguration global = Configuration.Global; PhpArray variables = null; // removes dummy item keeping the session alive: if (httpContext.Session[AspNetSessionHandler.PhpNetSessionVars] as string == AspNetSessionHandler.DummySessionItem) httpContext.Session.Remove(AspNetSessionHandler.PhpNetSessionVars); // loads an array of session variables using the current session handler: variables = scriptContext.Config.Session.Handler.Load(scriptContext, httpContext); // variables cannot be null: if (variables == null) variables = new PhpArray(); // sets the auto-global variable (the previous content of $_SESSION array is discarded): PhpReference.SetValue(ref scriptContext.AutoGlobals.Session, variables); // copies session variables to $GLOBALS array if necessary: if (global.GlobalVariables.RegisterGlobals) scriptContext.RegisterSessionGlobals(); // adds a SID constant: UpdateSID(); sessionState = SessionStates.Started; }
/// <summary> /// The HandleSession_Logon method is invoked to handle /// a logon message that has been received from the peer /// session that this session is communicating with. /// </summary> /// <param name="msg"> /// The FIX logon message received from the peer. /// </param> private void HandleSession_Logon(FixMessage msg) { // REC: Ensure that we're in the appropriate state // to handle a logon message: if (_currentState == SessionStates.Session_Pending || _currentState == SessionStates.Session_Closed) { // REC: Retrieve the FIX SenderCompID of the peer // from the logon message: FixField fldSenderCompID = msg.Header.GetField(49); if (fldSenderCompID != null) { // REC: The SenderCompID from the peer becomes the // session's TargetCompID for outgoing messages: _fixTargetCompID = fldSenderCompID.Content; // REC: Now that the FIX SenderCompID of the peer // session is known, it is used to construct the // identifier for the session - used to retrieve // the session's details from the database: _sessionId = string.Format("{0}-{1}", _fixSenderCompID, _fixTargetCompID); // REC: Attempt to retrieve the session details // from the session database: if (_fixDatabase != null) { // REC: Note that once a session record is acquired // from the database, it must be released when it is // no longer needed by the session instance... _sessionRecord = _fixDatabase.AcquireSession(_sessionId); if (this._resetSequence == true) { _sessionRecord.RxSequence = 1; _sessionRecord.TxSequence = 1; } } // REC: Register the peer session's SenderCompID as // the TargetCompID for outgoing messages: _fixAssembler.SetField(new FixField(56, _fixTargetCompID)); // REC: Assemble the response message: FixMessage response = _fixAssembler.CreateMessage(_sxVersion, _axVersion, "A"); // REC: Handle the sequence number reset flag // if it is present in the logon message: FixField fieldReset = msg.GetField(141); if (fieldReset != null) { response.AddField(new FixField(141, "Y")); } // REC: Transition to the opened state: _currentState = SessionStates.Session_Opened; // REC: Notify the session's owner that the peer // session has sent the logon request: _handler.OnSessionLogon(this, msg); // REC: Dispatch the administrative message out // to the session's owner: Dispatch_AdmMessage(response); } else { // REC: Throw an exception since the session has not // yet been established and there will be no handler // at the application level that can deal with this: throw new ArgumentException("Logon message missing required field - SenderCompID."); } } else { // REC: Notify the session handler that an // administrative message has been received // from the peer session: _handler.OnSessionRxAdmMessage(this, msg); // REC: Throw an exception that indicates the // session is not in the appropriate state to // handle the received message: //throw new InvalidOperationException("Session state invalid for received message."); } }
/// <summary> /// The HandleSession_Logout method is invoked to handle /// a logout message that has been received from the peer /// session that the session is interacting with. /// </summary> /// <param name="msg"> /// The FIX logout message that was received. /// </param> private void HandleSession_Logout(FixMessage msg) { // REC: If the session is already in the closing // state, then this is the acknowledgement by the // peer session that it has received the logout: if (_currentState == SessionStates.Session_Closing) { // REC: Transition to the shutdown state: _currentState = SessionStates.Session_Shutdown; // REC: Notify the session handler that the // administrative message has been received // from the peer session: _handler.OnSessionRxAdmMessage(this, msg); // REC: Release the session record from the // database so that it can be used again: _fixDatabase.ReleaseSession(_sessionId, _sessionRecord); // REC: Dispatch the shutdown notification // to the session handler: _handler.OnSessionClosed(this); } else if (_currentState == SessionStates.Session_Opened) { // REC: Transition to the closing state: _currentState = SessionStates.Session_Closing; // REC: Notify the session handler that the // administrative message has been received // from the peer session: _handler.OnSessionRxAdmMessage(this, msg); // REC: Dispatch a logout response to the peer // session to acknowledge the shutdown: FixMessage msgResponse = _fixAssembler.CreateMessage(_sxVersion, _axVersion, "5"); if (msgResponse != null) { Dispatch_AdmMessage(msgResponse); } // REC: Transition to the closed state: _currentState = SessionStates.Session_Closed; // REC: Release the session record from the // database so that it can be used again: _fixDatabase.ReleaseSession(_sessionId, _sessionRecord); // REC: Notify the session handler that // the session is logged out: _handler.OnSessionLogout(this, msg); } else { // REC: Notify the session handler that an // administrative message has been received: _handler.OnSessionRxAdmMessage(this, msg); // REC: Throw an exception that indicates the // message was received in an invalid state: throw new InvalidOperationException("Session state invalid for received message."); } }
private void SessionStateChangedHandler(ExchangeBoard board, SessionStates state) { AddGuiAction(() => SessionStateChanged.SafeInvoke(board, state)); }
public void UpdateState(SessionStates state) { this.State = state; this.IsFinished = state == SessionStates.CoolDown; }