Пример #1
0
        public IActionResult ConnectSuccess()
        {
            var bitString = "";

            for (int i = 0; i < 40; i++)
            {
                bitString += "0";
            }

            _connectionService.Connect("ip address goes here", "567432" + " " + bitString);

            return(View());
        }
        public async void ConnectToDefaultDatabaseRespondsWithActualDbName(string expectedDbName)
        {
            // Given connecting with empty database name will return the expected DB name
            var connectionMock = new Mock <DbConnection> {
                CallBase = true
            };

            connectionMock.Setup(c => c.Database).Returns(expectedDbName);

            var mockFactory = new Mock <ISqlConnectionFactory>();

            mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny <string>()))
            .Returns(connectionMock.Object);

            var connectionService = new ConnectionService(mockFactory.Object);

            // When I connect with an empty DB name
            var connectionDetails = TestObjects.GetTestConnectionDetails();

            connectionDetails.DatabaseName = string.Empty;

            var connectionResult = await
                                   connectionService
                                   .Connect(new ConnectParams()
            {
                OwnerUri   = "file:///my/test/file.sql",
                Connection = connectionDetails
            });

            // Then I expect connection to succeed and the Summary to include the correct DB name
            Assert.NotEmpty(connectionResult.ConnectionId);
            Assert.NotNull(connectionResult.ConnectionSummary);
            Assert.Equal(expectedDbName, connectionResult.ConnectionSummary.DatabaseName);
        }
        /// <summary>
        /// Redirects the connection to the details in
        /// the <see cref="ConnectionDetails"/> model.
        /// </summary>
        public void Redirect()
        {
            //absolutely critical that the encryption be uninitialized
            CryptoInitializer.DecryptionInitializable.Uninitialize();
            CryptoInitializer.EncryptionInitializable.Uninitialize();

            ConnectionService.Connect(ConnectionDetails.IpAddress, ConnectionDetails.Port);
        }
Пример #4
0
        private async Task <ConnectParams> CreateAndConnectWithConnectParams()
        {
            ConnectParams     connectParams = CreateConnectParams();
            ConnectionService connService   = ConnectionService.Instance;
            await connService.Connect(connectParams);

            return(connectParams);
        }
        public async void ListDatabasesOnServerForCurrentConnectionReturnsDatabaseNames()
        {
            // Result set for the query of database names
            Dictionary <string, string>[] data =
            {
                new Dictionary <string, string> {
                    { "name",           "master" }
                },
                new Dictionary <string, string> {
                    { "name",           "model" }
                },
                new Dictionary <string, string> {
                    { "name",           "msdb" }
                },
                new Dictionary <string, string> {
                    { "name",           "tempdb" }
                },
                new Dictionary <string, string> {
                    { "name",           "mydatabase" }
                },
            };

            // Setup mock connection factory to inject query results
            var mockFactory = new Mock <ISqlConnectionFactory>();

            mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny <string>()))
            .Returns(CreateMockDbConnection(new[] { data }));
            var connectionService = new ConnectionService(mockFactory.Object);

            // connect to a database instance
            string ownerUri         = "file://my/sample/file.sql";
            var    connectionResult = await
                                      connectionService
                                      .Connect(new ConnectParams()
            {
                OwnerUri   = ownerUri,
                Connection = TestObjects.GetTestConnectionDetails()
            });

            // verify that a valid connection id was returned
            Assert.NotEmpty(connectionResult.ConnectionId);

            // list databases for the connection
            ListDatabasesParams parameters = new ListDatabasesParams();

            parameters.OwnerUri = ownerUri;
            var listDatabasesResult = connectionService.ListDatabases(parameters);

            string[] databaseNames = listDatabasesResult.DatabaseNames;

            Assert.Equal(databaseNames.Length, 5);
            Assert.Equal(databaseNames[0], "master");
            Assert.Equal(databaseNames[1], "model");
            Assert.Equal(databaseNames[2], "msdb");
            Assert.Equal(databaseNames[3], "tempdb");
            Assert.Equal(databaseNames[4], "mydatabase");
        }
