public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            Task t = TestAsync(srcConstr, dstConstr, dstTable);

            DataTestUtility.AssertThrowsWrapper <AggregateException, InvalidOperationException>(() => t.Wait());
            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
        }
Exemple #2
0
            private void ReadCommitedIsolationLevel_ShouldReceiveTimeoutExceptionBecauseItWaitsForUncommitedTransaction()
            {
                using (SqlConnection connection1 = new SqlConnection(_connectionString))
                {
                    connection1.Open();
                    SqlTransaction tx1 = connection1.BeginTransaction();

                    using (SqlCommand command1 = connection1.CreateCommand())
                    {
                        command1.Transaction = tx1;
                        command1.CommandText = "INSERT INTO " + _tempTableName1 + " VALUES ( 'ZYXWV', 'XYZ', 'John' );";
                        command1.ExecuteNonQuery();
                    }

                    using (SqlConnection connection2 = new SqlConnection(_connectionString))
                    {
                        SqlCommand command2 =
                            new SqlCommand("select * from " + _tempTableName1 + " where CustomerID='ZYXWV'",
                                           connection2);

                        connection2.Open();
                        SqlTransaction tx2 = connection2.BeginTransaction(IsolationLevel.ReadCommitted);
                        command2.Transaction = tx2;

                        DataTestUtility.AssertThrowsWrapper <SqlException>(() => command2.ExecuteReader(), SystemDataResourceManager.Instance.SQL_Timeout as string);

                        tx2.Rollback();
                        connection2.Close();
                    }

                    tx1.Rollback();
                    connection1.Close();
                }
            }
        public void Test_DoubleStart_DifferentConnStr()
        {
            SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder(_startConnectionString);

            // just change something that doesn't impact the dependency dispatcher
            if (cb.ShouldSerialize("connect timeout"))
            {
                cb.ConnectTimeout = cb.ConnectTimeout + 1;
            }
            else
            {
                cb.ConnectTimeout = 50;
            }

            Assert.True(SqlDependency.Start(_startConnectionString), "Failed to start listener.");

            try
            {
                DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() => SqlDependency.Start(cb.ToString()));
            }
            finally
            {
                Assert.True(SqlDependency.Stop(_startConnectionString), "Failed to stop listener.");

                Assert.False(SqlDependency.Stop(cb.ToString()), "Expected failure when trying to completely stop listener.");
            }
        }
Exemple #4
0
 private static void OpenBadConnection <T>(string connectionString, string errorMessage = null) where T : Exception
 {
     using (SqlConnection conn = new SqlConnection(connectionString))
     {
         DataTestUtility.AssertThrowsWrapper <T>(() => conn.Open(), errorMessage);
     }
 }
Exemple #5
0
 public static void InvalidDBTest()
 {
     using (var connection = new SqlConnection(@"Data Source=(localdb)\MSSQLLOCALDB;Database=DOES_NOT_EXIST;Pooling=false;"))
     {
         DataTestUtility.AssertThrowsWrapper <SqlException>(() => connection.Open());
     }
 }
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            using (SqlConnection dstConn = new SqlConnection(dstConstr))
                using (SqlCommand dstCmd = dstConn.CreateCommand())
                {
                    dstConn.Open();
                    try
                    {
                        Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");

                        using (SqlConnection srcConn = new SqlConnection(srcConstr))
                            using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
                            {
                                srcConn.Open();

                                using (DbDataReader reader = srcCmd.ExecuteReader())
                                    using (SqlConnection conn3 = new SqlConnection(srcConstr))
                                    {
                                        conn3.Open();
                                        // Start a local transaction on the wrong connection.
                                        SqlTransaction myTrans  = conn3.BeginTransaction();
                                        string         errorMsg = SystemDataResourceManager.Instance.SQL_BulkLoadConflictingTransactionOption;
                                        DataTestUtility.AssertThrowsWrapper <ArgumentException>(() => new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, myTrans), exceptionMessage: errorMsg);
                                    }
                            }
                    }
                    finally
                    {
                        Helpers.TryExecute(dstCmd, "drop table " + dstTable);
                    }
                }
        }
