public void VerifyAnsiNullAndQuotedIdentifierSettingsReplayed()
 {
     using (ReliableSqlConnection conn = (ReliableSqlConnection)ReliableConnectionHelper.OpenConnection(CreateTestConnectionStringBuilder(), useRetry: true))
     {
         VerifySessionSettings(conn, true);
         VerifySessionSettings(conn, false);
     }
 }
        public void GetCompleteServerNameTests()
        {
            Assert.Null(ReliableConnectionHelper.GetCompleteServerName(null));

            Assert.NotNull(ReliableConnectionHelper.GetCompleteServerName("localhost"));

            Assert.NotNull(ReliableConnectionHelper.GetCompleteServerName("mytestservername"));
        }
 public void TestTryGetServerVersionInvalidConnectionString()
 {
     RunIfWrapper.RunIfWindows(() =>
     {
         ReliableConnectionHelper.ServerInfo info = null;
         Assert.False(ReliableConnectionHelper.TryGetServerVersion("this is not a valid connstr", out info));
     });
 }
Beispiel #4
0
        public static bool ValidatePaths(FileBrowserValidateEventArgs args, out string errorMessage)
        {
            errorMessage = string.Empty;
            bool          result     = true;
            SqlConnection connection = null;

            if (args != null)
            {
                ConnectionInfo connInfo;
                ConnectionService.Instance.TryFindConnection(args.OwnerUri, out connInfo);
                if (connInfo != null)
                {
                    DbConnection dbConnection = null;
                    connInfo.TryGetConnection(Connection.ConnectionType.Default, out dbConnection);
                    if (dbConnection != null)
                    {
                        connection = ReliableConnectionHelper.GetAsSqlConnection(dbConnection);
                    }
                }
            }

            if (connection != null)
            {
                foreach (string filePath in args.FilePaths)
                {
                    bool isFolder;
                    bool existing = IsPathExisting(connection, filePath, out isFolder);

                    if (existing)
                    {
                        if (isFolder)
                        {
                            errorMessage = SR.BackupPathIsFolderError;
                        }
                    }
                    else
                    {
                        if (args.ServiceType == FileValidationServiceConstants.Backup)
                        {
                            errorMessage = IsFolderPathExisting(connection, filePath);
                        }
                        else if (args.ServiceType == FileValidationServiceConstants.Restore)
                        {
                            errorMessage = SR.InvalidBackupPathError;
                        }
                    }

                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        result = false;
                        break;
                    }
                }
            }

            return(result);
        }
Beispiel #5
0
        public void TestGetCompleteServerName()
        {
            string name = ReliableConnectionHelper.GetCompleteServerName(@".\SQL2008");

            Assert.True(name.Contains(Environment.MachineName));

            name = ReliableConnectionHelper.GetCompleteServerName(@"(local)");
            Assert.True(name.Contains(Environment.MachineName));
        }
Beispiel #6
0
        private DatabaseEngineEdition GetOrReadCachedEngineEdition(IDbConnection conn)
        {
            if (CachedServerInfo.Instance.TryGetEngineEdition(conn, out _engineEdition) == DatabaseEngineEdition.Unknown)
            {
                _engineEdition = ReliableConnectionHelper.GetEngineEdition(conn);
                CachedServerInfo.Instance.AddOrUpdateEngineEdition(conn, _engineEdition);
            }

            return(_engineEdition);
        }
Beispiel #7
0
        public void GetConnectionStringBuilderExceptionTests()
        {
            SqlConnectionStringBuilder builder;

            // throws ArgumentException
            Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder("IntegratedGoldFish=True", out builder));

            // throws FormatException
            Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder("rabbits**frogs**lizards", out builder));
        }
Beispiel #8
0
        public void TestIsDatabaseReadonly()
        {
            var connectionBuilder = CreateTestConnectionStringBuilder();

            Assert.NotNull(connectionBuilder);

            bool isReadOnly = ReliableConnectionHelper.IsDatabaseReadonly(connectionBuilder);

            Assert.False(isReadOnly);
        }
Beispiel #9
0
        public void TestIsCloudIsFalseForLocalServer()
        {
            using (var connection = CreateTestConnection())
            {
                Assert.NotNull(connection);

                connection.Open();
                Assert.False(ReliableConnectionHelper.IsCloud(connection));
            }
        }