Пример #6
0
        public void Start()
        {
            Console.WriteLine("Connecting to {0}:{1}", host, port);
            var client = new TcpClient(host, port);

            connection.Start(client);
            Console.WriteLine(".. connected");

            connectionService = connection.GetImportedService <ConnectionService>();

            connectionService.Connect(null, ConnectRequest.CreateBuilder().Build(), OnConnectResponse);
        }
Пример #7
0
        public static ConnectionInfo CreateConnectedConnectionInfo(TestResultSet[] data, bool throwOnRead, string type = ConnectionType.Default)
        {
            ConnectionService connectionService = ConnectionService.Instance;

            connectionService.OwnerToConnectionMap.Clear();
            connectionService.ConnectionFactory = CreateMockFactory(data, throwOnRead);

            ConnectParams connectParams = new ConnectParams
            {
                Connection = StandardConnectionDetails,
                OwnerUri   = OwnerUri,
                Type       = type
            };

            connectionService.Connect(connectParams).Wait();
            return(connectionService.OwnerToConnectionMap[OwnerUri]);
        }
Пример #8
0
        /// <summary>
        /// Establish a connection with the device
        /// </summary>
        private void connect_Click(object sender, RoutedEventArgs e)
        {
            // TODO add a 'connecting...' prompt

            var address = HostName.Text;

            Connection = new ConnectionService(address, _connectionType);

            var connected = Connection.Connect();

            if (connected)
            {
                ScanDevice.IsEnabled = true;
            }

            // TODO change prompt to say 'connected' if successful
        }
Пример #9
0
        public static async Task <QueryExecutionService> GetPrimedExecutionService(ISqlConnectionFactory factory, bool isConnected, WorkspaceService <SqlToolsSettings> workspaceService)
        {
            var connectionService = new ConnectionService(factory);

            if (isConnected)
            {
                await connectionService.Connect(new ConnectParams
                {
                    Connection = GetTestConnectionDetails(),
                    OwnerUri   = OwnerUri
                });
            }
            return(new QueryExecutionService(connectionService, workspaceService)
            {
                BufferFileStreamFactory = GetFileStreamFactory()
            });
        }
Пример #10
0
        static void Main(string[] args)
        {
            IConfigurationService     configuration = new ConfigurationService();
            IConnector                connector     = new ConnectionService();
            IDeployer <SiteModelNode> siteDeployer  = new SiteDeploymentPresenter();
            IDeployer <WebModelNode>  webDeployer   = new WebDeploymentPresenter();

            var url      = configuration.GetConfigurationValue(ConfigurationDesignators.Url);
            var password = configuration.GetConfigurationValue(ConfigurationDesignators.Password);
            var login    = configuration.GetConfigurationValue(ConfigurationDesignators.Login);

            var context = connector.Connect(url, login, password);

            var taxonomyCreator             = new TaxonomyCreator(siteDeployer, context);
            var projectListCreator          = new ProjectListCreator(webDeployer, context);
            var projectDocumentsListCreator = new ProjectDocumentsListCreator(webDeployer, context);

            taxonomyCreator.Deploy();
            projectListCreator.Deploy();
            projectDocumentsListCreator.Deploy();
            Console.WriteLine("Good");
            Console.ReadKey();
        }