Exemple #7
0
        public void UDTParams_Binary()
        {
            using (SqlConnection conn = new SqlConnection(_connStr))
                using (SqlCommand cmd = new SqlCommand("vicinity", conn))
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.VarBinary, 8);
                    p.Direction = ParameterDirection.Input;

                    byte[] value = new byte[8];
                    value[0] = 0xF0;
                    value[1] = 0;
                    value[2] = 0;
                    value[3] = 0;
                    value[4] = 0xF0;
                    value[5] = 0;
                    value[6] = 0;
                    value[7] = 0;
                    p.Value  = new SqlBinary(value);

                    DataTestUtility.AssertThrowsWrapper <SqlException>(
                        () => cmd.ExecuteReader(),
                        "Error converting data type varbinary to Point.");
                }
        }
Exemple #8
0
        public void UDTFields_WrongType()
        {
            using (SqlConnection cn = new SqlConnection(_connStr))
                using (SqlCommand cmd = new SqlCommand("select name,location from cities order by name", cn))
                {
                    cn.Open();
                    cmd.CommandType = CommandType.Text;

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        reader.Read();

                        DataTestUtility.AssertEqualsWithDescription(
                            "beaverton", reader.GetValue(0),
                            "Unexpected reader value.");
                        DataTestUtility.AssertEqualsWithDescription(
                            "14.8660687473185", ((Point)reader.GetValue(1)).Distance().ToString(),
                            "Unexpected distance value.");

                        reader.Read();

                        // retrieve the UDT as a string
                        DataTestUtility.AssertThrowsWrapper <InvalidCastException>(
                            () => reader.GetString(1),
                            "Unable to cast object of type 'System.Byte[]' to type 'System.String'.");
                    }
                }
        }
Exemple #9
0
            private void ExceptionTest()
            {
                using (SqlConnection connection = new SqlConnection(_connectionString))
                {
                    connection.Open();

                    SqlTransaction tx = connection.BeginTransaction();

                    string invalidSaveStateMessage = SystemDataResourceManager.Instance.SQL_NullEmptyTransactionName;
                    string executeCommandWithoutTransactionMessage = SystemDataResourceManager.Instance.ADP_TransactionRequired("ExecuteNonQuery");
                    string transactionConflictErrorMessage         = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
                    string parallelTransactionErrorMessage         = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported("SqlConnection");
                    DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() =>
                    {
                        SqlCommand command = new SqlCommand("sql", connection);
                        command.ExecuteNonQuery();
                    }, executeCommandWithoutTransactionMessage);

                    DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() =>
                    {
                        SqlConnection con1 = new SqlConnection(_connectionString);
                        con1.Open();

                        SqlCommand command  = new SqlCommand("sql", con1);
                        command.Transaction = tx;
                        command.ExecuteNonQuery();
                    }, transactionConflictErrorMessage);

                    DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() =>
                    {
                        connection.BeginTransaction(null);
                    }, parallelTransactionErrorMessage);

                    DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() =>
                    {
                        connection.BeginTransaction("");
                    }, parallelTransactionErrorMessage);

                    DataTestUtility.AssertThrowsWrapper <ArgumentException>(() =>
                    {
                        tx.Rollback(null);
                    }, invalidSaveStateMessage);

                    DataTestUtility.AssertThrowsWrapper <ArgumentException>(() =>
                    {
                        tx.Rollback("");
                    }, invalidSaveStateMessage);

                    DataTestUtility.AssertThrowsWrapper <ArgumentException>(() =>
                    {
                        tx.Save(null);
                    }, invalidSaveStateMessage);

                    DataTestUtility.AssertThrowsWrapper <ArgumentException>(() =>
                    {
                        tx.Save("");
                    }, invalidSaveStateMessage);
                }
            }
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            cts = new CancellationTokenSource();
            cts.Cancel();
            Task t = TestAsync(srcConstr, dstConstr, dstTable, cts.Token);

            DataTestUtility.AssertThrowsWrapper <AggregateException, TaskCanceledException>(() => t.Wait());
            Assert.True(t.IsCompleted, "Task did not complete! Status: " + t.Status);
        }