Beispiel #10
0
        public void TestTryGetServerVersion()
        {
            ReliableConnectionHelper.ServerInfo info = null;
            var connBuilder = CreateTestConnectionStringBuilder();

            Assert.True(ReliableConnectionHelper.TryGetServerVersion(connBuilder.ConnectionString, out info, null));

            Assert.NotNull(info);
            Assert.NotNull(info.ServerVersion);
            Assert.NotEmpty(info.ServerVersion);
        }
Beispiel #11
0
        public void TestOpenConnectionOpensConnection()
        {
            using (var connection = CreateTestConnection())
            {
                Assert.NotNull(connection);

                Assert.True(connection.State == ConnectionState.Closed);
                ReliableConnectionHelper.OpenConnection(connection);
                Assert.True(connection.State == ConnectionState.Open);
            }
        }
Beispiel #12
0
        public void TestExecuteNonQuery()
        {
            var result = ReliableConnectionHelper.ExecuteNonQuery(
                CreateTestConnectionStringBuilder(),
                "SET NOCOUNT ON; SET NOCOUNT OFF;",
                ReliableConnectionHelper.SetCommandTimeout,
                null,
                true
                );

            Assert.NotNull(result);
        }
        /// <summary>
        /// Creates a ConnectionCompleteParams as a response to a successful connection.
        /// Also sets the DatabaseName and IsAzure properties of ConnectionInfo.
        /// </summary>
        /// <returns>A ConnectionCompleteParams in response to the successful connection</returns>
        private ConnectionCompleteParams GetConnectionCompleteParams(string connectionType, ConnectionInfo connectionInfo)
        {
            ConnectionCompleteParams response = new ConnectionCompleteParams {
                OwnerUri = connectionInfo.OwnerUri, Type = connectionType
            };

            try
            {
                DbConnection connection;
                connectionInfo.TryGetConnection(connectionType, out connection);

                // Update with the actual database name in connectionInfo and result
                // Doing this here as we know the connection is open - expect to do this only on connecting
                connectionInfo.ConnectionDetails.DatabaseName = connection.Database;
                response.ConnectionSummary = new ConnectionSummary
                {
                    ServerName   = connectionInfo.ConnectionDetails.ServerName,
                    DatabaseName = connectionInfo.ConnectionDetails.DatabaseName,
                    UserName     = connectionInfo.ConnectionDetails.UserName,
                };

                response.ConnectionId = connectionInfo.ConnectionId.ToString();

                var          reliableConnection   = connection as ReliableSqlConnection;
                DbConnection underlyingConnection = reliableConnection != null
                    ? reliableConnection.GetUnderlyingConnection()
                    : connection;

                ReliableConnectionHelper.ServerInfo serverInfo = ReliableConnectionHelper.GetServerVersion(underlyingConnection);
                response.ServerInfo = new ServerInfo
                {
                    ServerMajorVersion   = serverInfo.ServerMajorVersion,
                    ServerMinorVersion   = serverInfo.ServerMinorVersion,
                    ServerReleaseVersion = serverInfo.ServerReleaseVersion,
                    EngineEditionId      = serverInfo.EngineEditionId,
                    ServerVersion        = serverInfo.ServerVersion,
                    ServerLevel          = serverInfo.ServerLevel,
                    ServerEdition        = serverInfo.ServerEdition,
                    IsCloud      = serverInfo.IsCloud,
                    AzureVersion = serverInfo.AzureVersion,
                    OsVersion    = serverInfo.OsVersion
                };
                connectionInfo.IsAzure      = serverInfo.IsCloud;
                connectionInfo.MajorVersion = serverInfo.ServerMajorVersion;
                connectionInfo.IsSqlDW      = (serverInfo.EngineEditionId == (int)DatabaseEngineEdition.SqlDataWarehouse);
            }
            catch (Exception ex)
            {
                response.Messages = ex.ToString();
            }

            return(response);
        }
Beispiel #14
0
        public void TestTryGetServerVersion()
        {
            TestUtils.RunIfWindows(() =>
            {
                ReliableConnectionHelper.ServerInfo info = null;
                Assert.True(ReliableConnectionHelper.TryGetServerVersion(CreateTestConnectionStringBuilder().ConnectionString, out info));

                Assert.NotNull(info);
                Assert.NotNull(info.ServerVersion);
                Assert.NotEmpty(info.ServerVersion);
            });
        }
