public void ServerSocketStopsSendingData() { int callbackCount = 0; ManualResetEvent callbackInvokedEvent = new ManualResetEvent( false ); Mock<INetworkFacade> mockFacade = new Mock<INetworkFacade>(); mockFacade.Setup( m => m.BeginReceive( It.IsAny<Action<bool, byte[], INetworkFacade>>() ) ) .Callback<Action<bool, byte[], INetworkFacade>>( callback => { if ( callbackCount++ == 0 ) { callbackInvokedEvent.Set(); callback( true, null, mockFacade.Object ); } } ); ServerSession session = new ServerSession(); session.Start( mockFacade.Object ); Assert.That( callbackInvokedEvent.WaitOne( 1000 ) ); Assert.That( session.HasStoppedSendingData ); Assert.That( !session.HasClosed ); Assert.That( session.LastResponseHeader, Is.Null ); }
public void ServerSocketFailsToSend() { int callbackCount = 0; ManualResetEvent callbackInvokedEvent = new ManualResetEvent(false); Mock<INetworkFacade> mockFacade = new Mock<INetworkFacade>(); mockFacade.Setup(m => m.BeginReceive(It.IsAny<Action<bool, byte[], INetworkFacade>>())) .Callback<Action<bool, byte[], INetworkFacade>>(callback => { if (callbackCount++ == 0) { callbackInvokedEvent.Set(); callback(false, null, mockFacade.Object); } }); ServerSession session = new ServerSession(); session.Start(mockFacade.Object); Assert.That(callbackInvokedEvent.WaitOne(1000)); Assert.That(session.LastResponseHeader, Is.Null); mockFacade.Verify(m=>m.BeginClose(It.IsAny<Action<bool,INetworkFacade>>()), Times.Once()); }
public override void Terminate() { ServerSession.Instance = null; if (ClientSession.Instance != null) { ClientSession.Instance.Disconnect(); } }
static void Main() { MinecraftNetSession login = new MinecraftNetSession( "Username", "Password" ); login.Login(); ServerInfo data = login.GetServerInfo( "f4e8bee64595a29f61cacd2fdae8479" ); ServerSession session = new ServerSession( data ); session.Connect( false ); }
public PlayerData GetPlayerDataBySession(ServerSession session) { if (onLineSessionDic.TryGetValue(session, out PlayerData playerData)) { return(playerData); } else { return(null); } }
public void AddMsgQue(ServerSession _session, GameMsg _msg) { lock (obj) { MsgPack pack = (new MsgPack { session = _session, msg = _msg }); msgPackQue.Enqueue(pack); } }
public WeaponsActor(ServerSession session, PlayerCharactersActor charactersActor) : base(session) { this.charactersActor = charactersActor; weaponShops = new Dictionary <int, WeaponShop>(); weaponShopPrefab = Resources.Load <WeaponShop>("Prefabs/Weapons/weapon_picker"); charactersActor.OnPlayerEntitySpawned += AllowWeaponForCharacter; charactersActor.OnPlayerEntityDestroy += DestroyWeaponShop; LoadResources(); }
/// <summary> /// Sends the report. /// </summary> /// <param name="xmlString">The XML string.</param> public void SendReport(string xmlString) { #if PORTING UPMail mail = new UPMail(); mail.Subject = "Sync-conflict reports"; mail.AddRecipient(((UPMSyncConflictsPage)this.Page).SyncConflictEmail); string filename = $"SyncConflicts_{ServerSession.CurrentSession().UserName}_{StringExtensions.CrmValueFromDate(DateTime.UtcNow)}.xml"; UPMailAttachment attachment = new UPMailAttachment(xmlString, "application/xml", filename); mail.AddAttachment(attachment); this.ModelControllerDelegate.SendMailModal(mail, false); #endif }
/// <summary> /// Speichert eine Sitzung. /// </summary> /// <param name="session">Sitzungsdaten</param> public void StoreSession(ServerSession session) { // Wenn die Sitzung noch nicht gespeichert ist ... if (!ExistSession(session.SessionID)) { lock (_sessionLock) { // Sitzung der Sitzungsliste zufüen _sessions.Add(session.SessionID, session); } } }
public HttpSysListener(HttpSysOptions options, ILoggerFactory loggerFactory) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (!HttpApi.Supported) { throw new PlatformNotSupportedException(); } Debug.Assert(HttpApi.ApiVersion == HttpApiTypes.HTTP_API_VERSION.Version20, "Invalid Http api version"); Options = options; Logger = loggerFactory.CreateLogger <HttpSysListener>(); _state = State.Stopped; _internalLock = new object(); // V2 initialization sequence: // 1. Create server session // 2. Create url group // 3. Create request queue // 4. Add urls to url group - Done in Start() // 5. Attach request queue to url group - Done in Start() try { _serverSession = new ServerSession(); _requestQueue = new RequestQueue(options.RequestQueueName, options.RequestQueueMode, Logger); _urlGroup = new UrlGroup(_serverSession, _requestQueue, Logger); _disconnectListener = new DisconnectListener(_requestQueue, Logger); } catch (Exception exception) { // If Url group or request queue creation failed, close server session before throwing. _requestQueue?.Dispose(); _urlGroup?.Dispose(); _serverSession?.Dispose(); Log.HttpSysListenerCtorError(Logger, exception); throw; } }
public FrontendSession GetFrontendSession(ServerSession session) { lock (_sessions) { FrontendSession localSession = _sessions[session] as FrontendSession; if (localSession == null) { localSession = new FrontendSession(this, session); _sessions.Add(session, localSession); } return(localSession); } }
/// <summary> /// Attaches the debugger to a session. /// </summary> /// <remarks> /// When the debugger is attached to a session, all running processes on that session /// are attached to the debugger. In addition, any processes subsequently started /// on that session are automatically attached to the debugger. /// </remarks> public void AttachSession(ServerSession session) { lock (_syncHandle) { session.SetDebuggedByID(DebuggerID); _sessions.Add(session); lock (session.Processes) foreach (ServerProcess process in session.Processes) { Attach(process); } } }
public ServerSession Generate() { lock (_lock) { ServerSession session = new ServerSession(); session.DummyId = _dummyId; _dummyId++; _sessions.Add(session); Console.WriteLine($"Connected({_sessions.Count}) Players"); return(session); } }
/// <summary> /// 当账号下线时. /// </summary> /// <param name="session">Session.</param> public void AccountOffLine(ServerSession session) { foreach (var item in onlineAccountDict) { if (item.Value == session) { onlineAccountDict.Remove(item.Key); break; } } onlineSessionDict.Remove(session); }
public override bool Handle(ServerSession session, int length, int opcode, byte[] data) { // Inform the user that an undefined packet is received Console.WriteLine("[Unhandled packet, Opcode: {0}, Length: {1}, Data: ", opcode, length); // Convert the byte array to a string string dataString = BitConverter.ToString(data); // Write the packet data, in hex form Console.WriteLine(String.Format("{0,10:X}]", dataString)); return(true); }
public void ClearOfflineData(ServerSession session) { PlayerData pd = cacheSvc.GetPlayerDataBySession(session); if (pd != null) { pd.time = TimerSvc.Instance.GetNowTime(); if (!cacheSvc.UpdatePlayerData(pd.id, pd)) { Common.Log("Update offline time error", LogType.Error); } } cacheSvc.AcctOffLine(session); }
/// <summary> /// Called whenever an OnReceive event is received by the server, which signifies /// an incoming packet from an existing connection. /// </summary> /// <param name="session">The connection's session</param> /// <param name="data"></param> /// <param name="bytesRead"></param> private bool OnRecieve(ServerSession session, byte[] data, int bytesRead) { int packetLength = ((data[0] & 0xFF) + ((data[1] & 0xFF) << 8)); int packetOpcode = ((data[2] & 0xFF) + ((data[3] & 0xFF) << 8)); byte[] packetData = new byte[packetLength - 4]; Array.Copy(data, 4, packetData, 0, packetLength - 4); var handler = _packetManager.GetHandler(packetOpcode); // Handle the incoming packet return(handler.Handle(session, packetLength - 4, packetOpcode, packetData)); }
public void AccOffLine(ServerSession session) { foreach (var item in onLineAccDic) { if (item.Value == session) { onLineAccDic.Remove(item.Key); break; } } bool succ = onlineSessionDic.Remove(session); PECommon.Log("ID:" + session.sessionID + "的客户端移除结果:" + succ); }
public void ClearOffLineData(ServerSession session) { PlayerData playerData = _cacheSvc.GetPlayerDataBySession(session); if (playerData != null) { playerData.Time = _timeSvc.GetNowTime(); if (!_cacheSvc.UpdatePlayerData(playerData.Id, playerData)) { PeRoot.Log("Update offline time error", LogType.LogError); } _cacheSvc.AcctOffLine(session); } }
public void ClearOfflineData(ServerSession serverSession) { PlayerData playerData = cacheSvc.GetPlayerDataCache(serverSession); if (playerData != null) { playerData.time = timeSvc.GetNowTime(); if (!cacheSvc.UpdatePlayerData(playerData.id, playerData)) { PECommon.Log("Update OffLine Time Error", LogType.Error); } cacheSvc.ClearOffLineData(serverSession); } }
public int UploadSession(ServerSession mySession) { Console.WriteLine(mySession.ToString()); int id = mySession.InsertAtDB(false, Constants.SessionTable); try { File.Create("need-to-update-r-graphs"); } catch { //file exists and cannot be overwritten } return(id); //uniqueID of session at server }
/// <summary> /// 清除下线账号缓存数据 /// </summary> /// <param name="svcSession"></param> public void ClearOfflineData(ServerSession svcSession) { PlayerData playerData = cacheSvc.GetPlayerDataBySession(svcSession); if (playerData != null) { playerData.time = TimerSvc.Instance.GetNowTime(); if (!cacheSvc.UpdatePlayerData(playerData.id, playerData)) { CommonTools.Log("Update offline time error", LogType.LogType_Error); } } cacheSvc.ClearOfflineData(svcSession); }
public void ClearOfflineData(ServerSession session) { PlayerData playerData = cacheSvc.GetPlayerDataBySession(session); if (playerData != null) { playerData.time = timerSvc.GetNowTime(); if (cacheSvc.UpdatePlayerData(playerData.id, playerData) == false) { Common.Log("Update offline time error", LogType.Error); } cacheSvc.AcctOffline(session); } }
public void AcctOffLine(ServerSession session) { foreach (var item in onLineAcctDic) { if (item.Value == session) { onLineAcctDic.Remove(item.Key); break; } } bool succ = onLineSessionDic.Remove(session); PECommon.Log($"Offline Result: SessionID:{session.sessionID} {succ}"); }
public ServerSession GetOnlineServerSessions(int ID) { ServerSession session = null; foreach (var item in onLineSessionDic) { if (item.Value.id == ID) { session = item.Key; break; } } return(session); }
/// <summary> /// 玩家下线处理 /// </summary> public void AcctOffLine(ServerSession session) { foreach (var item in onLineAcctDic) { if (item.Value == session) { onLineAcctDic.Remove(item.Key); break; } } bool success = onLineSessionDic.Remove(session); PeRoot.Log("Offline Result: SessionID:" + session.sessionId + " " + success); }
public void AcctOffLine(ServerSession serverSession) { foreach (var item in onLineAcct) { if (item.Value == serverSession) { onLineAcct.Remove(item.Key); break; } } bool succ = onLineSessionDic.Remove(serverSession); PECommon.Log("账号下线,Session:" + serverSession.session); }
/// <summary> /// Handles an incoming request to check an available character name. /// </summary> /// <param name="session">The session instance</param> /// <param name="length">The length of the packet</param> /// <param name="opcode">The opcode of the incoming packet</param> /// <param name="data">The packet data</param> /// <returns></returns> public override bool Handle(ServerSession session, int length, int opcode, byte[] data) { byte[] characterName = new byte[length - 1]; Array.Copy(data, 0, characterName, 0, length - 1); string name = Encoding.UTF8.GetString(characterName); var player = GameService.GetPlayerForIndex(session.GetGameIndex()); GameService.PushTask(new CheckAvailableNameTask(player, name)); return(true); }
public void ClearOffline(ServerSession session) { PlayerData pd = CacheSvc.Instance.GetPlayerDataBySession(session); if (pd != null) { pd.time = TimeSvc.Instance.GetNowTime(); if (!CacheSvc.Instance.UpdatePlayerData(pd.id, pd, session)) { PECommon.Log("Update offline time Error"); } CacheSvc.Instance.AcctOffline(session); } }
/// <summary> /// Handles the creation of a character. /// </summary> /// <param name="session">The session instance</param> /// <param name="length">The length of the packet</param> /// <param name="opcode">The opcode of the incoming packet</param> /// <param name="requestId"></param> /// <param name="data">The packet data</param> /// <returns></returns> public override bool Handle(ServerSession session, int length, int opcode, int requestId, byte[] data) { var request = new CreateCharacterRequest(); int serverId = data[0]; int userId = (data[1] & 0xFF) + ((data[2] & 0xFF) << 8) + ((data[3] & 0xFF) << 16) + ((data[4] & 0xFF) << 24); request = Serializer.Deserialize <CreateCharacterRequest>(data.Skip(5).ToArray()); using (SqlConnection connection = new DatabaseConnector().GetConnection("origin_gamedata")) { var cmd = new SqlCommand("create_character", connection); cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.AddWithValue(":server_id", serverId); cmd.Parameters.AddWithValue(":user_id", userId); cmd.Parameters.AddWithValue(":character_name", Encoding.UTF8.GetString(request.name).TrimEnd('\0')); cmd.Parameters.AddWithValue(":race", request.race); cmd.Parameters.AddWithValue(":mode", request.mode); cmd.Parameters.AddWithValue(":profession", request.profession); cmd.Parameters.AddWithValue(":hair", request.hair); cmd.Parameters.AddWithValue(":face", request.face); cmd.Parameters.AddWithValue(":height", request.height); cmd.Parameters.AddWithValue(":sex", request.sex); connection.Open(); // Execute the prepared statement var reader = cmd.ExecuteReader(); // Loop through the results while (reader.Read()) { var bldr = new PacketBuilder(opcode); bldr.WriteInt(requestId); // Write the result bldr.WriteByte((byte)reader.GetInt32(0)); session.Write(bldr.ToPacket()); } reader.Close(); } return(true); }
public void AcctOffline(ServerSession session) { foreach (var item in onlineAcctDic) { if (item.Value == session) { onlineAcctDic.Remove(item.Key); break; } } bool succ = onlineSessionPdDic.Remove(session); Common.Log("Offline Result:SessionID = " + session.SessionID + " result = " + succ); }
public void CachePlayerData(string acct, PlayerData data, ServerSession ses) { if (!onlinePlayerSessionDic.ContainsKey(acct)) { onlinePlayerSessionDic.Add(acct, ses); } if (!onlinePlayerDataDic.ContainsKey(ses)) { onlinePlayerDataDic.Add(ses, data); } if (!onlineSessionList.Contains(ses)) { onlineSessionList.Add(ses); } }
public ServerSession GetServerSessionByID(int id) { ServerSession session = null; foreach (var item in onLineSessionDic) { if (item.Value.id == id) { session = item.Key; break; } } return(session); }
public void AcctOffline(ServerSession session) { foreach (var item in onLineAcctDic) { if (item.Value == session) { onLineAcctDic.Remove(item.Key); break; } } bool ret = onLineSessionDic.Remove(session); PECommon.Log("Offline Result:" + ret + "SessionID:" + session.SessionID); }
public void VerifyExplicitClose() { Mock<INetworkFacade> mockFacade = new Mock<INetworkFacade>(); mockFacade.Setup( m => m.BeginClose( It.IsAny<Action<bool, INetworkFacade>>() ) ) .Callback<Action<bool, INetworkFacade>>( callback => callback( true, mockFacade.Object ) ); ServerSession session = new ServerSession(); session.Start( mockFacade.Object ); session.Close(); Assert.That( session.HasClosed ); mockFacade.Verify( m => m.BeginClose( It.IsAny<Action<bool, INetworkFacade>>() ), Times.Once() ); }
public DataModel(MainWindow mainWindow) { MainWindow = mainWindow; ServerList = new ServerList(); ServerSession = new ServerSession(this); ServerStatus = new ServerStatus(this); Database = new Database(this); QuickSearch = new QuickSearch(this); AdvancedSearch = new AdvancedSearch(this); DatabaseView = new DatabaseView(this); StreamsCollection = new StreamsCollection(); SavedPlaylists = new SavedPlaylists(this); CurrentSong = new CurrentSong(this); Playlist = new Playlist(this); OutputCollection = new OutputCollection(this); CustomDateNormalizer = new DateNormalizer(); CustomDateNormalizer.ReadFromSettings(); YearNormalizer = new DateNormalizer(new string[] {"YYYY"}); }
public void UploadSessionAsync(ServerSession mySession, object userState) { if ((this.UploadSessionOperationCompleted == null)) { this.UploadSessionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUploadSessionCompleted); } this.InvokeAsync("UploadSession", new object[] { mySession}, this.UploadSessionOperationCompleted, userState); }
public int UploadSession(ServerSession mySession) { object[] results = this.Invoke("UploadSession", new object[] { mySession}); return ((int)(results[0])); }
public void UploadSessionAsync(ServerSession mySession) { this.UploadSessionAsync(mySession, null); }
public RentalProcesses( ServerSession session ) : base( session ) { this.customerProcesses = new CustomerProcesses( session ); }
public EmployeeProcesses( ServerSession session ) : base( session ) { }
public void VerifyStartBehavior() { Mock<INetworkFacade> mockFacade = new Mock<INetworkFacade>(); ServerSession session = new ServerSession(); session.Start( mockFacade.Object ); Assert.That( !session.HasClosed ); Assert.That( !session.HasStoppedSendingData ); Assert.That( session.Connection, Is.SameAs( mockFacade.Object ) ); Assert.That( session.LastResponseHeader, Is.Null ); }
/// <summary> /// Speichert eine Sitzung in der SQL Server Datenbank ab. /// </summary> /// <param name="session">Sitzungsobjekt</param> private void StoreSessionOnSqlServer(ServerSession session) { // Transaktion erzwingen using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead })) { // Wenn keine Sitzung angegeben wurde ... if (session == null) // Ausnahme werfen throw new ArgumentNullException("session"); // Verbindung zum SQL Server herstellen using (SqlConnection connection = new SqlConnection(_connectionString)) { // SQL-Stapel zum Löschen und Neuanlegen der Sitzung zusammenstellen StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.AppendFormat("DELETE FROM [{0}].[{1}] WHERE SessionID=@sessionID; ", _sqlSchema, _sqlSessionTableName); sqlBuilder.AppendFormat("INSERT [{0}].[{1}] (SessionID,SessionTimestamp,IdentityName) ", _sqlSchema, _sqlSessionTableName); sqlBuilder.Append("VALUES (@sessionID,@sessionTimestamp,@identityName)"); // SQL-Befehl erzeugen using (SqlCommand command = new SqlCommand(sqlBuilder.ToString(), connection)) { // Eingabeparameter erzeugen command.Parameters.Add("@sessionID", SqlDbType.UniqueIdentifier).Value = session.SessionID; command.Parameters.Add("@sessionTimestamp", SqlDbType.DateTime).Value = session.Timestamp; command.Parameters.Add("@identityName", SqlDbType.NVarChar, 255).Value = session.Identity.Name; // Sitzung speichern connection.Open(); command.ExecuteNonQuery(); connection.Close(); // Transaktion abschließen scope.Complete(); } } } }
private void RenewSessionOnSqlServer(ServerSession session) { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead })) { using (SqlConnection connection = new SqlConnection(_connectionString)) { // Prepare the SQL statement StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.AppendFormat("UPDATE [{0}].[{1}] SET SessionTimestamp=@sessionTimestamp WHERE SessionID=@sessionID", _sqlSchema, _sqlSessionTableName); using (SqlCommand command = new SqlCommand(sqlBuilder.ToString(), connection)) { command.Parameters.Add("@sessionID", SqlDbType.UniqueIdentifier).Value = session.SessionID; command.Parameters.Add("@sessionTimestamp", SqlDbType.DateTime).Value = session.Timestamp; // Execute the statement and commit the transaction connection.Open(); command.ExecuteNonQuery(); connection.Close(); scope.Complete(); } } } }
/// <summary> /// Renews the given session. /// </summary> /// <param name="session">The <see cref="ServerSession"/> to renew.</param> public virtual void RenewSession(ServerSession session) { session.Timestamp = DateTime.Now; }
public NoteProcesses( ServerSession session ) : base( session ) { }
/// <summary> /// Renews the given session. /// </summary> /// <param name="session">The <see cref="ServerSession" /> to renew.</param> public override void RenewSession(ServerSession session) { base.RenewSession(session); RenewSessionOnSqlServer(session); }
public CashboxProcesses( ServerSession session ) : base( session ) { }
public void VerifyReceiveBehavior() { int callbackCount = 0; Mock<INetworkFacade> mockFacade = new Mock<INetworkFacade>(); byte[] data = Encoding.UTF8.GetBytes( "HTTP/1.1 200 OK\r\nContent-length: 2\r\n\r\nhi" ); mockFacade.Setup( m => m.BeginReceive( It.IsAny<Action<bool, byte[], INetworkFacade>>() ) ) .Callback<Action<bool, byte[], INetworkFacade>>( callback => { if ( callbackCount++ == 0 ) { callback( true, data, mockFacade.Object ); } } ); ServerSession session = new ServerSession(); int fullResponseCount = 0; int responseHeaderCount = 0; int partialDataCount = 0; ManualResetEvent doneParsing = new ManualResetEvent( false ); session.FullResponseReadComplete += ( sender, args ) => { fullResponseCount++; doneParsing.Set(); }; session.HttpResponseHeaderAvailable += ( sender, args ) => { if ( args.StatusCode == 200 ) { responseHeaderCount++; } }; session.PartialDataAvailableForClient += ( sender, args ) => { if ( args.Data[0] == 'h' && args.Data[1] == 'i' ) { partialDataCount++; } }; session.Start( mockFacade.Object ); Assert.That( doneParsing.WaitOne( 2000 ) ); Assert.That( fullResponseCount, Is.EqualTo( 1 ) ); Assert.That( responseHeaderCount, Is.EqualTo( 1 ) ); Assert.That( partialDataCount, Is.EqualTo( 1 ) ); Assert.That( session.LastResponseHeader, Is.Not.Null ); Assert.That( session.LastResponseHeader.Status, Is.EqualTo( 200 ) ); }
public int UploadSession(ServerSession mySession) { Console.WriteLine(mySession.ToString()); int id = mySession.InsertAtDB(false, Constants.SessionTable); try { File.Create("need-to-update-r-graphs"); } catch { //file exists and cannot be overwritten } return id; //uniqueID of session at server }
public System.IAsyncResult BeginUploadSession(ServerSession mySession, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UploadSession", new object[] { mySession}, callback, asyncState); }
public void Awake() { Instance = this; }
public void VerifySocketClose() { Mock<INetworkFacade> mockFacade = new Mock<INetworkFacade>(); ServerSession session = new ServerSession(); session.Start( mockFacade.Object ); mockFacade.Raise( m => m.ConnectionClosed += null, new EventArgs() ); Assert.That( session.HasClosed ); }
/// <summary> /// Stores the given <see cref="ServerSession"/> to the session list. /// </summary> /// <param name="session"><see cref="ServerSession"/> to store.</param> public override void StoreSession(ServerSession session) { StoreSessionOnSqlServer(session); }
public BookProcesses( ServerSession session ) : base( session ) { }
private void StoreSessionOnSqlServer(ServerSession session) { using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead })) { if (session == null) throw new ArgumentNullException("session"); using (SqlConnection connection = new SqlConnection(_connectionString)) { // Create SQL statement to delete and recreate the session StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.AppendFormat("DELETE FROM [{0}].[{1}] WHERE SessionID=@sessionID; ", _sqlSchema, _sqlSessionTableName); sqlBuilder.AppendFormat("INSERT [{0}].[{1}] (SessionID,SessionTimestamp,IdentityName) ", _sqlSchema, _sqlSessionTableName); sqlBuilder.Append("VALUES (@sessionID,@sessionTimestamp,@identityName)"); using (SqlCommand command = new SqlCommand(sqlBuilder.ToString(), connection)) { command.Parameters.Add("@sessionID", SqlDbType.UniqueIdentifier).Value = session.SessionID; command.Parameters.Add("@sessionTimestamp", SqlDbType.DateTime).Value = session.Timestamp; command.Parameters.Add("@identityName", SqlDbType.NVarChar, 255).Value = session.Identity.Name; // Execute the query and commit the transaction connection.Open(); command.ExecuteNonQuery(); connection.Close(); scope.Complete(); } } } }
/// <summary> /// Sets the current server session. /// </summary> /// <param name="session">The session.</param> public void SetCurrentSession(ServerSession session) { ServerSession.CurrentSession = session; }
/// <summary> /// Stores the given <see cref="ServerSession"/> to the session list. /// </summary> /// <param name="session">The <see cref="ServerSession"/> to store.</param> public abstract void StoreSession(ServerSession session);
private static void on_server_upload_session_started() { int evalSID = Convert.ToInt32(SqlitePreferences.Select("evaluatorServerID")); try { ChronojumpServer myServer = new ChronojumpServer(); Log.WriteLine(myServer.ConnectDatabase()); int state = (int) Constants.ServerSessionStates.UPLOADINGSESSION; //create ServerSession based on Session currentSession ServerSession serverSession = new ServerSession(currentSession, evalSID, progName + " " + progVersion, Util.GetOS(), DateTime.Now, state); //if uploading session for first time if(currentSession.ServerUniqueID == Constants.ServerUndefinedID) { //upload ServerSession int idAtServer = myServer.UploadSession(serverSession); //update session currentSession (serverUniqueID) on client database currentSession.ServerUniqueID = idAtServer; SqliteSession.UpdateServerUniqueID(currentSession.UniqueID, currentSession.ServerUniqueID); } state = (int) Constants.ServerSessionStates.UPLOADINGDATA; myServer.UpdateSession(currentSession.ServerUniqueID, state); sessionUploadPersonData.testTypes = ""; string testTypesSeparator = ""; sessionUploadPersonData.sports = ""; string sportsSeparator = ""; //upload persons (updating also person.serverUniqueID locally) ArrayList persons = SqlitePersonSession.SelectCurrentSessionPersons(serverSession.UniqueID); Constants.UploadCodes uCode; ArrayList notToUpload = SqlitePersonSessionNotUpload.SelectAll(currentSession.UniqueID); //store in variable for updating progressBar from other thread progressBarPersonsNum = persons.Count - notToUpload.Count; foreach(Person p in persons) { Person person = p; //do not continue with this person if has been banned to upload if(Util.FoundInArrayList(notToUpload, person.UniqueID.ToString())) continue; PersonSession ps = SqlitePersonSession.Select(person.UniqueID, currentSession.UniqueID); //check person if exists if(person.ServerUniqueID != Constants.ServerUndefinedID) uCode = Constants.UploadCodes.EXISTS; else { uCode = Constants.UploadCodes.OK; person = serverUploadPerson(myServer, person, serverSession.UniqueID); } //if sport is user defined, upload it //and when upload the person, do it with new sportID Sport sport = SqliteSport.Select(ps.SportID); //but record old sport ID because locally will be a change in serverUniqueID //(with slite update) //but local sport has not to be changed int sportUserDefinedLocal = -1; if(sport.UserDefined) { sportUserDefinedLocal = sport.UniqueID; //this will be uploaded int newSport = myServer.UploadSport(sport); if(newSport != -1) { ps.SportID = newSport; sessionUploadPersonData.sports += sportsSeparator + sport.Name; sportsSeparator = ", "; } } //a person can be in the database for one session, //but maybe now we add jumps from another session and we should add an entry at personsession serverUploadPersonSessionIfNeeded(myServer, person.ServerUniqueID, currentSession.ServerUniqueID, ps, sportUserDefinedLocal); //other thread updates the gui: sessionUploadPersonData.person = person; sessionUploadPersonData.personCode = uCode; //upload jumps int countU = 0; int countE = 0; int countS = 0; string [] jumps = SqliteJump.SelectJumps(currentSession.UniqueID, person.UniqueID, "", ""); Sqlite.Open(); foreach(string myJump in jumps) { string [] js = myJump.Split(new char[] {':'}); //select jump Jump test = SqliteJump.SelectJumpData(Convert.ToInt32(js[1]), true); //uniqueID //fix it to server person, session keys test.PersonID = person.ServerUniqueID; test.SessionID = currentSession.ServerUniqueID; //if test is not simulated and has not been uploaded, //see if it's type is not predefined and is not in the database //then upload it first if(test.Simulated == 0) { //upload jumpType if is user defined and doesn't exists in server database //JumpType type = new JumpType(test.Type); JumpType type = SqliteJumpType.SelectAndReturnJumpType(test.Type, true); if( ! type.IsPredefined) { //Console.WriteLine("USER DEFINED TEST: " + test.Type); // //this uploads the new type, as it's user created, it will be like this //eg: for user defined jumpType: "supra" of evaluatorServerID: 9 //at server will be "supra-9" //then two problems get solved: //1.- every evaluator that uploads a type will have a different name //than other evaluator uploading a type that is named the same but could be different //(one can think that "supra" is another thing //2- when the same evaluator upload some supra's, only a new type is created //test.Type = myServer.UploadJumpType(type, evalSID); //int testType = (int) Constants.TestTypes.JUMP; //string insertedType = myServer.UploadTestType(Constants.TestTypes.JUMP, type, evalSID); //string insertedType = myServer.UploadTestType(testType, type, evalSID); string insertedType = myServer.UploadJumpType(type, evalSID); if(insertedType != "-1") { //record type in test (with the "-7" if it's done by evaluator 7) test.Type = insertedType; //show user uploaded type (without the "-7") sessionUploadPersonData.testTypes += testTypesSeparator + type.Name; testTypesSeparator = ", "; } //test.Type in the server will have the correct name "supra-9" } } //upload... (if not because of simulated or uploaded before, report also the user) uCode = serverUploadTest(myServer, Constants.TestTypes.JUMP, Constants.JumpTable, test); if(uCode == Constants.UploadCodes.OK) countU ++; else if(uCode == Constants.UploadCodes.EXISTS) countE ++; else //SIMULATED countS ++; } Sqlite.Close(); //other thread updates the gui: sessionUploadPersonData.jumpsU = countU; sessionUploadPersonData.jumpsE = countE; sessionUploadPersonData.jumpsS = countS; //upload jumpsRj countU = 0; countE = 0; countS = 0; string [] jumpsRj = SqliteJumpRj.SelectJumps(currentSession.UniqueID, person.UniqueID, "", ""); Sqlite.Open(); foreach(string myJump in jumpsRj) { string [] js = myJump.Split(new char[] {':'}); //select jump JumpRj test = SqliteJumpRj.SelectJumpData(Constants.JumpRjTable, Convert.ToInt32(js[1]), true); //uniqueID //fix it to server person, session keys test.PersonID = person.ServerUniqueID; test.SessionID = currentSession.ServerUniqueID; if(test.Simulated == 0) { JumpType type = SqliteJumpType.SelectAndReturnJumpRjType(test.Type, true); if( ! type.IsPredefined) { string insertedType = myServer.UploadJumpRjType(type, evalSID); if(insertedType != "-1") { test.Type = insertedType; sessionUploadPersonData.testTypes += testTypesSeparator + type.Name; testTypesSeparator = ", "; } } } //upload... uCode = serverUploadTest(myServer, Constants.TestTypes.JUMP_RJ, Constants.JumpRjTable, test); if(uCode == Constants.UploadCodes.OK) countU ++; else if(uCode == Constants.UploadCodes.EXISTS) countE ++; else //SIMULATED countS ++; } Sqlite.Close(); //other thread updates the gui: sessionUploadPersonData.jumpsRjU = countU; sessionUploadPersonData.jumpsRjE = countE; sessionUploadPersonData.jumpsRjS = countS; //upload runs countU = 0; countE = 0; countS = 0; string [] runs = SqliteRun.SelectRuns(currentSession.UniqueID, person.UniqueID, ""); Sqlite.Open(); foreach(string myRun in runs) { string [] js = myRun.Split(new char[] {':'}); //select run Run test = SqliteRun.SelectRunData(Convert.ToInt32(js[1]), true); //uniqueID //fix it to server person, session keys test.PersonID = person.ServerUniqueID; test.SessionID = currentSession.ServerUniqueID; if(test.Simulated == 0) { RunType type = SqliteRunType.SelectAndReturnRunType(test.Type, true); if( ! type.IsPredefined) { string insertedType = myServer.UploadRunType(type, evalSID); if(insertedType != "-1") { test.Type = insertedType; sessionUploadPersonData.testTypes += testTypesSeparator + type.Name; testTypesSeparator = ", "; } } } //upload... uCode = serverUploadTest(myServer, Constants.TestTypes.RUN, Constants.RunTable, test); if(uCode == Constants.UploadCodes.OK) countU ++; else if(uCode == Constants.UploadCodes.EXISTS) countE ++; else //SIMULATED countS ++; } Sqlite.Close(); //other thread updates the gui: sessionUploadPersonData.runsU = countU; sessionUploadPersonData.runsE = countE; sessionUploadPersonData.runsS = countS; //upload runs intervallic countU = 0; countE = 0; countS = 0; string [] runsI = SqliteRunInterval.SelectRuns(currentSession.UniqueID, person.UniqueID, ""); Sqlite.Open(); foreach(string myRun in runsI) { string [] js = myRun.Split(new char[] {':'}); //select run RunInterval test = SqliteRunInterval.SelectRunData(Constants.RunIntervalTable, Convert.ToInt32(js[1]), true); //uniqueID //fix it to server person, session keys test.PersonID = person.ServerUniqueID; test.SessionID = currentSession.ServerUniqueID; if(test.Simulated == 0) { RunType type = SqliteRunIntervalType.SelectAndReturnRunIntervalType(test.Type, true); if( ! type.IsPredefined) { string insertedType = myServer.UploadRunIntervalType(type, evalSID); if(insertedType != "-1") { test.Type = insertedType; sessionUploadPersonData.testTypes += testTypesSeparator + type.Name; testTypesSeparator = ", "; } } } //upload... uCode = serverUploadTest(myServer, Constants.TestTypes.RUN_I, Constants.RunIntervalTable, test); if(uCode == Constants.UploadCodes.OK) countU ++; else if(uCode == Constants.UploadCodes.EXISTS) countE ++; else //SIMULATED countS ++; } Sqlite.Close(); //other thread updates the gui: sessionUploadPersonData.runsIU = countU; sessionUploadPersonData.runsIE = countE; sessionUploadPersonData.runsIS = countS; //upload reaction times countU = 0; countE = 0; countS = 0; string [] rts = SqliteReactionTime.SelectReactionTimes(currentSession.UniqueID, person.UniqueID); Sqlite.Open(); foreach(string myRt in rts) { string [] js = myRt.Split(new char[] {':'}); //select rt ReactionTime test = SqliteReactionTime.SelectReactionTimeData(Convert.ToInt32(js[1]), true); //uniqueID //fix it to server person, session keys test.PersonID = person.ServerUniqueID; test.SessionID = currentSession.ServerUniqueID; //upload... uCode = serverUploadTest(myServer, Constants.TestTypes.RT, Constants.ReactionTimeTable, test); if(uCode == Constants.UploadCodes.OK) countU ++; else if(uCode == Constants.UploadCodes.EXISTS) countE ++; else //SIMULATED countS ++; } Sqlite.Close(); //other thread updates the gui: sessionUploadPersonData.rtsU = countU; sessionUploadPersonData.rtsE = countE; sessionUploadPersonData.rtsS = countS; //upload pulses countU = 0; countE = 0; countS = 0; string [] pulses = SqlitePulse.SelectPulses(currentSession.UniqueID, person.UniqueID); Sqlite.Open(); foreach(string myPulse in pulses) { string [] js = myPulse.Split(new char[] {':'}); //select pulse Pulse test = SqlitePulse.SelectPulseData(Convert.ToInt32(js[1]), true); //uniqueID //fix it to server person, session keys test.PersonID = person.ServerUniqueID; test.SessionID = currentSession.ServerUniqueID; //upload... uCode = serverUploadTest(myServer, Constants.TestTypes.PULSE, Constants.PulseTable, test); if(uCode == Constants.UploadCodes.OK) countU ++; else if(uCode == Constants.UploadCodes.EXISTS) countE ++; else //SIMULATED countS ++; } Sqlite.Close(); //other thread updates the gui: sessionUploadPersonData.pulsesU = countU; sessionUploadPersonData.pulsesE = countE; sessionUploadPersonData.pulsesS = countS; //upload multiChronopic countU = 0; countE = 0; countS = 0; string [] mcs = SqliteMultiChronopic.SelectTests(currentSession.UniqueID, person.UniqueID); Sqlite.Open(); foreach(string mc in mcs) { string [] js = mc.Split(new char[] {':'}); //select mc MultiChronopic test = SqliteMultiChronopic.SelectMultiChronopicData(Convert.ToInt32(js[1]), true); //uniqueID //fix it to server person, session keys test.PersonID = person.ServerUniqueID; test.SessionID = currentSession.ServerUniqueID; //upload... uCode = serverUploadTest(myServer, Constants.TestTypes.MULTICHRONOPIC, Constants.MultiChronopicTable, test); if(uCode == Constants.UploadCodes.OK) countU ++; else if(uCode == Constants.UploadCodes.EXISTS) countE ++; else //SIMULATED countS ++; } Sqlite.Close(); //other thread updates the gui: sessionUploadPersonData.mcsU = countU; sessionUploadPersonData.mcsE = countE; sessionUploadPersonData.mcsS = countS; needUpdateServerSession = true; while(needUpdateServerSession) { //wait until data is printed on the other thread } } state = (int) Constants.ServerSessionStates.DONE; //myServer.UpdateSession(currentSession.ServerUniqueID, (ServerSessionStates) Constants.ServerSessionStates.DONE); myServer.UpdateSession(currentSession.ServerUniqueID, state); Log.WriteLine(myServer.DisConnectDatabase()); } catch { //other thread updates the gui: serverSessionError = true; } }