Exemple #11
0
        public static void LocalDBNotSupportedOnUapTest()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(@"server=(localdb)\MSSQLLocalDB");

            builder.IntegratedSecurity = true;
            builder.ConnectTimeout     = 2;

            DataTestUtility.AssertThrowsWrapper <PlatformNotSupportedException>(() => OpenConnection(builder.ConnectionString));
        }
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
#if DEBUG
            string initialQueryTemplate = "create table {0} (col1 int, col2 nvarchar(20), col3 nvarchar(10), col4 varchar(8000))";
            string sourceQuery          = "select EmployeeID, LastName, FirstName, REPLICATE('a', 8000) from employees";
            string initialQuery         = string.Format(initialQueryTemplate, dstTable);

            using (SqlConnection dstConn = new SqlConnection(dstConstr))
                using (SqlCommand dstCmd = dstConn.CreateCommand())
                {
                    dstConn.Open();

                    try
                    {
                        Helpers.TryExecute(dstCmd, initialQuery);
                        using (SqlConnection srcConn = new SqlConnection(srcConstr))
                            using (SqlCommand srcCmd = new SqlCommand(sourceQuery, srcConn))
                            {
                                srcConn.Open();

                                using (DbDataReader reader = srcCmd.ExecuteReader())
                                {
                                    using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
                                    {
                                        bulkcopy.DestinationTableName = dstTable;

                                        // Close the bulk copy's connection when it notifies us
                                        bulkcopy.NotifyAfter    = 1;
                                        bulkcopy.SqlRowsCopied += (sender, e) =>
                                        {
                                            dstConn.Close();
                                        };

                                        using (AsyncDebugScope debugScope = new AsyncDebugScope())
                                        {
                                            // Force all writes to pend, this will guarantee that we will go through the correct code path
                                            debugScope.ForceAsyncWriteDelay = 1;

                                            // Check that the copying fails
                                            string message = string.Format(SystemDataResourceManager.Instance.ADP_OpenConnectionRequired, "WriteToServer", SystemDataResourceManager.Instance.ADP_ConnectionStateMsg_Closed);
                                            DataTestUtility.AssertThrowsWrapper <AggregateException, InvalidOperationException>(() => bulkcopy.WriteToServerAsync(reader).Wait(5000), innerExceptionMessage: message);
                                        }
                                    }
                                }
                            }
                    }
                    finally
                    {
                        Helpers.TryDropTable(dstConstr, dstTable);
                    }
                }
#endif
        }
Exemple #13
0
        private static void TimeoutCancel(string constr)
        {
            using (SqlConnection con = new SqlConnection(constr))
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = 1;
                cmd.CommandText    = "WAITFOR DELAY '00:00:30';select * from Customers";

                string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
                DataTestUtility.AssertThrowsWrapper <SqlException>(() => cmd.ExecuteReader(), errorMessage);

                VerifyConnection(cmd);
            }
        }
        public void Test_SingleDependency_NoStart()
        {
            using (SqlConnection conn = new SqlConnection(_execConnectionString))
                using (SqlCommand cmd = new SqlCommand("SELECT a, b, c FROM " + _tableName, conn))
                {
                    conn.Open();

                    SqlDependency dep = new SqlDependency(cmd);
                    dep.OnChange += delegate(object o, SqlNotificationEventArgs args)
                    {
                        Console.WriteLine("4 Notification callback. Type={0}, Info={1}, Source={2}", args.Type, args.Info, args.Source);
                    };

                    DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() => cmd.ExecuteReader());
                }
        }