Beispiel #15
0
        /// <summary>
        /// Determines if a connection is being made to a SQL DW database.
        /// </summary>
        /// <param name="conn">A connection object.</param>
        private bool IsSqlDwConnection(IDbConnection conn)
        {
            //Set the connection only if it has not been set earlier.
            //This is assuming that it is highly unlikely for a connection to change between instances.
            //Hence any subsequent calls to this method will just return the cached value and not
            //verify again if this is a SQL DW database connection or not.
            if (!CachedServerInfo.Instance.TryGetIsSqlDw(conn, out _isSqlDwDatabase))
            {
                _isSqlDwDatabase = ReliableConnectionHelper.IsSqlDwDatabase(conn);
                CachedServerInfo.Instance.AddOrUpdateIsSqlDw(conn, _isSqlDwDatabase);;
            }

            return(_isSqlDwDatabase);
        }
        public void ReliableConnectionHelperTest()
        {
            ScriptFile     scriptFile;
            ConnectionInfo connInfo = TestObjects.InitLiveConnectionInfo(out scriptFile);

            Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(connInfo.SqlConnection));

            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

            Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(builder));
            ReliableConnectionHelper.TryAddAlwaysOnConnectionProperties(builder, new SqlConnectionStringBuilder());

            Assert.NotNull(ReliableConnectionHelper.GetServerName(connInfo.SqlConnection));
            Assert.NotNull(ReliableConnectionHelper.ReadServerVersion(connInfo.SqlConnection));

            Assert.NotNull(ReliableConnectionHelper.GetAsSqlConnection(connInfo.SqlConnection));

            ServerInfo info = ReliableConnectionHelper.GetServerVersion(connInfo.SqlConnection);

            Assert.NotNull(ReliableConnectionHelper.IsVersionGreaterThan2012RTM(info));
        }
        public void ReliableConnectionHelperTest()
        {
            var            result     = LiveConnectionHelper.InitLiveConnectionInfo();
            ConnectionInfo connInfo   = result.ConnectionInfo;
            DbConnection   connection = connInfo.ConnectionTypeToConnectionMap[ConnectionType.Default];


            Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(connection));

            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

            Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(builder));
            ReliableConnectionHelper.TryAddAlwaysOnConnectionProperties(builder, new SqlConnectionStringBuilder());

            Assert.NotNull(ReliableConnectionHelper.GetServerName(connection));
            Assert.NotNull(ReliableConnectionHelper.ReadServerVersion(connection));

            Assert.NotNull(ReliableConnectionHelper.GetAsSqlConnection(connection));

            ReliableConnectionHelper.ServerInfo info = ReliableConnectionHelper.GetServerVersion(connection);
            Assert.NotNull(ReliableConnectionHelper.IsVersionGreaterThan2012RTM(info));
        }
Beispiel #18
0
        public void TestGetDefaultDatabaseFilePath()
        {
            var connectionBuilder = CreateTestConnectionStringBuilder();

            Assert.NotNull(connectionBuilder);

            string filePath = string.Empty;
            string logPath  = string.Empty;

            ReliableConnectionHelper.OpenConnection(
                connectionBuilder,
                usingConnection: (conn) =>
            {
                filePath = ReliableConnectionHelper.GetDefaultDatabaseFilePath(conn);
                logPath  = ReliableConnectionHelper.GetDefaultDatabaseLogPath(conn);
            },
                catchException: null,
                useRetry: false);

            Assert.False(string.IsNullOrWhiteSpace(filePath));
            Assert.False(string.IsNullOrWhiteSpace(logPath));
        }
