public SessionInformation GetSession() { _logger.LogInfo($"Session collector | {nameof(WindowsSession)}"); var startInfo = new ProcessStartInfo { FileName = "cmd.exe", Arguments = $"/c query user", UseShellExecute = false, RedirectStandardOutput = true }; var process = new System.Diagnostics.Process { StartInfo = startInfo }; process.Start(); var cmdContent = process.StandardOutput.ReadToEnd(); DateTime logonTime = GetLogonTime(cmdContent).ToUniversalTime(); var sessionInstance = new SessionInformation { SessionId = Guid.NewGuid(), SessionStarted = logonTime, User = _platformInformation.PlatformInformation.UserName }; _logger.LogInfo("User session created {@data} | WindowsSession", sessionInstance); return(sessionInstance); }
public void SessionChange(HostControl hostControl, SessionChangedArguments args) { var sid = (uint)args.SessionId; var kind = Kind.Unknown; switch (args.ReasonCode) { // Kind.Active to store latest active time span when user ends work case SessionChangeReasonCode.ConsoleDisconnect: case SessionChangeReasonCode.RemoteDisconnect: case SessionChangeReasonCode.SessionLock: case SessionChangeReasonCode.SessionLogoff: kind = Kind.Active; break; // Kind.Connected to reset Accounter and start watching for user time since connected state case SessionChangeReasonCode.ConsoleConnect: case SessionChangeReasonCode.RemoteConnect: case SessionChangeReasonCode.SessionLogon: case SessionChangeReasonCode.SessionUnlock: kind = Kind.Connected; break; } if (kind != Kind.Unknown) { _accounter.Changed(new SessionData(sid, kind, this) { User = SessionInformation.GetUsernameBySessionId(sid, false) }); } }
public bool IsValidSession(string sessionKey, SessionInformation sessionInformation) { var sessionInformationIsNull = sessionInformation == null; if (sessionInformationIsNull) { LogUtility.Debug($"Could not find session with key '{sessionKey}'"); return(false); } else { var sessionDataMissing = (string.IsNullOrEmpty(sessionInformation.Value) || string.IsNullOrEmpty(sessionInformation.Key)); if (sessionDataMissing) { LogUtility.Debug($"Session data is incomplete"); return(false); } else { var sessionKeyMismatch = sessionDataMissing == false && sessionInformation.Key.Equals(sessionKey, StringComparison.InvariantCultureIgnoreCase) == false; if (sessionKeyMismatch) { LogUtility.Debug($"Supplied session key does not match with key from server"); return(false); } } } return(true); }
// Note: Do not rely on cancellationToken parameter to this method because the top layer does not yet implement any cancellation. public async Task <TaskOrchestrationWorkItem> LockNextTaskOrchestrationWorkItemAsync(TimeSpan receiveTimeout, CancellationToken cancellationToken) { var currentSession = await this.orchestrationProvider.AcceptSessionAsync(receiveTimeout); if (currentSession == null) { return(null); } List <Message <Guid, TaskMessageItem> > newMessages; try { newMessages = await this.orchestrationProvider.ReceiveSessionMessagesAsync(currentSession); var currentRuntimeState = new OrchestrationRuntimeState(currentSession.SessionState); var workItem = new TaskOrchestrationWorkItem() { NewMessages = newMessages.Select(m => m.Value.TaskMessage).ToList(), InstanceId = currentSession.SessionId.InstanceId, OrchestrationRuntimeState = currentRuntimeState }; if (newMessages.Count == 0) { if (currentRuntimeState.ExecutionStartedEvent == null) { ServiceFabricProviderEventSource.Tracing.UnexpectedCodeCondition($"Orchestration with no execution started event found: {currentSession.SessionId}"); return(null); } bool isComplete = this.IsOrchestrationComplete(currentRuntimeState.OrchestrationStatus); if (isComplete) { await this.HandleCompletedOrchestration(workItem); } this.orchestrationProvider.TryUnlockSession(currentSession.SessionId, isComplete: isComplete); return(null); } var sessionInfo = new SessionInformation() { Instance = currentSession.SessionId, LockTokens = newMessages.Select(m => m.Key).ToList() }; if (!this.sessionInfos.TryAdd(workItem.InstanceId, sessionInfo)) { ServiceFabricProviderEventSource.Tracing.UnexpectedCodeCondition($"{nameof(FabricOrchestrationService)}.{nameof(LockNextTaskOrchestrationWorkItemAsync)} : Multiple receivers processing the same session : {currentSession.SessionId.InstanceId}?"); } return(workItem); } catch (Exception) { this.orchestrationProvider.TryUnlockSession(currentSession.SessionId, abandon: true); throw; } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDataProtection(); services.AddControllersWithViews().AddRazorRuntimeCompilation().AddNewtonsoftJson(); services.AddTransient <IMediator, Mediator>(); new MainMapper().Setup(services); // DB Setup services.AddTransient <NoticeBoardContext>(serviceProvider => { DbContextOptionsBuilder <NoticeBoardContext> options = new DbContextOptionsBuilder <NoticeBoardContext>(); options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); var context = new NoticeBoardContext(options.Options); return(context); }); services.AddScoped <ISessionInformation>(serviceProvider => { DbContextOptionsBuilder <NoticeBoardContext> options = new DbContextOptionsBuilder <NoticeBoardContext>(); options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); var context = new NoticeBoardContext(options.Options); SessionInformation sessionInformation = new SessionInformation(); var contextAccessor = serviceProvider.GetService <IHttpContextAccessor>(); if (true) //contextAccessor.HttpContext != null) //TODO: Get HttpContext { var claims = contextAccessor?.HttpContext?.User?.Claims; var userid = "1"; //TODO: Replace with Id from user claim //var userid = Convert.ToInt32(claims?.FirstOrDefault(n => n.Type == "objectid")?.Value); var user = context.Player.SingleOrDefault(n => n.UserId == userid && n.IsEnabled); if (user != null) { sessionInformation.Name = user.Name; sessionInformation.UserId = userid; sessionInformation.IsDM = user.IsDm; sessionInformation.IsEnabled = user.IsEnabled; } } return(sessionInformation); }); var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MapperProfiles()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); }
/// <summary> /// Resets ingredient selection, saves the selected ingredients and calls the switch to the next state /// </summary> protected override void OnLeaveState() { m_CurrentNumberOfSelectedIngredients = 0; ActivateIngredientSelection(false); SessionInformation info = LogicManager.CurrentSessionInfo; info.IngredientsOfSession = m_SelectedIngredients; LogicManager.CurrentSessionInfo = info; LogicManager.Switchstate(); }
private SessionInformation GetSessionInformation(Dvtk.Sessions.Session theSession) { SessionInformation theSessionInformation = null; int theIndex = GetLoadedSessionsIndex(theSession); if (theIndex != -1) { theSessionInformation = GetSessionInformation(theIndex); } return(theSessionInformation); }
public Task ReleaseTaskOrchestrationWorkItemAsync(TaskOrchestrationWorkItem workItem) { bool isComplete = this.IsOrchestrationComplete(workItem.OrchestrationRuntimeState.OrchestrationStatus); SessionInformation sessionInfo = TryRemoveSessionInfo(workItem.InstanceId); if (sessionInfo != null) { this.orchestrationProvider.TryUnlockSession(sessionInfo.Instance, isComplete: isComplete); } return(Task.CompletedTask); }
public void SetSessionChanged(Dvtk.Sessions.Session theSession, bool changed) { SessionInformation theSessionInformation = GetSessionInformation(theSession); if (theSessionInformation == null) { // Sanity check. Debug.Assert(false); } else { theSessionInformation.HasChanged = changed; } }
public Task AbandonTaskOrchestrationWorkItemAsync(TaskOrchestrationWorkItem workItem) { SessionInformation sessionInfo = TryRemoveSessionInfo(workItem.InstanceId); if (sessionInfo == null) { ServiceFabricProviderEventSource.Tracing.UnexpectedCodeCondition($"{nameof(AbandonTaskOrchestrationWorkItemAsync)} : Could not get a session info object while trying to abandon session {workItem.InstanceId}"); } else { this.orchestrationProvider.TryUnlockSession(sessionInfo.Instance, abandon: true); } return(Task.CompletedTask); }
public void Add(string inventoryItem) { var InventoryItems = Request.Cookies["InventoryItems"]; if (InventoryItems == null) { HttpCookie Inventory = SessionInformation.CreateCookie("InventoryItems", inventoryItem); Response.Cookies.Add(Inventory); } else { InventoryItems.Value = InventoryItems.Value + "+" + inventoryItem; Response.Cookies.Add(InventoryItems); } }
// TODO: Implement a function in Dvtk to unload a session file. public void RemoveSession(Dvtk.Sessions.Session theSession) { SessionInformation theSessionInformation = GetSessionInformation(theSession); if (theSessionInformation == null) { // Sanity check. Debug.Assert(false); } else { _LoadedSessions.Remove(theSessionInformation); _HasProjectChanged = true; } }
public async Task <IAuthedResult <SessionResponse> > VerifySessionAsync(SessionInformation sessionInformation) { sessionInformation.GuardAgainstNull(); using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, "session")) { requestMessage.Content = new FormUrlEncodedContent(new Dictionary <string, string> { { "userSession", sessionInformation.UserSession } }); requestMessage.Headers.Add("Session", sessionInformation.Session); return(await _requester.SendRequestAsync <SessionResponse>(requestMessage).ConfigureAwait(false)); } }
private SessionInformation GetSessionInformation(int theIndex) { SessionInformation theSessionInformation = null; if ((theIndex < 0) || (theIndex >= _LoadedSessions.Count)) { // Sanity check. Debug.Assert(false); } else { theSessionInformation = (SessionInformation)(_LoadedSessions[theIndex]); } return(theSessionInformation); }
private int GetLoadedSessionsIndex(Dvtk.Sessions.Session theSession) { int theReturnValue = -1; for (int theIndex = 0; theIndex < _LoadedSessions.Count; theIndex++) { SessionInformation theSessionInformation = (SessionInformation)_LoadedSessions[theIndex]; if (theSessionInformation.Session == theSession) { theReturnValue = theIndex; break; } } return(theReturnValue); }
/// <summary> /// Save the session under a new file name. /// /// A new session object will be created from this new saved file (and returned by this method) /// and added to the project. The original session wil not be saved. /// </summary> /// <param name="theCurrentSession"></param> /// <returns>The new created session object, null if save as a new session has been cancelled or failed.</returns> public Dvtk.Sessions.Session SaveSessionAs(Dvtk.Sessions.Session theCurrentSession) { Dvtk.Sessions.Session theNewSession = null; SaveFileDialog theSaveFileDialog = new SaveFileDialog(); theSaveFileDialog.AddExtension = true; theSaveFileDialog.DefaultExt = ".ses"; theSaveFileDialog.OverwritePrompt = false; theSaveFileDialog.Filter = "All session files (*.ses)|*.ses"; DialogResult theDialogResult = theSaveFileDialog.ShowDialog(); // User has specified a file name and has pressed the OK button. if (theDialogResult == DialogResult.OK) { if (File.Exists(theSaveFileDialog.FileName)) { MessageBox.Show(string.Format("File name \"{0}\" already exists.\nOperation cancelled", theSaveFileDialog.FileName)); } else { // Save the current session to a new file. string theCurrentSessionFullFileName = theCurrentSession.SessionFileName; theCurrentSession.SessionFileName = theSaveFileDialog.FileName; theCurrentSession.SaveToFile(); theCurrentSession.SessionFileName = theCurrentSessionFullFileName; // Create a new session object from this new saved file and replace the current session. theNewSession = LoadSession(theSaveFileDialog.FileName); if (theNewSession != null) { int theCurrentIndex = GetLoadedSessionsIndex(theCurrentSession); _LoadedSessions[theCurrentIndex] = new SessionInformation(theNewSession); _HasProjectChanged = true; } } } return(theNewSession); }
/// <summary> /// Select motion from the list of possible mixing motions. Only accepts valid motions. /// </summary> /// <param name="motionID"></param> private void SelectMotion(int motionID) { bool invalid = motionID >= m_PossibleMixingMotions.Length || motionID < 0; if (!invalid) { SessionInformation info = LogicManager.CurrentSessionInfo; info.MotionOfSession = m_PossibleMixingMotions[motionID]; LogicManager.CurrentSessionInfo = info; ActivateMotionDetector(false); StartCoroutine(OnDisplaySelectedMotion(motionID)); } else { print("Invalid motion ID"); } }
public bool GetSessionChanged(Dvtk.Sessions.Session theSession) { bool theReturnValue = false; SessionInformation theSessionInformation = GetSessionInformation(theSession); if (theSessionInformation == null) { // Sanity check. Debug.Assert(false); } else { theReturnValue = theSessionInformation.HasChanged; } return(theReturnValue); }
private static async Task <User> GetUserDetailsAsync(IAuthedService authedService, string userSession, string session) { var clientEndpoint = authedService.ClientEndpoint; var sessionInformation = new SessionInformation { UserSession = userSession, Session = session }; var userResponse = await clientEndpoint.GetUserDetailsAsync(sessionInformation); if (userResponse.Success && userResponse.Response.Code == 200) { return(userResponse.Response.User); } return(null); }
private static async Task <string> VerifySessionAsync(IAuthedService authedService, string userSession, string session) { var clientEndpoint = authedService.ClientEndpoint; var sessionInformation = new SessionInformation { UserSession = userSession, Session = session }; var verifySessionResponse = await clientEndpoint.VerifySessionAsync(sessionInformation); if (verifySessionResponse.Success && verifySessionResponse.Response.Code == 200) { return(verifySessionResponse.Response.UserSession); } return(string.Empty); }
public async static Task <SessionInformation> GetSessionTokenAndMerchantGuid() { var allTokens = await Database.Sessions.GetEntitiesAsync(); if (_merchantGuid == null || _sessionToken == null || _email == null) { if (allTokens.Any() && (allTokens.Any(t => t.IsCurrent) || allTokens.Count == 1)) { _merchantGuid = allTokens.OrderByDescending(t => t.IsCurrent).First().MerchantGuid; _sessionToken = allTokens.OrderByDescending(t => t.IsCurrent).First().SessionToken; _email = allTokens.OrderByDescending(t => t.IsCurrent).First().Email; } } var info = new SessionInformation { MerchantGuid = _merchantGuid, SessionToken = _sessionToken, Email = _email }; return(info); }
/// <summary> /// создать/обновить сессию игрока /// </summary> /// <param name="sessionId">идентификатор игрока</param> /// <param name="userName">имя игрока</param> /// <param name="roleId">идентификатор роли</param> /// <param name="callback">интерфейс обратного вызова</param> /// <param name="session">данные сессии</param> /// <returns></returns> public static bool CreateOrUpdateSession(string sessionId, string userName, string roleId, IClientNotification callback, out SessionInformation session) { if (string.IsNullOrEmpty(sessionId)) { throw new ArgumentException("sessionId is null or empty"); } if (string.IsNullOrEmpty(userName)) { throw new ArgumentException("userName is null or empty"); } if (string.IsNullOrEmpty(roleId)) { throw new ArgumentException("roleId is null or empty"); } sessionLock.EnterWriteLock(); try { bool isNewSession = !sessions.TryGetValue(sessionId, out session); if (isNewSession) { session = new SessionInformation(); sessions.Add(sessionId, session); } session.SessionId = sessionId; session.UserName = userName; session.RoleId = roleId; session.Callback = callback; session.IsActive = true; session.LastSyncTime = DateTime.Now; return(isNewSession); } finally { sessionLock.ExitWriteLock(); } }
/// <summary> /// Implements the <see cref="ProcessRecord"/> method for <see cref="GetTransmissionSessionCmdlet"/>. /// </summary> protected override void ProcessRecord() { try { var sessionSvc = new SessionService(); SessionInformation sessionInfo = Task.Run(async() => await sessionSvc.Get()).Result; if (Json) { WriteObject(JsonConvert.SerializeObject(sessionInfo)); } else { WriteObject(sessionInfo); } } catch (Exception e) { ThrowTerminatingError(new ErrorRecord(new Exception($"Failed to retrieve session information with error: {e.Message}", e), null, ErrorCategory.OperationStopped, null)); } }
public SessionData GetCurrent(object sender) { var sessionId = SessionInformation.GetSession(); if (sessionId < SessionInformation.NoSession) { var sd = new SessionData(sessionId, Kind.Unknown, sender); var state = SessionInformation.GetSessionLockState(sessionId); var isLocked = state == SessionInformation.LockState.Locked; if (isLocked) { sd.Reason = Kind.Locked; } else { sd.Reason = Kind.Active; } return(sd); } return(null); }
public void Add(SessionData data) { var quit = data.Spent == TimeSpan.Zero; if (data.Reason == Kind.Locked) { quit |= LogOnce(_marker, "loggerLocked", () => Log.TraceFormat("session is locked, ignoring. sender:{0}", data.Sender)); } if (data.Reason == Kind.Connected) { quit |= true; Log.TraceFormat("session was connected, ignoring. sender:{0}", data.Sender); } if (!quit && data.User.IsEmpty()) { data.User = SessionInformation.GetUsernameBySessionId(data.SessionID, false); } if ("SYSTEM".Equals(data.User, StringComparison.OrdinalIgnoreCase) || data.User.IsEmpty()) { quit |= LogOnce(_marker, "systemLocked", () => Log.TraceFormat("no user data (system), ignoring. sender:{0}", data.Sender)); } if (quit) { return; } _marker.Clear(); if (data.Reason != Kind.Active) // like Connected { Log.DebugFormat("adding session data reason:{0} spent:{1}", data.Reason, data.Spent); } _items.Enqueue(data); }
public LoadAccountsCommand(SessionInformation userSession) : base(userSession) { }
public LoadBaseDataCommand(SessionInformation userSession) : base(userSession) { }
public LoadUserGlobalsCommand(AccountInformation account, string moduleId, SessionInformation userSession) : base(userSession) { _moduleId = moduleId; _account = account; }
public async Task CompleteTaskOrchestrationWorkItemAsync( TaskOrchestrationWorkItem workItem, OrchestrationRuntimeState newOrchestrationRuntimeState, IList <TaskMessage> outboundMessages, IList <TaskMessage> orchestratorMessages, IList <TaskMessage> timerMessages, TaskMessage continuedAsNewMessage, OrchestrationState orchestrationState) { SessionInformation sessionInfo = GetSessionInfo(workItem.InstanceId); ServiceFabricProviderEventSource.Tracing.LogOrchestrationInformation(workItem.InstanceId, workItem.OrchestrationRuntimeState.OrchestrationInstance?.ExecutionId, $"Current orchestration status: {workItem.OrchestrationRuntimeState.OrchestrationStatus}"); bool isComplete = this.IsOrchestrationComplete(workItem.OrchestrationRuntimeState.OrchestrationStatus); IList <OrchestrationInstance> sessionsToEnqueue = null; List <Message <Guid, TaskMessageItem> > scheduledMessages = null; List <Message <string, TaskMessageItem> > activityMessages = null; await RetryHelper.ExecuteWithRetryOnTransient(async() => { bool retryOnException; do { try { retryOnException = false; sessionsToEnqueue = null; scheduledMessages = null; activityMessages = null; using (var txn = this.stateManager.CreateTransaction()) { if (outboundMessages?.Count > 0) { activityMessages = outboundMessages.Select(m => new Message <string, TaskMessageItem>(Guid.NewGuid().ToString(), new TaskMessageItem(m))).ToList(); await this.activitiesProvider.SendBatchBeginAsync(txn, activityMessages); } if (timerMessages?.Count > 0) { scheduledMessages = timerMessages.Select(m => new Message <Guid, TaskMessageItem>(Guid.NewGuid(), new TaskMessageItem(m))).ToList(); await this.scheduledMessagesProvider.SendBatchBeginAsync(txn, scheduledMessages); } if (orchestratorMessages?.Count > 0) { if (workItem.OrchestrationRuntimeState?.ParentInstance != null) { sessionsToEnqueue = await this.orchestrationProvider.TryAppendMessageBatchAsync(txn, orchestratorMessages.Select(tm => new TaskMessageItem(tm))); } else { await this.orchestrationProvider.AppendMessageBatchAsync(txn, orchestratorMessages.Select(tm => new TaskMessageItem(tm))); sessionsToEnqueue = orchestratorMessages.Select(m => m.OrchestrationInstance).ToList(); } } if (continuedAsNewMessage != null) { await this.orchestrationProvider.AppendMessageAsync(txn, new TaskMessageItem(continuedAsNewMessage)); sessionsToEnqueue = new List <OrchestrationInstance>() { continuedAsNewMessage.OrchestrationInstance }; } await this.orchestrationProvider.CompleteMessages(txn, sessionInfo.Instance, sessionInfo.LockTokens); if (workItem.OrchestrationRuntimeState.OrchestrationStatus == OrchestrationStatus.ContinuedAsNew) { await HandleCompletedOrchestration(workItem); } // When an orchestration is completed, we need to drop the session which involves 2 steps (1) Removing the row from sessions // (2) Dropping the session messages dictionary. The second step is done in background thread for performance so is not // part of transaction. Since it will happen outside the trasanction, if this transaction fails for some reason and we dropped // the session as part of this transaction, we wouldn't have updated the session state but would have lost the messages // in the session messages dictionary which are needed for state to reach complete state (when the orchestration is picked up again in next fetch). // So we don't want to drop session as part of this transaction. // Instead, we drop the session as part of a subsequent different transaction. // However, framework passes us 'null' value for 'newOrchestrationRuntimeState' when orchestration is completed and // if we updated the session state to null and this transaction succeded, and a node failures occurs and we // never call the subsequent transaction, we will lose the runtime state of orchestration and never will be able to // mark it as complete even if it is. So we use the work item's runtime state when 'newOrchestrationRuntimeState' is null // so that the latest state is what is stored for the session. // As part of next transaction, we are going to remove the row anyway for the session and it doesn't matter to update it to 'null'. await this.orchestrationProvider.UpdateSessionState(txn, newOrchestrationRuntimeState.OrchestrationInstance, newOrchestrationRuntimeState ?? workItem.OrchestrationRuntimeState); // We skip writing to instanceStore when orchestration reached terminal state to avoid a minor timing issue that // wait for an orchestration completes but another orchestration with the same name cannot be started immediately // because the session is still in store. We update the instance store on orchestration completion and drop the // session as part of the next atomic transaction. if (this.instanceStore != null && orchestrationState != null && !isComplete) { await this.instanceStore.WriteEntitiesAsync(txn, new InstanceEntityBase[] { new OrchestrationStateInstanceEntity() { State = orchestrationState } }); } await txn.CommitAsync(); } } catch (FabricReplicationOperationTooLargeException ex) { ServiceFabricProviderEventSource.Tracing.ExceptionInReliableCollectionOperations($"OrchestrationInstance = {sessionInfo.Instance}, Action = {nameof(CompleteTaskOrchestrationWorkItemAsync)}", ex.ToString()); retryOnException = true; newOrchestrationRuntimeState = null; outboundMessages = null; timerMessages = null; orchestratorMessages = null; if (orchestrationState != null) { orchestrationState.OrchestrationStatus = OrchestrationStatus.Failed; orchestrationState.Output = $"Fabric exception when trying to process orchestration: {ex}. Investigate and consider reducing the serialization size of orchestration inputs/outputs/overall length to avoid the issue."; } } } while (retryOnException); }, uniqueActionIdentifier : $"OrchestrationId = '{workItem.InstanceId}', Action = '{nameof(CompleteTaskOrchestrationWorkItemAsync)}'"); if (activityMessages != null) { this.activitiesProvider.SendBatchComplete(activityMessages); } if (scheduledMessages != null) { this.scheduledMessagesProvider.SendBatchComplete(scheduledMessages); } if (sessionsToEnqueue != null) { foreach (var instance in sessionsToEnqueue) { this.orchestrationProvider.TryEnqueueSession(instance); } } if (isComplete) { await HandleCompletedOrchestration(workItem); } }
public LoadUserProfileCommand(SessionInformation userSession) : base(userSession) { }
/// <summary> /// Set session /// </summary> private void SetSession(Platform type) { SessionInformation = _sessionFactory.GetUserSessionCollector().GetSession(); SessionInformation.OS = type.ToString(); SessionInformation.Offline = false; }
public AbstractLoadCommand(SessionInformation userSession) { _userSession = userSession; }