Exemple #15
0
        public void UDTParams_Invalid()
        {
            using (SqlConnection conn = new SqlConnection(_connStr))
                using (SqlCommand cmd = new SqlCommand("vicinity", conn))
                {
                    conn.Open();
                    cmd.CommandType = CommandType.StoredProcedure;

                    SqlParameter p = cmd.Parameters.Add("@boundary", SqlDbType.Udt);
                    p.UdtTypeName = "UdtTestDb.dbo.Point";
                    p.Value       = 32;

                    DataTestUtility.AssertThrowsWrapper <ArgumentException>(
                        () => cmd.ExecuteReader(),
                        "Specified type is not registered on the target server. System.Int32");
                }
        }
Exemple #16
0
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            using (SqlConnection dstConn = new SqlConnection(dstConstr))
                using (SqlCommand dstCmd = dstConn.CreateCommand())
                {
                    dstConn.Open();

                    try
                    {
                        Helpers.Execute(dstCmd, "create table " + dstTable + " (orderid int, customerid nchar(5), rdate datetime, freight money, shipname nvarchar(40))");

                        using (SqlConnection srcConn = new SqlConnection(srcConstr))
                            using (SqlCommand srcCmd = new SqlCommand("select top 100 * from orders", srcConn))
                            {
                                srcConn.Open();

                                using (DbDataReader reader = srcCmd.ExecuteReader())
                                    using (bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, null))
                                    {
                                        bulkcopy.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnRowCopied);

                                        bulkcopy.DestinationTableName = dstTable;
                                        bulkcopy.NotifyAfter          = 50;

                                        SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;

                                        ColumnMappings.Add("OrderID", "orderid");
                                        ColumnMappings.Add("CustomerID", "customerid");
                                        ColumnMappings.Add("RequiredDate", "rdate");
                                        ColumnMappings.Add("Freight", "freight");
                                        ColumnMappings.Add("ShipName", "shipname");

                                        bulkcopy.NotifyAfter = 3;
                                        DataTestUtility.AssertThrowsWrapper <OperationAbortedException>(() => bulkcopy.WriteToServer(reader));
                                        bulkcopy.SqlRowsCopied -= new SqlRowsCopiedEventHandler(OnRowCopied);
                                        bulkcopy.Close();
                                    }
                            }
                    }
                    finally
                    {
                        Helpers.Execute(dstCmd, "drop table " + dstTable);
                    }
                }
        }
Exemple #17
0
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            using (SqlConnection dstConn = new SqlConnection(dstConstr))
                using (SqlCommand dstCmd = dstConn.CreateCommand())
                {
                    dstConn.Open();

                    try
                    {
                        Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");

                        using (SqlConnection srcConn = new SqlConnection(srcConstr))
                            using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
                            {
                                srcConn.Open();

                                using (DbDataReader reader = srcCmd.ExecuteReader())
                                    using (SqlConnection conn3 = new SqlConnection(srcConstr))
                                    {
                                        conn3.Open();
                                        // Start a local transaction on the wrong connection.
                                        SqlTransaction myTrans = conn3.BeginTransaction();
                                        using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.Default, myTrans))
                                        {
                                            SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;
                                            bulkcopy.DestinationTableName = dstTable;

                                            string exceptionMsg = SystemDataResourceManager.Instance.ADP_TransactionConnectionMismatch;
                                            DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() => bulkcopy.WriteToServer(reader), exceptionMessage: exceptionMsg);

                                            SqlCommand myCmd = dstConn.CreateCommand();
                                            myCmd.CommandText = "select * from " + dstTable;
                                            myCmd.Transaction = myTrans;

                                            DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() => myCmd.ExecuteReader(), exceptionMessage: exceptionMsg);
                                        }
                                    }
                            }
                    }
                    finally
                    {
                        Helpers.TryExecute(dstCmd, "drop table " + dstTable);
                    }
                }
        }