Beispiel #19
0
        public async void GetAssessmentItemsServerTest()
        {
            var liveConnection = LiveConnectionHelper.InitLiveConnectionInfo("master");

            var connection = liveConnection.ConnectionInfo.AllConnections.FirstOrDefault();

            Debug.Assert(connection != null, "Live connection is always expected providing a connection");

            var serverInfo = ReliableConnectionHelper.GetServerVersion(connection);

            var response = await CallAssessment <CheckInfo>(
                nameof(SqlAssessmentService.GetAssessmentItems),
                SqlObjectType.Server,
                liveConnection);

            Assert.All(
                response.Items,
                i =>
            {
                AssertInfoPresent(i);
                Assert.Equal(serverInfo.ServerName, i.TargetName);
            });
        }
        public void ReliableConnectionHelperTest()
        {
            using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile())
            {
                var            result     = LiveConnectionHelper.InitLiveConnectionInfo(null, queryTempFile.FilePath);
                ConnectionInfo connInfo   = result.ConnectionInfo;
                DbConnection   connection = connInfo.ConnectionTypeToConnectionMap[ConnectionType.Default];

                Assert.True(connection.State == ConnectionState.Open, "Connection should be open.");
                Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(connection));

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
                Assert.True(ReliableConnectionHelper.IsAuthenticatingDatabaseMaster(builder));
                ReliableConnectionHelper.TryAddAlwaysOnConnectionProperties(builder, new SqlConnectionStringBuilder());

                Assert.NotNull(ReliableConnectionHelper.GetServerName(connection));
                Assert.NotNull(ReliableConnectionHelper.ReadServerVersion(connection));

                Assert.NotNull(ReliableConnectionHelper.GetAsSqlConnection(connection));

                ReliableConnectionHelper.ServerInfo info = ReliableConnectionHelper.GetServerVersion(connection);
                Assert.NotNull(ReliableConnectionHelper.IsVersionGreaterThan2012RTM(info));
            }
        }
        /// <summary>
        /// Open a connection with the specified connection details
        /// </summary>
        /// <param name="connectionParams"></param>
        public async Task <ConnectionCompleteParams> Connect(ConnectParams connectionParams)
        {
            // Validate parameters
            string paramValidationErrorMessage;

            if (connectionParams == null)
            {
                return(new ConnectionCompleteParams
                {
                    Messages = SR.ConnectionServiceConnectErrorNullParams
                });
            }
            if (!connectionParams.IsValid(out paramValidationErrorMessage))
            {
                return(new ConnectionCompleteParams
                {
                    OwnerUri = connectionParams.OwnerUri,
                    Messages = paramValidationErrorMessage
                });
            }

            // Resolve if it is an existing connection
            // Disconnect active connection if the URI is already connected
            ConnectionInfo connectionInfo;

            if (ownerToConnectionMap.TryGetValue(connectionParams.OwnerUri, out connectionInfo))
            {
                var disconnectParams = new DisconnectParams()
                {
                    OwnerUri = connectionParams.OwnerUri
                };
                Disconnect(disconnectParams);
            }
            connectionInfo = new ConnectionInfo(ConnectionFactory, connectionParams.OwnerUri, connectionParams.Connection);

            // try to connect
            var response = new ConnectionCompleteParams {
                OwnerUri = connectionParams.OwnerUri
            };
            CancellationTokenSource source = null;

            try
            {
                // build the connection string from the input parameters
                string connectionString = BuildConnectionString(connectionInfo.ConnectionDetails);

                // create a sql connection instance
                connectionInfo.SqlConnection = connectionInfo.Factory.CreateSqlConnection(connectionString);

                // Add a cancellation token source so that the connection OpenAsync() can be cancelled
                using (source = new CancellationTokenSource())
                {
                    // Locking here to perform two operations as one atomic operation
                    lock (cancellationTokenSourceLock)
                    {
                        // If the URI is currently connecting from a different request, cancel it before we try to connect
                        CancellationTokenSource currentSource;
                        if (ownerToCancellationTokenSourceMap.TryGetValue(connectionParams.OwnerUri, out currentSource))
                        {
                            currentSource.Cancel();
                        }
                        ownerToCancellationTokenSourceMap[connectionParams.OwnerUri] = source;
                    }

                    // Create a task to handle cancellation requests
                    var cancellationTask = Task.Run(() =>
                    {
                        source.Token.WaitHandle.WaitOne();
                        try
                        {
                            source.Token.ThrowIfCancellationRequested();
                        }
                        catch (ObjectDisposedException)
                        {
                            // Ignore
                        }
                    });

                    var openTask = Task.Run(async() => {
                        await connectionInfo.SqlConnection.OpenAsync(source.Token);
                    });

                    // Open the connection
                    await Task.WhenAny(openTask, cancellationTask).Unwrap();

                    source.Cancel();
                }
            }
            catch (SqlException ex)
            {
                response.ErrorNumber  = ex.Number;
                response.ErrorMessage = ex.Message;
                response.Messages     = ex.ToString();
                return(response);
            }
            catch (OperationCanceledException)
            {
                // OpenAsync was cancelled
                response.Messages = SR.ConnectionServiceConnectionCanceled;
                return(response);
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
                response.Messages     = ex.ToString();
                return(response);
            }
            finally
            {
                // Remove our cancellation token from the map since we're no longer connecting
                // Using a lock here to perform two operations as one atomic operation
                lock (cancellationTokenSourceLock)
                {
                    // Only remove the token from the map if it is the same one created by this request
                    CancellationTokenSource sourceValue;
                    if (ownerToCancellationTokenSourceMap.TryGetValue(connectionParams.OwnerUri, out sourceValue) && sourceValue == source)
                    {
                        ownerToCancellationTokenSourceMap.TryRemove(connectionParams.OwnerUri, out sourceValue);
                    }
                }
            }

            ownerToConnectionMap[connectionParams.OwnerUri] = connectionInfo;

            // Update with the actual database name in connectionInfo and result
            // Doing this here as we know the connection is open - expect to do this only on connecting
            connectionInfo.ConnectionDetails.DatabaseName = connectionInfo.SqlConnection.Database;
            response.ConnectionSummary = new ConnectionSummary
            {
                ServerName   = connectionInfo.ConnectionDetails.ServerName,
                DatabaseName = connectionInfo.ConnectionDetails.DatabaseName,
                UserName     = connectionInfo.ConnectionDetails.UserName,
            };

            // invoke callback notifications
            InvokeOnConnectionActivities(connectionInfo);

            // try to get information about the connected SQL Server instance
            try
            {
                var          reliableConnection = connectionInfo.SqlConnection as ReliableSqlConnection;
                DbConnection connection         = reliableConnection != null?reliableConnection.GetUnderlyingConnection() : connectionInfo.SqlConnection;

                ReliableConnectionHelper.ServerInfo serverInfo = ReliableConnectionHelper.GetServerVersion(connection);
                response.ServerInfo = new ServerInfo
                {
                    ServerMajorVersion   = serverInfo.ServerMajorVersion,
                    ServerMinorVersion   = serverInfo.ServerMinorVersion,
                    ServerReleaseVersion = serverInfo.ServerReleaseVersion,
                    EngineEditionId      = serverInfo.EngineEditionId,
                    ServerVersion        = serverInfo.ServerVersion,
                    ServerLevel          = serverInfo.ServerLevel,
                    ServerEdition        = serverInfo.ServerEdition,
                    IsCloud      = serverInfo.IsCloud,
                    AzureVersion = serverInfo.AzureVersion,
                    OsVersion    = serverInfo.OsVersion
                };
                connectionInfo.IsAzure = serverInfo.IsCloud;
            }
            catch (Exception ex)
            {
                response.Messages = ex.ToString();
            }

            // return the connection result
            response.ConnectionId = connectionInfo.ConnectionId.ToString();
            return(response);
        }