Пример #11
0
        /// <summary>
        /// Handles a request to execute a string and return the result
        /// </summary>
        internal async Task HandleSimpleExecuteRequest(SimpleExecuteParams executeParams,
                                                       RequestContext <SimpleExecuteResult> requestContext)
        {
            try
            {
                string randomUri = Guid.NewGuid().ToString();
                ExecuteStringParams executeStringParams = new ExecuteStringParams
                {
                    Query = executeParams.QueryString,
                    // generate guid as the owner uri to make sure every query is unique
                    OwnerUri = randomUri
                };

                // get connection
                ConnectionInfo connInfo;
                if (!ConnectionService.TryFindConnection(executeParams.OwnerUri, out connInfo))
                {
                    await requestContext.SendError(SR.QueryServiceQueryInvalidOwnerUri);

                    return;
                }

                ConnectParams connectParams = new ConnectParams
                {
                    OwnerUri   = randomUri,
                    Connection = connInfo.ConnectionDetails,
                    Type       = ConnectionType.Default
                };

                Task workTask = Task.Run(async() => {
                    await ConnectionService.Connect(connectParams);

                    ConnectionInfo newConn;
                    ConnectionService.TryFindConnection(randomUri, out newConn);

                    Func <string, Task> queryCreateFailureAction = message => requestContext.SendError(message);

                    ResultOnlyContext <SimpleExecuteResult> newContext = new ResultOnlyContext <SimpleExecuteResult>(requestContext);

                    // handle sending event back when the query completes
                    Query.QueryAsyncEventHandler queryComplete = async query =>
                    {
                        try
                        {
                            // check to make sure any results were recieved
                            if (query.Batches.Length == 0 ||
                                query.Batches[0].ResultSets.Count == 0)
                            {
                                await requestContext.SendError(SR.QueryServiceResultSetHasNoResults);
                                return;
                            }

                            long rowCount = query.Batches[0].ResultSets[0].RowCount;
                            // check to make sure there is a safe amount of rows to load into memory
                            if (rowCount > Int32.MaxValue)
                            {
                                await requestContext.SendError(SR.QueryServiceResultSetTooLarge);
                                return;
                            }

                            SimpleExecuteResult result = new SimpleExecuteResult
                            {
                                RowCount   = rowCount,
                                ColumnInfo = query.Batches[0].ResultSets[0].Columns,
                                Rows       = new DbCellValue[0][]
                            };

                            if (rowCount > 0)
                            {
                                SubsetParams subsetRequestParams = new SubsetParams
                                {
                                    OwnerUri       = randomUri,
                                    BatchIndex     = 0,
                                    ResultSetIndex = 0,
                                    RowsStartIndex = 0,
                                    RowsCount      = Convert.ToInt32(rowCount)
                                };
                                // get the data to send back
                                ResultSetSubset subset = await InterServiceResultSubset(subsetRequestParams);
                                result.Rows            = subset.Rows;
                            }
                            await requestContext.SendResult(result);
                        }
                        finally
                        {
                            Query removedQuery;
                            Task removedTask;
                            // remove the active query since we are done with it
                            ActiveQueries.TryRemove(randomUri, out removedQuery);
                            ActiveSimpleExecuteRequests.TryRemove(randomUri, out removedTask);
                            ConnectionService.Disconnect(new DisconnectParams()
                            {
                                OwnerUri = randomUri,
                                Type     = null
                            });
                        }
                    };

                    // handle sending error back when query fails
                    Query.QueryAsyncErrorEventHandler queryFail = async(q, e) =>
                    {
                        await requestContext.SendError(e);
                    };

                    await InterServiceExecuteQuery(executeStringParams, newConn, newContext, null, queryCreateFailureAction, queryComplete, queryFail);
                });

                ActiveSimpleExecuteRequests.TryAdd(randomUri, workTask);
            }
            catch (Exception ex)
            {
                await requestContext.SendError(ex.ToString());
            }
        }
        public void CanCancelConnectRequest()
        {
            var testFile = "file:///my/test/file.sql";

            // Given a connection that times out and responds to cancellation
            var mockConnection = new Mock <DbConnection> {
                CallBase = true
            };
            CancellationToken token;
            bool ready = false;

            mockConnection.Setup(x => x.OpenAsync(Moq.It.IsAny <CancellationToken>()))
            .Callback <CancellationToken>(t =>
            {
                // Pass the token to the return handler and signal the main thread to cancel
                token = t;
                ready = true;
            })
            .Returns(() =>
            {
                if (TestUtils.WaitFor(() => token.IsCancellationRequested))
                {
                    throw new OperationCanceledException();
                }
                else
                {
                    return(Task.FromResult(true));
                }
            });

            var mockFactory = new Mock <ISqlConnectionFactory>();

            mockFactory.Setup(factory => factory.CreateSqlConnection(It.IsAny <string>()))
            .Returns(mockConnection.Object);


            var connectionService = new ConnectionService(mockFactory.Object);

            // Connect the connection asynchronously in a background thread
            var connectionDetails = TestObjects.GetTestConnectionDetails();
            var connectTask       = Task.Run(async() =>
            {
                return(await connectionService
                       .Connect(new ConnectParams()
                {
                    OwnerUri = testFile,
                    Connection = connectionDetails
                }));
            });

            // Wait for the connection to call OpenAsync()
            Assert.True(TestUtils.WaitFor(() => ready));

            // Send a cancellation request
            var cancelResult = connectionService
                               .CancelConnect(new CancelConnectParams()
            {
                OwnerUri = testFile
            });

            // Wait for the connection task to finish
            connectTask.Wait();

            // Verify that the connection was cancelled (no connection was created)
            Assert.Null(connectTask.Result.ConnectionId);

            // Verify that the cancel succeeded
            Assert.True(cancelResult);
        }