Exemple #18
0
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            using (SqlConnection dstConn = new SqlConnection(dstConstr))
                using (SqlCommand dstCmd = dstConn.CreateCommand())
                {
                    dstConn.Open();

                    try
                    {
                        Helpers.TryExecute(dstCmd, "create table " + dstTable + " (col1 int, col2 nvarchar(20), col3 nvarchar(10))");

                        using (SqlConnection srcConn = new SqlConnection(srcConstr))
                            using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
                            {
                                srcConn.Open();

                                using (DbDataReader reader = srcCmd.ExecuteReader())
                                    using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn, SqlBulkCopyOptions.UseInternalTransaction, null))
                                    {
                                        bulkcopy.DestinationTableName = dstTable;
                                        SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;

                                        SqlCommand myCmd = dstConn.CreateCommand();
                                        myCmd.CommandText = "begin transaction";
                                        myCmd.ExecuteNonQuery();

                                        try
                                        {
                                            DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() => bulkcopy.WriteToServer(reader));
                                        }
                                        finally
                                        {
                                            myCmd.CommandText = "rollback transaction";
                                            myCmd.ExecuteNonQuery();
                                        }
                                    }
                            }
                    }
                    finally
                    {
                        Helpers.TryExecute(dstCmd, "drop table " + dstTable);
                    }
                }
        }
Exemple #19
0
        public void UDTParams_NullInput()
        {
            string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
            string tableName        = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2_Customer");

            using (SqlConnection conn = new SqlConnection(_connStr))
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    conn.Open();

                    cmd.Transaction = conn.BeginTransaction();
                    cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "create proc " + spInsertCustomer + "(@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
                    cmd.ExecuteNonQuery();
                    try
                    {
                        cmd.CommandText = spInsertCustomer;
                        cmd.CommandType = CommandType.StoredProcedure;

                        SqlParameter pName = cmd.Parameters.Add("@name", SqlDbType.NVarChar, 20);
                        SqlParameter p     = cmd.Parameters.Add("@addr", SqlDbType.Udt);

                        p.UdtTypeName = "UdtTestDb.dbo.Address";
                        p.Value       = null;
                        pName.Value   = "john";

                        string spInsertCustomerNoBrackets = spInsertCustomer;
                        if (spInsertCustomer.StartsWith("[") && spInsertCustomer.EndsWith("]"))
                        {
                            spInsertCustomerNoBrackets = spInsertCustomer.Substring(1, spInsertCustomer.Length - 2);
                        }
                        string errorMsg = "Procedure or function '" + spInsertCustomerNoBrackets + "' expects parameter '@addr', which was not supplied.";

                        DataTestUtility.AssertThrowsWrapper <SqlException>(
                            () => cmd.ExecuteNonQuery(),
                            errorMsg);
                    }
                    finally
                    {
                        cmd.Transaction.Rollback();
                    }
                }
        }
Exemple #20
0
        private static void TimeOutDuringRead(string constr)
        {
            // Create the proxy
            ProxyServer proxy = ProxyServer.CreateAndStartProxy(constr, out constr);

            proxy.SimulatedPacketDelay = 100;
            proxy.SimulatedOutDelay    = true;

            try
            {
                using (SqlConnection conn = new SqlConnection(constr))
                {
                    // Start the command
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("SELECT @p", conn);
                    cmd.Parameters.AddWithValue("p", new byte[20000]);
                    SqlDataReader reader = cmd.ExecuteReader();
                    reader.Read();

                    // Tweak the timeout to 1ms, stop the proxy from proxying and then try GetValue (which should timeout)
                    reader.SetDefaultTimeout(1);
                    proxy.PauseCopying();
                    string errorMessage = SystemDataResourceManager.Instance.SQL_Timeout;
                    DataTestUtility.AssertThrowsWrapper <SqlException>(() => reader.GetValue(0), errorMessage);

                    // Return everything to normal and close
                    proxy.ResumeCopying();
                    reader.SetDefaultTimeout(30000);
                    reader.Dispose();
                }

                proxy.Stop();
            }
            catch
            {
                // In case of error, stop the proxy and dump its logs (hopefully this will help with debugging
                proxy.Stop();
                Console.WriteLine(proxy.GetServerEventLog());
                Assert.True(false, "Error while reading through proxy");
                throw;
            }
        }
