public SessionChannel(ConnectionService connectionService, uint clientChannelId, uint clientInitialWindowSize, uint clientMaxPacketSize, uint serverChannelId) : base(connectionService, clientChannelId, clientInitialWindowSize, clientMaxPacketSize, serverChannelId) { }
void Awake() { UnityEngine.Cursor.visible = true; if (PlayerPrefs.HasKey("server")) { this.server = PlayerPrefs.GetString("server"); } if (PlayerPrefs.HasKey("username")) { this.username = PlayerPrefs.GetString("username"); } this.connectionService = (ConnectionService) this.gameObject.GetComponent("ConnectionService"); if (this.connectionService != null) { this.connectionService.successResponseHandler = new WebService.SuccessResponseHandler(this.HandleConnectionSuccess); this.connectionService.failureResponseHandler = new WebService.FailureResponseHandler(this.HandleConnectionFailure); } else { Debug.LogWarning("Unable to find ConnectionService. Make sure script is attached."); } PlayerPrefs.SetInt("offline", 0); }
//Called when we receive data void OnData(ConnectionService con, ref NetworkMessage data) { //Decode the data so it is readable data.DecodeData (); //Convert the data to Vector3 (for backwards compatability you have to use Vector3Carriers //here but that will go soon... hopefully) Vector3 pos = (Vector3)(Vector3Carrier)data.data; ushort id = data.subject; //Move the cube cubes [id].GetComponent<Rigidbody> ().MovePosition (pos); }
private DatabaseLocksManager CreateManager() { DatabaseLocksManager databaseLocksManager = new DatabaseLocksManager(2000); var connectionLock1 = new Mock <IConnectedBindingQueue>(); var connectionLock2 = new Mock <IConnectedBindingQueue>(); connectionLock1.Setup(x => x.CloseConnections(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>())); connectionLock2.Setup(x => x.OpenConnections(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>())); connectionLock1.Setup(x => x.OpenConnections(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>())); connectionLock2.Setup(x => x.CloseConnections(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>())); ConnectionService connectionService = new ConnectionService(); databaseLocksManager.ConnectionService = connectionService; connectionService.RegisterConnectedQueue("1", connectionLock1.Object); connectionService.RegisterConnectedQueue("2", connectionLock2.Object); return(databaseLocksManager); }
public Channel(ConnectionService connectionService, uint clientChannelId, uint clientInitialWindowSize, uint clientMaxPacketSize, uint serverChannelId) { Contract.Requires(connectionService != null); _connectionService = connectionService; ClientChannelId = clientChannelId; ClientInitialWindowSize = clientInitialWindowSize; ClientWindowSize = clientInitialWindowSize; ClientMaxPacketSize = clientMaxPacketSize; ServerChannelId = serverChannelId; ServerInitialWindowSize = Session.InitialLocalWindowSize; ServerWindowSize = Session.InitialLocalWindowSize; ServerMaxPacketSize = Session.LocalChannelDataPacketSize; }
public void ValidateDefaultBackupFullFilePath() { var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true); SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo); string backupPath = Path.Combine(GetDefaultBackupFolderPath(helper.DataContainer, sqlConn), "master.bak"); string message; bool result = DisasterRecoveryFileValidator.ValidatePaths(new FileBrowserValidateEventArgs { ServiceType = FileValidationServiceConstants.Backup, OwnerUri = liveConnection.ConnectionInfo.OwnerUri, FilePaths = new string[] { backupPath } }, out message); Assert.True(result); Assert.Empty(message); }
private RestoreDatabaseTaskDataObject CreateRestoreForNewSession(string ownerUri, string targetDatabaseName = null) { ConnectionInfo connInfo; DisasterRecoveryService.ConnectionServiceInstance.TryFindConnection( ownerUri, out connInfo); if (connInfo != null) { SqlConnection connection = ConnectionService.OpenSqlConnection(connInfo, "Restore"); Server server = new Server(new ServerConnection(connection)); RestoreDatabaseTaskDataObject restoreDataObject = new RestoreDatabaseTaskDataObject(server, targetDatabaseName); return(restoreDataObject); } return(null); }
public void VerifyExecuteScript() { using (ExecutionEngine executionEngine = new ExecutionEngine()) { string query = @"SELECT 1+2 Go 2"; var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { TestExecutor testExecutor = new TestExecutor(query, sqlConn, new ExecutionEngineConditions()); testExecutor.Run(); ScriptExecutionResult result = (testExecutor.ExecutionResult == ScriptExecutionResult.Success) ? ScriptExecutionResult.Success : ScriptExecutionResult.Failure; Assert.Equal <ScriptExecutionResult>(ScriptExecutionResult.Success, result); } } }
void ConnectionService_onPlayerDisconnect(ConnectionService con) { //Remove player if it disconnects Player player = Connections[con]; if (player.MyRoomID != 0) { //Remove player from room; if room has no more players, remove the room Room room = AllRooms[player.MyRoomID]; if (room.RemovePlayer(player)) { AllRooms.Remove(room.RoomID); SearchingRooms.Remove(room); } } Connections.Remove(con); Players.Remove(player); }
public void VerifyIncludeSqlCmd() { string file = "VerifyIncludeSqlCmd_test.sql"; try { using (ExecutionEngine executionEngine = new ExecutionEngine()) { var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); string serverName = liveConnection.ConnectionInfo.ConnectionDetails.ServerName; string sqlCmdFile = $@" select * from sys.databases where name = 'master' GO"; File.WriteAllText("VerifyIncludeSqlCmd_test.sql", sqlCmdFile); string sqlCmdQuery = $@" :r {file} GO select * from sys.databases where name = 'master' GO"; var condition = new ExecutionEngineConditions() { IsSqlCmd = true }; using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) using (TestExecutor testExecutor = new TestExecutor(sqlCmdQuery, sqlConn, condition)) { testExecutor.Run(); Assert.True(testExecutor.ResultCountQueue.Count == 2, $"Unexpected number of ResultCount items - expected 1 but got {testExecutor.ResultCountQueue.Count}"); Assert.True(testExecutor.ErrorMessageQueue.Count == 0, $"Unexpected error messages from test executor : {string.Join(Environment.NewLine, testExecutor.ErrorMessageQueue)}"); } File.Delete(file); } } catch { if (File.Exists(file)) { File.Delete(file); } } }
public void RunningMultipleQueriesCreatesOnlyOneConnection() { // Connect/disconnect twice to ensure reconnection can occur ConnectionService service = ConnectionService.Instance; service.OwnerToConnectionMap.Clear(); for (int i = 0; i < 2; i++) { var result = LiveConnectionHelper.InitLiveConnectionInfo(); ConnectionInfo connectionInfo = result.ConnectionInfo; string uri = connectionInfo.OwnerUri; // We should see one ConnectionInfo and one DbConnection Assert.Equal(1, connectionInfo.CountConnections); Assert.Equal(1, service.OwnerToConnectionMap.Count); // If we run a query var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); Query query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory); query.Execute(); query.ExecutionTask.Wait(); // We should see two DbConnections Assert.Equal(2, connectionInfo.CountConnections); // If we run another query query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory); query.Execute(); query.ExecutionTask.Wait(); // We should still have 2 DbConnections Assert.Equal(2, connectionInfo.CountConnections); // If we disconnect, we should remain in a consistent state to do it over again // e.g. loop and do it over again service.Disconnect(new DisconnectParams() { OwnerUri = connectionInfo.OwnerUri }); // We should be left with an empty connection map Assert.Equal(0, service.OwnerToConnectionMap.Count); } }
private void Handle(CodedInputStream stream) { var packet = new ClientPacket(stream); if (packet.Service == PrevService) { //packet.Method should be 0, if there is no errors Callback callback = callbacks.Dequeue(); if (callback.RequestId != packet.RequestId) { throw new InvalidOperationException("Callback does not match!"); } callback.Action(packet.ReadMessage(callback.Builder)); return; } IService service = importedServices[packet.Service]; MethodDescriptor method = service.DescriptorForType.Methods.Single(m => GetMethodId(m) == packet.Method); Action <IMessage> done = response => { ServerPacket data = new ServerPacket(PrevService, (int)ErrorCode, packet.RequestId, 0).WriteMessage(response); Send(data); if (ErrorCode != AuthError.None) { DisconnectNotification dcNotify = DisconnectNotification.CreateBuilder().SetErrorCode((uint)ErrorCode).Build(); ConnectionService.CreateStub(this).ForceDisconnect(null, dcNotify, r => { }); Disconnect(); } }; IMessage requestProto = service.GetRequestPrototype(method); IMessage message = packet.ReadMessage(requestProto.WeakToBuilder()); // Logging Console.WriteLine(requestProto.GetType()); Console.WriteLine("Text View:"); Console.WriteLine(message.ToString()); service.CallMethod(method, null, message, done); }
public IActionResult GenerateEntityClass( [FromQuery] ColumnRequest request , [FromServices] SmartSqlBuilderFactory factory , [FromServices] ISqlProviderFactory sqlProviderFactory , [FromServices] ConnectionService connectionService ) { var connection = connectionService.QuerySingle(request.ConnectionId); if (connection == null) { return(null); } var dbService = DatabaseService.Create(factory, sqlProviderFactory, connection); var columns = dbService.ListColumns(request.TableName); var code = _codeGenerator.Execute(columns); return(Success(code)); }
private async Task <Mock <RequestContext <DacFxResult> > > ValidateExportCancellation() { var result = GetLiveAutoCompleteTestObjects(); var requestContext = new Mock <RequestContext <DacFxResult> >(); requestContext.Setup(x => x.SendResult(It.IsAny <DacFxResult>())).Returns(Task.FromResult(new object())); SqlTestDb testdb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "DacFxExportTest"); string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "DacFxTest"); Directory.CreateDirectory(folderPath); var exportParams = new ExportParams { DatabaseName = testdb.DatabaseName, PackageFilePath = Path.Combine(folderPath, string.Format("{0}.bacpac", testdb.DatabaseName)) }; SqlConnection sqlConn = ConnectionService.OpenSqlConnection(result.ConnectionInfo, "Export"); DacFxService service = new DacFxService(); ExportOperation operation = new ExportOperation(exportParams, sqlConn); // set cancellation token to cancel operation.Cancel(); OperationCanceledException expectedException = null; try { service.PerformOperation(operation); } catch (OperationCanceledException canceledException) { expectedException = canceledException; } Assert.NotNull(expectedException); // cleanup testdb.Cleanup(); return(requestContext); }
public void ServerNodeContextShouldSetErrorMessageIfSqlConnectionIsNull() { // given a connectionInfo with no SqlConnection to use for queries ConnectionService connService = SetupAndRegisterTestConnectionService(); connService.OwnerToConnectionMap.Remove(defaultOwnerUri); Server smoServer = new Server(new ServerConnection(new SqlConnection(fakeConnectionString))); ServerNode node = SetupServerNodeWithServer(smoServer); // When I get the context for a ServerNode var context = node.GetContextAs <SmoQueryContext>(); // Then I expect it to be in an error state Assert.Null(context); Assert.Equal( string.Format(CultureInfo.CurrentCulture, SR.ServerNodeConnectionError, defaultConnectionDetails.ServerName), node.ErrorStateMessage); }
private void Back(bool goToBulkSearch) { try { List <int> TaskIds = new List <int>(); if (AppSession.TaskIds != null && AppSession.TaskIds.Count > 0) { TaskIds = AppSession.TaskIds; } if (AppSession.ExecutingTaskId != 0) { TaskIds.Add(AppSession.ExecutingTaskId); } Result result = ConnectionService.ExitCurrentTask( new GetNextTaskModel { execTaskId = TaskIds, LastRoleID = AppSession.LastRoleId == 0 ? 0 : AppSession.LastRoleId, LastUserID = AppSession.UserId == 0 ? 0 : AppSession.UserId, WaveID = AppSession.CurrentWaveId == 0 ? 0 : AppSession.CurrentWaveId, IsHire = AppSession.IsHireWave ? false : AppSession.IsHireWave }); if (result.Status) { AppSession.ExecutingTaskId = 0; AppSession.LastRoleId = 0; AppSession.CurrentWaveId = 0; if (goToBulkSearch) { _navigationService.PushAsync(new BulkPickSearchPage()); } } } catch (Exception ex) { _navigationService.DisplayAlert("Task Error", ex.Message, "Ok"); } }
public object RemoveKeys(int id, int userId, int tokenId, string token) { var context = ConnectionService.GetContext(); var check = CheckToken.Check(tokenId, userId, token); if (check == false) { return(new { error = true, messageError = "Неправильный токен" }); } var rem = context.Keys.Where(r => r.Id == id && r.UserId == userId).FirstOrDefault(); if (rem != null) { context.Keys.Remove(rem); context.SaveChanges(); return(new { error = false, userId = userId }); } return(new { error = true, messageError = "Ошибка" }); }
void ConnectionService_onDataDecoded(ConnectionService con, ref NetworkMessage data) { //Processing data sent from a player. Interface.Log("Data Received"); switch (data.tag) { case 0: break; case 1: //Getting the player's instance Player source = Connections[con]; //Finding the player's room and routing the data to that room AllRooms[source.MyRoomID].ProcessInformation((byte[])data.data); Interface.Log("Data Roomed"); break; } }
public object CreateProfile(int id, string mail, string name, string surname, string token) { var context = ConnectionService.GetContext(); var uti = context.Tokens.Where(u => u.UserId == id).FirstOrDefault(); if (uti != null && uti.TokenId == token) { Profile profile = new Profile() { Mail = mail, Name = name, Surname = surname, UserId = id }; context.Profiles.Add(profile); context.SaveChanges(); return(profile.Id); } return(new { error = true, messageError = "Указанный Вами токен не подходит" }); }
/// <summary> /// Handles request to start the scripting operation /// </summary> public async Task HandleScriptExecuteRequest(ScriptingParams parameters, RequestContext <ScriptingResult> requestContext) { SmoScriptingOperation operation = null; try { // if a connection string wasn't provided as a parameter then // use the owner uri property to lookup its associated ConnectionInfo // and then build a connection string out of that ConnectionInfo connInfo = null; if (parameters.ConnectionString == null) { ScriptingService.ConnectionServiceInstance.TryFindConnection(parameters.OwnerUri, out connInfo); if (connInfo != null) { parameters.ConnectionString = ConnectionService.BuildConnectionString(connInfo.ConnectionDetails); } else { throw new Exception("Could not find ConnectionInfo"); } } if (!ShouldCreateScriptAsOperation(parameters)) { operation = new ScriptingScriptOperation(parameters); } else { operation = new ScriptAsScriptingOperation(parameters); } operation.PlanNotification += (sender, e) => requestContext.SendEvent(ScriptingPlanNotificationEvent.Type, e).Wait(); operation.ProgressNotification += (sender, e) => requestContext.SendEvent(ScriptingProgressNotificationEvent.Type, e).Wait(); operation.CompleteNotification += (sender, e) => this.SendScriptingCompleteEvent(requestContext, ScriptingCompleteEvent.Type, e, operation, parameters.ScriptDestination); RunTask(requestContext, operation); } catch (Exception e) { await requestContext.SendError(e); } }
private async Task <object> Back() { try { List <int> TaskIds = new List <int>(); if (AppSession.TaskIds != null && AppSession.TaskIds.Count > 0) { TaskIds = AppSession.TaskIds; } if (AppSession.ExecutingTaskId != 0) { TaskIds.Add(AppSession.ExecutingTaskId); } Result result = ConnectionService.ExitCurrentTask( new GetNextTaskModel { execTaskId = TaskIds, LastRoleID = AppSession.LastRoleId, LastUserID = AppSession.UserId, WaveID = AppSession.CurrentWaveId, IsHire = AppSession.IsHireWave }); if (result.Status) { AppSession.ExecutingTaskId = 0; AppSession.LastRoleId = 0; await _navigationService.PushAsync(new FinePickSearchPage()); } } catch (Exception ex) { await _navigationService.DisplayAlert("Alert.", ex.Message, "Ok"); } return(null); }
public async void GetCurrentConnectionStringTest() { // If we make a connection to a live database ConnectionService service = ConnectionService.Instance; var result = LiveConnectionHelper.InitLiveConnectionInfo(); var requestContext = new Mock<SqlTools.Hosting.Protocol.RequestContext<string>>(); requestContext.Setup(x => x.SendResult(It.Is<string>((connectionString) => connectionString.Contains("Password=" + ConnectionService.PasswordPlaceholder)))) .Returns(Task.FromResult(new object())); var requestParams = new GetConnectionStringParams() { OwnerUri = result.ConnectionInfo.OwnerUri, IncludePassword = false }; await service.HandleGetConnectionStringRequest(requestParams, requestContext.Object); requestContext.VerifyAll(); }
public static string PlaceConnectionDefifinitionPoint(Connection[] connections, string scheme, bool regenerate) { string mesg = EplDefinition.EPL_PLACE_CONNECTION_DEFINITION.ToString(); try { ConnectionService connectionService = new ConnectionService(); var connectionList = new System.Collections.ArrayList(connections); // Place connection definition points connectionService.PlaceConnectionDefinitionPoints(connectionList, "DI_DO_connection", regenerate); } catch (Exception ex) { mesg = EplError.EPL_ERROR.ToString(); EplException("Place connection difinition error.", ex); } return(mesg); }
public async Task <string> CreateBackupFile() { using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) { SqlTestDb testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, null, "RestoreTest"); var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(testDb.DatabaseName, queryTempFile.FilePath); // Initialize backup service DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true); SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo); // Get default backup pathS BackupConfigInfo backupConfigInfo = DisasterRecoveryService.Instance.GetBackupConfigInfo(helper.DataContainer, sqlConn, sqlConn.Database); string backupPath = Path.Combine(backupConfigInfo.DefaultBackupFolder, testDb.DatabaseName + ".bak"); BackupInfo backupInfo = CreateBackupInfo(testDb.DatabaseName, BackupType.Full, new List <string>() { backupPath }, new Dictionary <string, int>() { { backupPath, (int)DeviceType.File } }); var backupParams = new BackupParams { OwnerUri = liveConnection.ConnectionInfo.OwnerUri, BackupInfo = backupInfo, TaskExecutionMode = TaskExecutionMode.Execute }; // Backup the database BackupOperation backupOperation = DisasterRecoveryService.Instance.CreateBackupOperation(helper.DataContainer, sqlConn, backupParams.BackupInfo); DisasterRecoveryService.Instance.PerformBackup(backupOperation); // Clean up the database testDb.Cleanup(); return(backupPath); } }
public static string PlaceConnectionNumber(Connection[] connections, string scheme, bool regenerate) { string mesg = EplDefinition.EPL_GEN_CONNECTION_NUM.ToString(); try { ConnectionService connectionService = new ConnectionService(); var connectionList = new System.Collections.ArrayList(connections); //Place connection number, base on the definition placed previous time. connectionService.DesignateConnections(connectionList, scheme, ConnectionService.DesignateOverwrition.ExceptManuals, true, regenerate); } catch (Exception ex) { mesg = EplError.EPL_ERROR.ToString(); EplException("Place connection number error.", ex); } return(mesg); }
static async Task Main(string[] args) { if (args.Length < 1) { ShowUsage(); return; } var path = args[0]; var cmd = args[1]; IConnectionService connectionService = new ConnectionService(); await connectionService.LoadDatabase(@".\WINCC", path); switch (cmd) { case "list": { ConsoleTable .From(connectionService.Connections) .Write(Format.Alternative); break; } case "set": { if (args.Length < 4) { ShowUsage(); return; } var connectionName = args[2]; var parameter = args[3]; await SetConnectionParameter(connectionService, connectionName, parameter); break; } } connectionService.CloseDatabase(); }
private void btnTestConnection_Click(object sender, EventArgs e) { if (ValidateChildren(ValidationConstraints.Enabled)) { try { using (var connection = ConnectionService.GetConnection(server, database)) { connection.Open(); ctrlConnectionStatus.BackColor = COLOR_SUCCESS; } } catch (Exception ex) { MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Information); ctrlConnectionStatus.BackColor = COLOR_FAIL; } } }
void AppStartup(object Sender, StartupEventArgs e) { DataService dataService = new DataService(); MainModel _MainModel = dataService.Model; ConnectionService _ConnectionService = new ConnectionService(_MainModel, dataService); MainWindow = new MainWindow(); MainWindow.DataContext = new MainViewModel(_ConnectionService, _MainModel); this.Exit += _ConnectionService.OnExit; MainWindow.Show(); }
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { var builder = new ContainerBuilder(); var saverService = new SaverService(); var dataProvider = new DataProvider(saverService); var appInfo = new AppInfo(); var connectionService = new ConnectionService(); var ravenClientDSN = DebugHelper.GetRavenClientDSN(); var reporterService = new ReporterService(appInfo, ravenClientDSN); builder.RegisterInstance(appInfo).As <IAppInfo>().SingleInstance(); builder.RegisterInstance(saverService).As <ISaverService>().SingleInstance(); builder.RegisterInstance(dataProvider).As <IDataProvider>().SingleInstance(); builder.RegisterInstance(reporterService).As <IReporterService>().SingleInstance(); builder.RegisterInstance(connectionService).As <IConnectionService>().SingleInstance(); AppSettings.Container = builder.Build(); AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => { //AppSettings.Reporter.SendCrash((Exception)e.ExceptionObject); }; TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs e) => { //AppSettings.Reporter.SendCrash(e.Exception); }; Window = new UIWindow(UIScreen.MainScreen.Bounds); if (BasePresenter.User.IsAuthenticated) { InitialViewController = new MainTabBarController(); } else { InitialViewController = new PreSearchViewController(); } var navController = new UINavigationController(InitialViewController); Window.RootViewController = navController; Window.MakeKeyAndVisible(); return(true); }
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId) { UserInfo = DataStorageService.LoadData <UserInfo>("UserInfo.json", this); if (UserInfo == null) { UserInfo = new UserInfo(); DataStorageService.StoreData(UserInfo, "UserInfo.json", this); } ConnectionSettings = DataStorageService.LoadData <ConnectionSettings>("ConnectionSettings.json", this); if (ConnectionSettings == null) { ConnectionSettings = new ConnectionSettings(); DataStorageService.StoreData(ConnectionSettings, "ConnectionSettings.json", this); } IsActivated = DataStorageService.LoadData <bool>("IsActivated.json", this); if (IsActivated == default(bool)) { IsActivated = false; DataStorageService.StoreData(IsActivated, "IsActivated.json", this); } SignalRService = new SignalRService(ConnectionSettings, UserInfo); ConnectionService = new ConnectionService(ConnectionSettings); UserInfoChanged = UserInfo; ConnectionSettingsChanged = ConnectionSettings; IsActivatedChange = IsActivated; Reciver = new NetworkStatusListener(); Reciver.CheckNetwork = ConnectionService.CheckNetwork; Reciver.RegisterOnNetwork = SignalRService.StartConnection; RegisterReceiver(Reciver, new IntentFilter(ConnectivityManager.ConnectivityAction)); return(StartCommandResult.Sticky); }
public void DatabaseChangesAffectAllConnections() { // If we make a connection to a live database ConnectionService service = ConnectionService.Instance; var result = LiveConnectionHelper.InitLiveConnectionInfo(); ConnectionInfo connectionInfo = result.ConnectionInfo; ConnectionDetails details = connectionInfo.ConnectionDetails; string initialDatabaseName = details.DatabaseName; string uri = connectionInfo.OwnerUri; string newDatabaseName = "tempdb"; string changeDatabaseQuery = "use " + newDatabaseName; // Then run any query to create a query DbConnection var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(); Query query = new Query(Constants.StandardQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory); query.Execute(); query.ExecutionTask.Wait(); // All open DbConnections (Query and Default) should have initialDatabaseName as their database foreach (DbConnection connection in connectionInfo.AllConnections) { if (connection != null && connection.State == ConnectionState.Open) { Assert.Equal(connection.Database, initialDatabaseName); } } // If we run a query to change the database query = new Query(changeDatabaseQuery, connectionInfo, new QueryExecutionSettings(), fileStreamFactory); query.Execute(); query.ExecutionTask.Wait(); // All open DbConnections (Query and Default) should have newDatabaseName as their database foreach (DbConnection connection in connectionInfo.AllConnections) { if (connection != null && connection.State == ConnectionState.Open) { Assert.Equal(connection.Database, newDatabaseName); } } }
public void ScriptBackupTest() { DisasterRecoveryService service = new DisasterRecoveryService(); string databaseName = "SqlToolsService_TestBackup_" + new Random().Next(10000000, 99999999); SqlTestDb testDb = SqlTestDb.CreateNew(TestServerType.OnPrem, false, databaseName); try { var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo(databaseName); DatabaseTaskHelper helper = AdminService.CreateDatabaseTaskHelper(liveConnection.ConnectionInfo, databaseExists: true); SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo); string backupPath = GetDefaultBackupFullPath(service, databaseName, helper.DataContainer, sqlConn); BackupInfo backupInfo = CreateDefaultBackupInfo(databaseName, BackupType.Full, new List <string>() { backupPath }, new Dictionary <string, int>() { { backupPath, (int)DeviceType.File } }); BackupOperation backupOperation = CreateBackupOperation(service, liveConnection.ConnectionInfo.OwnerUri, backupInfo, helper.DataContainer, sqlConn); // Generate script for backup service.ScriptBackup(backupOperation); string script = backupOperation.ScriptContent; Assert.True(!string.IsNullOrEmpty(script)); // Execute the script testDb.RunQuery(script); VerifyAndCleanBackup(backupPath); sqlConn.Close(); } finally { testDb.Cleanup(); } }
/// <summary> /// Handles request to start the scripting operation /// </summary> public async Task HandleScriptExecuteRequest(ScriptingParams parameters, RequestContext <ScriptingResult> requestContext) { try { // if a connection string wasn't provided as a parameter then // use the owner uri property to lookup its associated ConnectionInfo // and then build a connection string out of that ConnectionInfo connInfo = null; if (parameters.ConnectionString == null || parameters.ScriptOptions.ScriptCreateDrop == "ScriptSelect") { ScriptingService.ConnectionServiceInstance.TryFindConnection(parameters.OwnerUri, out connInfo); if (connInfo != null) { parameters.ConnectionString = ConnectionService.BuildConnectionString(connInfo.ConnectionDetails); } else { throw new Exception("Could not find ConnectionInfo"); } } // if the scripting operation is for SELECT then handle that message differently // for SELECT we'll build the SQL directly whereas other scripting operations depend on SMO if (parameters.ScriptOptions.ScriptCreateDrop == "ScriptSelect") { RunSelectTask(connInfo, parameters, requestContext); } else { ScriptingScriptOperation operation = new ScriptingScriptOperation(parameters); operation.PlanNotification += (sender, e) => requestContext.SendEvent(ScriptingPlanNotificationEvent.Type, e).Wait(); operation.ProgressNotification += (sender, e) => requestContext.SendEvent(ScriptingProgressNotificationEvent.Type, e).Wait(); operation.CompleteNotification += (sender, e) => this.SendScriptingCompleteEvent(requestContext, ScriptingCompleteEvent.Type, e, operation, parameters.ScriptDestination); RunTask(requestContext, operation); } } catch (Exception e) { await requestContext.SendError(e); } }
public void VerifyExecuteBatch() { using (ExecutionEngine executionEngine = new ExecutionEngine()) { string query = "SELECT 1+2"; var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master"); using (SqlConnection sqlConn = ConnectionService.OpenSqlConnection(liveConnection.ConnectionInfo)) { var executionPromise = new TaskCompletionSource <bool>(); executionEngine.BatchParserExecutionFinished += (object sender, BatchParserExecutionFinishedEventArgs e) => { Assert.Equal(ScriptExecutionResult.Success, e.ExecutionResult); executionPromise.SetResult(true); }; executionEngine.ExecuteBatch(new ScriptExecutionArgs(query, sqlConn, 15, new ExecutionEngineConditions(), new BatchParserMockEventHandler())); Task.WaitAny(executionPromise.Task, Task.Delay(5000)); Assert.True(executionPromise.Task.IsCompleted, "Execution did not finish in time"); } } }
//TODO stop users logging in if they're already logged in, it'll circumvent the logout event D: void OnServerMessage(ConnectionService con, NetworkMessage data) { if (data.tag == tag) { //Login if (data.subject == loginSubject) { try { using (DarkRiftReader reader = (DarkRiftReader)data.data) { bool isLoggedIn = false; try { isLoggedIn = (bool)con.GetData(name, "IsLoggedIn"); } catch (KeyNotFoundException) { } if (!isLoggedIn) { try { //Query then database DatabaseRow[] rows = DarkRiftServer.database.ExecuteQuery( "SELECT id FROM users WHERE username = @username AND password = @password LIMIT 1 ", new QueryParameter("username", reader.ReadString()), new QueryParameter("password", reader.ReadString()) ); //If 1 is returned then the details are correct if (rows.Length == 1) { int id = Convert.ToInt32(rows[0]["id"]); con.SetData(name, "IsLoggedIn", true); con.SetData(name, "UserID", id); if (onSuccessfulLogin != null) onSuccessfulLogin(id, con); if (debug) Interface.Log("[LoginPlugin] Successfull login (" + id + ")."); con.SendReply(tag, loginSuccessSubject, id); } else { if (onUnsucessfulLogin != null) onUnsucessfulLogin(con); if (debug) Interface.Log("[LoginPlugin] Unsuccessfull login."); con.SendReply(tag, loginFailedSubject, 0); } } catch (DatabaseException e) { Interface.LogError("[LoginPlugin] SQL error during login:"******"[LoginPlugin] Unsuccessfull login."); con.SendReply(tag, loginFailedSubject, 0); } } else { Interface.LogError("[LoginPlugin] Client tried to login while still logged in!"); if (onUnsucessfulLogin != null) onUnsucessfulLogin(con); if (debug) Interface.Log("[LoginPlugin] Unsuccessfull login."); con.SendReply(tag, loginFailedSubject, 0); } } } catch(InvalidCastException) { Interface.LogError("[LoginPlugin] Invalid data recieved in a Login request."); if (onUnsucessfulLogin != null) onUnsucessfulLogin(con); if (debug) Interface.Log("[LoginPlugin] Unsuccessfull login."); con.SendReply(tag, loginFailedSubject, 0); } } //Logout if (data.subject == logoutSubject) { con.SetData(name, "IsLoggedIn", false); int id = (int)con.GetData(name, "UserID"); con.SetData(name, "UserID", -1); if( onLogout != null ) onLogout(id, con); if( debug ) Interface.Log("[LoginPlugin] Successful logout."); con.SendReply (tag, logoutSuccessSubject, 0); } //Add User if (data.subject == addUserSubject && settings.IsTrue ("AllowAddUser")) { try { using (DarkRiftReader reader = (DarkRiftReader)data.data) { string username = reader.ReadString(); string password = reader.ReadString(); try { object o = DarkRiftServer.database.ExecuteScalar ( "SELECT EXISTS(SELECT 1 FROM users WHERE username = @username AND password = @password) ", new QueryParameter("username", username), new QueryParameter("password", password) ); if (!Convert.ToBoolean(o)) { int id = AddUserToDatabase (username, password); con.SetData (name, "IsLoggedIn", true); con.SetData (name, "UserID", id); if (onAddUser != null) onAddUser (id, username, con); if( debug ) Interface.Log("[LoginPlugin] User added."); con.SendReply (tag, addUserSuccessSubject, id); } else { if (onAddUserFailed != null) onAddUserFailed (username, con); if( debug ) Interface.Log("[LoginPlugin] Add user failed."); con.SendReply (tag, addUserFailedSubject, 0); } } catch(DatabaseException e) { Interface.LogError("[LoginPlugin] SQL error during AddUser:"******"[LoginPlugin] Add user failed."); con.SendReply (tag, loginFailedSubject, 0); } } } catch(InvalidCastException) { Interface.LogError("[LoginPlugin] Invalid data recieved in an AddUser request."); if( onAddUserFailed != null ) onAddUserFailed("", con); if( debug ) Interface.Log("[LoginPlugin] Add user failed."); con.SendReply (tag, loginFailedSubject, 0); } } } }