Пример #13
0
        /// <summary>
        /// This function obtains a live connection, then calls
        /// an assessment operation specified by <paramref name="assessmentFunc"/>
        /// </summary>
        /// <typeparam name="TResult">
        /// SQL Assessment result item type.
        /// </typeparam>
        /// <param name="requestParams">
        /// Request parameters passed from the host.
        /// </param>
        /// <param name="connectParams">
        /// Connection parameters used to identify and access the target.
        /// </param>
        /// <param name="taskUri">
        /// An URI identifying the request task to enable concurrent execution.
        /// </param>
        /// <param name="assessmentFunc">
        /// A function performing assessment operation for given target.
        /// </param>
        /// <returns>
        /// Returns <see cref="AssessmentResult{TResult}"/> for given target.
        /// </returns>
        internal async Task <AssessmentResult <TResult> > CallAssessmentEngine <TResult>(
            AssessmentParams requestParams,
            ConnectParams connectParams,
            string taskUri,
            Func <SqlObjectLocator, Task <List <TResult> > > assessmentFunc)
            where TResult : AssessmentItemInfo

        {
            var result = new AssessmentResult <TResult>
            {
                ApiVersion = ApiVersion
            };

            await ConnectionService.Connect(connectParams);

            var connection = await ConnectionService.Instance.GetOrOpenConnection(taskUri, ConnectionType.Query);

            try
            {
                var serverInfo = ReliableConnectionHelper.GetServerVersion(connection);
                var hostInfo   = ReliableConnectionHelper.GetServerHostInfo(connection);

                var server = new SqlObjectLocator
                {
                    Connection    = connection,
                    EngineEdition = GetEngineEdition(serverInfo.EngineEditionId),
                    Name          = serverInfo.ServerName,
                    ServerName    = serverInfo.ServerName,
                    Type          = SqlObjectType.Server,
                    Urn           = serverInfo.ServerName,
                    Version       = Version.Parse(serverInfo.ServerVersion),
                    Platform      = hostInfo.Platform
                };

                switch (requestParams.TargetType)
                {
                case SqlObjectType.Server:
                    Logger.Write(
                        TraceEventType.Verbose,
                        $"SQL Assessment: running an operation on a server, platform:{server.Platform}, edition:{server.EngineEdition.ToString()}, version:{server.Version}");

                    result.Items.AddRange(await assessmentFunc(server));

                    Logger.Write(
                        TraceEventType.Verbose,
                        $"SQL Assessment: finished an operation on a server, platform:{server.Platform}, edition:{server.EngineEdition.ToString()}, version:{server.Version}");
                    break;

                case SqlObjectType.Database:
                    var db = GetDatabaseLocator(server, connection.Database);
                    Logger.Write(
                        TraceEventType.Verbose,
                        $"SQL Assessment: running an operation on a database, platform:{server.Platform}, edition:{server.EngineEdition.ToString()}, version:{server.Version}");

                    result.Items.AddRange(await assessmentFunc(db));

                    Logger.Write(
                        TraceEventType.Verbose,
                        $"SQL Assessment: finished an operation on a database, platform:{server.Platform}, edition:{server.EngineEdition.ToString()}, version:{server.Version}");
                    break;
                }

                result.Success = true;
            }
            finally
            {
                ActiveRequests.TryRemove(taskUri, out _);
                ConnectionService.Disconnect(new DisconnectParams {
                    OwnerUri = taskUri, Type = null
                });
            }

            return(result);
        }
Пример #14
0
        public void Connection_WrongConnectionProperties()
        {
            ConnectionService service = new ConnectionService();

            Assert.False(service.Connect(String.Empty, String.Empty, String.Empty, String.Empty));
        }