Exemple #21
0
        private static void MultipleExecutesInSameTransactionTest_shouldThrowsUnsupported(string connectionString)
        {
            string expectedErrorMessage = SystemDataResourceManager.Instance.ADP_ParallelTransactionsNotSupported(typeof(SqlConnection).Name);
            string tempTableName        = "";

            try
            {
                tempTableName = CreateTempTable(connectionString);
                DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(
                    actionThatFails: () => { MultipleExecutesInSameTransactionTest(connectionString, tempTableName); },
                    exceptionMessage: expectedErrorMessage);
            }
            finally
            {
                if (!string.IsNullOrEmpty(tempTableName))
                {
                    DropTempTable(connectionString, tempTableName);
                }
            }
        }
Exemple #22
0
        public void UDTParams_Invalid2()
        {
            string spInsertCustomer = DataTestUtility.GetUniqueNameForSqlServer("spUdtTest2_InsertCustomer");
            string tableName        = DataTestUtility.GetUniqueNameForSqlServer("UdtTest2");

            using (SqlConnection conn = new SqlConnection(_connStr))
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    conn.Open();

                    cmd.Transaction = conn.BeginTransaction();
                    cmd.CommandText = "create table " + tableName + " (name nvarchar(30), address Address)";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "create proc " + spInsertCustomer + "(@name nvarchar(30), @addr Address OUTPUT)" + " AS insert into " + tableName + " values (@name, @addr)";
                    cmd.ExecuteNonQuery();
                    try
                    {
                        cmd.CommandText = spInsertCustomer;
                        cmd.CommandType = CommandType.StoredProcedure;

                        SqlParameter pName = cmd.Parameters.Add("@fname", SqlDbType.NVarChar, 20);
                        SqlParameter p     = cmd.Parameters.Add("@addr", SqlDbType.Udt);

                        Address addr = Address.Parse("customer whose name is address");
                        p.UdtTypeName = "UdtTestDb.dbo.Address";
                        p.Value       = addr;
                        pName.Value   = addr;

                        DataTestUtility.AssertThrowsWrapper <InvalidCastException>(
                            () => cmd.ExecuteReader(),
                            "Failed to convert parameter value from a Address to a String.");
                    }
                    finally
                    {
                        cmd.Transaction.Rollback();
                    }
                }
        }
Exemple #23
0
 private static void PlainCancelAsync(string connString)
 {
     using (SqlConnection conn = new SqlConnection(connString))
         using (SqlCommand cmd = new SqlCommand("select * from dbo.Orders; waitfor delay '00:00:10'; select * from dbo.Orders", conn))
         {
             conn.Open();
             Task <SqlDataReader> readerTask = cmd.ExecuteReaderAsync();
             DataTestUtility.AssertThrowsWrapper <SqlException>(
                 () =>
             {
                 readerTask.Wait(2000);
                 SqlDataReader reader = readerTask.Result;
                 cmd.Cancel();
                 do
                 {
                     while (reader.Read())
                     {
                     }
                 }while (reader.NextResult());
             },
                 "A severe error occurred on the current command.  The results, if any, should be discarded.");
         }
 }