Beispiel #22
0
 /// <summary>
 /// Disconnects a sqlcmd connection
 /// </summary>
 private void DisconnectSqlCmdInternal()
 {
     if (isSqlCmdConnection)
     {
         RaiseBatchMessage(string.Format(CultureInfo.CurrentCulture, "Disconnection from server {0}", ReliableConnectionHelper.GetServerName(connection)));
         CloseConnection(connection);
     }
 }
Beispiel #23
0
        /// <summary>
        /// Create a set of batches to be executed before and after the script is executed
        /// </summary>
        /// <remarks>
        /// This is the way some server side settings can be set. Additionally, it supports
        /// a way to wrap the script execution within a transaction block
        /// </remarks>
        private void CreatePrePostConditionBatches()
        {
            StringBuilder scriptPreBatches  = new StringBuilder();
            StringBuilder scriptPostBatches = new StringBuilder();
            int           serverVersion     = 8;

            if (connection != null && connection.State == ConnectionState.Open)
            {
                serverVersion = new Version(ReliableConnectionHelper.ReadServerVersion(connection)).Major;
            }

            ConfigurePrePostConditionBatches(preConditionBatches);
            ConfigurePrePostConditionBatches(postConditionBatches);

            if (conditions.IsNoExec)
            {
                scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.NoExecStatement(false));
            }

            if (conditions.IsStatisticsIO)
            {
                scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsIOStatement(true));
                scriptPostBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsIOStatement(false));
            }

            if (conditions.IsStatisticsTime)
            {
                scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsTimeStatement(true));
                scriptPostBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsTimeStatement(false));
            }

            if (conditions.IsEstimatedShowPlan)
            {
                if (serverVersion >= 9)
                {
                    scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.ShowPlanXmlStatement(true));
                    scriptPostBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.ShowPlanXmlStatement(false));
                    expectedShowPlan = ShowPlanType.EstimatedXmlShowPlan;
                }
                else
                {
                    scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.ShowPlanAllStatement(true));
                    scriptPostBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.ShowPlanAllStatement(false));
                    expectedShowPlan = ShowPlanType.EstimatedExecutionShowPlan;
                }
            }
            else if (conditions.IsActualShowPlan)
            {
                if (serverVersion >= 9)
                {
                    scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsXmlStatement(true));
                    scriptPostBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsXmlStatement(false));
                    expectedShowPlan = ShowPlanType.ActualXmlShowPlan;
                }
                else
                {
                    scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsProfileStatement(true));
                    scriptPostBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.StatisticsProfileStatement(false));
                    expectedShowPlan = ShowPlanType.ActualExecutionShowPlan;
                }
            }

            if (conditions.IsTransactionWrapped)
            {
                scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.BeginTransactionStatement);
                // issuing a Rollback or a Commit will depend on the script execution result
            }

            if (conditions.IsParseOnly)
            {
                scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.ParseOnlyStatement(true));
                scriptPostBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.ParseOnlyStatement(false));
            }

            if (conditions.IsNoExec)
            {
                scriptPreBatches.AppendFormat(CultureInfo.InvariantCulture, "{0} ", ExecutionEngineConditions.NoExecStatement(true));
            }

            if (conditions.IsShowPlanText &&
                !conditions.IsEstimatedShowPlan &&
                !conditions.IsActualShowPlan)
            {
                // SET SHOWPLAN_TEXT cannot be used with other statements in the batch
                preConditionBatches.Insert(0,
                                           new Batch(
                                               string.Format(CultureInfo.CurrentCulture, "{0} ", ExecutionEngineConditions.ShowPlanTextStatement(true)),
                                               false,
                                               executionTimeout));

                postConditionBatches.Insert(0,
                                            new Batch(
                                                string.Format(CultureInfo.CurrentCulture, "{0} ", ExecutionEngineConditions.ShowPlanTextStatement(false)),
                                                false,
                                                executionTimeout));
            }

            string preBatches  = scriptPreBatches.ToString().Trim();
            string postBatches = scriptPostBatches.ToString().Trim();

            if (scriptPreBatches.Length > 0)
            {
                preConditionBatches.Add(new Batch(preBatches, false, executionTimeout));
            }

            if (scriptPostBatches.Length > 0)
            {
                postConditionBatches.Add(new Batch(postBatches, false, executionTimeout));
            }
        }
Beispiel #24
0
        public void GetConnectionStringBuilderNullConnectionString()
        {
            SqlConnectionStringBuilder builder;

            Assert.False(ReliableConnectionHelper.TryGetConnectionStringBuilder(null, out builder));
        }
Beispiel #25
0
 public void StandardExceptionHandlerTests()
 {
     Assert.True(ReliableConnectionHelper.StandardExceptionHandler(new InvalidCastException()));
     Assert.False(ReliableConnectionHelper.StandardExceptionHandler(new Exception()));
 }
Beispiel #26
0
 public void SetLockAndCommandTimeoutThrowsOnNull()
 {
     Assert.Throws(typeof(ArgumentNullException), () => ReliableConnectionHelper.SetLockAndCommandTimeout(null));
 }
Beispiel #27
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);
        }
Beispiel #28
0
 public void TestIsDatabaseReadonlyWithNullBuilder()
 {
     Assert.Throws <ArgumentNullException>(() => ReliableConnectionHelper.IsDatabaseReadonly(null, null));
 }