Exemple #24
0
        private static void ExecuteCommandCancelExpected(object state)
        {
            var        stateTuple   = (Tuple <bool, SqlCommand, Barrier>)state;
            bool       async        = stateTuple.Item1;
            SqlCommand command      = stateTuple.Item2;
            Barrier    threadsReady = stateTuple.Item3;

            string errorMessage = SystemDataResourceManager.Instance.SQL_OperationCancelled;

            DataTestUtility.AssertThrowsWrapper <SqlException>(() =>
            {
                threadsReady.SignalAndWait();
                using (SqlDataReader r = command.ExecuteReader())
                {
                    do
                    {
                        while (r.Read())
                        {
                        }
                    } while (r.NextResult());
                }
            }, errorMessage);
        }
        public static void Test(string srcConstr, string dstConstr, string dstTable)
        {
            using (SqlConnection dstConn = new SqlConnection(dstConstr))
                using (SqlCommand dstCmd = dstConn.CreateCommand())
                {
                    dstConn.Open();

                    try
                    {
                        Helpers.Execute(dstCmd, "create table " + dstTable + " (col1 int, col3 nvarchar(10))");

                        using (SqlConnection srcConn = new SqlConnection(srcConstr))
                            using (SqlCommand srcCmd = new SqlCommand("select top 5 EmployeeID, LastName, FirstName from employees", srcConn))
                            {
                                srcConn.Open();

                                using (DbDataReader reader = srcCmd.ExecuteReader())
                                    using (SqlBulkCopy bulkcopy = new SqlBulkCopy(dstConn))
                                    {
                                        bulkcopy.DestinationTableName = dstTable;
                                        SqlBulkCopyColumnMappingCollection ColumnMappings = bulkcopy.ColumnMappings;

                                        ColumnMappings.Add("EmployeeID", "col1");
                                        ColumnMappings.Add("LastName", "col2"); // this column does not exist
                                        ColumnMappings.Add("FirstName", "col3");

                                        string errorMsg = SystemDataResourceManager.Instance.SQL_BulkLoadNonMatchingColumnMapping;
                                        DataTestUtility.AssertThrowsWrapper <InvalidOperationException>(() => bulkcopy.WriteToServer(reader), exceptionMessage: errorMsg);
                                    }
                            }
                    }
                    finally
                    {
                        Helpers.Execute(dstCmd, "drop table " + dstTable);
                    }
                }
        }
Exemple #26
0
        public void TestSqlUserDefinedAggregateAttributeMaxByteSize()
        {
            Func <int, SqlUserDefinedAggregateAttribute> create
                = (size) => new SqlUserDefinedAggregateAttribute(Format.UserDefined)
                {
                MaxByteSize = size
                };

            SqlUserDefinedAggregateAttribute attribute1 = create(-1);
            SqlUserDefinedAggregateAttribute attribute2 = create(0);
            SqlUserDefinedAggregateAttribute attribute3 = create(SqlUserDefinedAggregateAttribute.MaxByteSizeValue);

            string udtError     = SystemDataResourceManager.Instance.SQLUDT_MaxByteSizeValue;
            string errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", 8001, udtError)).Message;

            DataTestUtility.AssertThrowsWrapper <ArgumentOutOfRangeException>(
                () => create(SqlUserDefinedAggregateAttribute.MaxByteSizeValue + 1),
                errorMessage);

            errorMessage = (new ArgumentOutOfRangeException("MaxByteSize", -2, udtError)).Message;
            DataTestUtility.AssertThrowsWrapper <ArgumentOutOfRangeException>(
                () => create(-2),
                errorMessage);
        }
Exemple #27
0
        public static void CodeCoverageSqlClient()
        {
            SqlParameterCollection opc = new SqlCommand().Parameters;

            Assert.True(opc.Count == 0, string.Format("FAILED: Expected count: {0}. Actual count: {1}.", 0, opc.Count));
            Assert.False(((IList)opc).IsReadOnly, "FAILED: Expected collection to NOT be read only.");
            Assert.False(((IList)opc).IsFixedSize, "FAILED: Expected collection to NOT be fixed size.");
            Assert.False(((IList)opc).IsSynchronized, "FAILED: Expected collection to NOT be synchronized.");
            DataTestUtility.AssertEqualsWithDescription("Object", ((IList)opc).SyncRoot.GetType().Name, "FAILED: Incorrect SyncRoot Name");

            {
                string failValue;
                DataTestUtility.AssertThrowsWrapper <IndexOutOfRangeException>(() => failValue = opc[0].ParameterName, "Invalid index 0 for this SqlParameterCollection with Count=0.");

                DataTestUtility.AssertThrowsWrapper <IndexOutOfRangeException>(() => failValue = opc["@p1"].ParameterName, "An SqlParameter with ParameterName '@p1' is not contained by this SqlParameterCollection.");
            }

            DataTestUtility.AssertThrowsWrapper <ArgumentNullException>(() => opc.Add(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects.");

            opc.Add((object)new SqlParameter());
            IEnumerator enm = opc.GetEnumerator();

            Assert.True(enm.MoveNext(), "FAILED: Expected MoveNext to be true");
            DataTestUtility.AssertEqualsWithDescription("Parameter1", ((SqlParameter)enm.Current).ParameterName, "FAILED: Incorrect ParameterName");

            opc.Add(new SqlParameter());
            DataTestUtility.AssertEqualsWithDescription("Parameter2", opc[1].ParameterName, "FAILED: Incorrect ParameterName");

            opc.Add(new SqlParameter(null, null));
            opc.Add(new SqlParameter(null, SqlDbType.Int));
            DataTestUtility.AssertEqualsWithDescription("Parameter4", opc["Parameter4"].ParameterName, "FAILED: Incorrect ParameterName");

            opc.Add(new SqlParameter("Parameter5", SqlDbType.NVarChar, 20));
            opc.Add(new SqlParameter(null, SqlDbType.NVarChar, 20, "a"));
            opc.RemoveAt(opc[3].ParameterName);
            DataTestUtility.AssertEqualsWithDescription(-1, opc.IndexOf(null), "FAILED: Incorrect index for null value");

            SqlParameter p = opc[0];

            DataTestUtility.AssertThrowsWrapper <ArgumentException>(() => opc.Add((object)p), "The SqlParameter is already contained by another SqlParameterCollection.");

            DataTestUtility.AssertThrowsWrapper <ArgumentException>(() => new SqlCommand().Parameters.Add(p), "The SqlParameter is already contained by another SqlParameterCollection.");

            DataTestUtility.AssertThrowsWrapper <ArgumentNullException>(() => opc.Remove(null), "The SqlParameterCollection only accepts non-null SqlParameter type objects.");

            string pname = p.ParameterName;

            p.ParameterName = pname;
            p.ParameterName = pname.ToUpper();
            p.ParameterName = pname.ToLower();
            p.ParameterName = "@p1";
            p.ParameterName = pname;

            opc.Clear();
            opc.Add(p);

            opc.Clear();
            opc.AddWithValue("@p1", null);

            DataTestUtility.AssertEqualsWithDescription(-1, opc.IndexOf(p.ParameterName), "FAILED: Incorrect index for parameter name");

            opc[0] = p;
            DataTestUtility.AssertEqualsWithDescription(0, opc.IndexOf(p.ParameterName), "FAILED: Incorrect index for parameter name");

            Assert.True(opc.Contains(p.ParameterName), "FAILED: Expected collection to contain provided parameter.");
            Assert.True(opc.Contains(opc[0]), "FAILED: Expected collection to contain provided parameter.");

            opc[0] = p;
            opc[p.ParameterName] = new SqlParameter(p.ParameterName, null);
            opc[p.ParameterName] = new SqlParameter();
            opc.RemoveAt(0);

            new SqlCommand().Parameters.Clear();
            new SqlCommand().Parameters.CopyTo(new object[0], 0);
            Assert.False(new SqlCommand().Parameters.GetEnumerator().MoveNext(), "FAILED: Expected MoveNext to be false");

            DataTestUtility.AssertThrowsWrapper <InvalidCastException>(() => new SqlCommand().Parameters.Add(0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");

            DataTestUtility.AssertThrowsWrapper <InvalidCastException>(() => new SqlCommand().Parameters.Insert(0, 0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");

            DataTestUtility.AssertThrowsWrapper <InvalidCastException>(() => new SqlCommand().Parameters.Remove(0), "The SqlParameterCollection only accepts non-null SqlParameter type objects, not Int32 objects.");

            DataTestUtility.AssertThrowsWrapper <ArgumentException>(() => new SqlCommand().Parameters.Remove(new SqlParameter()), "Attempted to remove an SqlParameter that is not contained by this SqlParameterCollection.");
        }