예제 #1
0
        public void TestOnErrorSqlCmdCommand()
        {
            var            fileStreamFactory  = MemoryFileSystem.GetFileStreamFactory();
            var            liveConnection     = LiveConnectionHelper.InitLiveConnectionInfo("master");
            ConnectionInfo connInfo           = liveConnection.ConnectionInfo;
            string         sqlCmdQuerySuccess = $@"
:on error ignore
GO
select * from sys.databases_wrong where name = 'master'
GO
select * from sys.databases where name = 'master'
GO";

            Query query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQuerySuccess, connInfo, fileStreamFactory, IsSqlCmd: true);

            Assert.True(query.Batches[0].HasExecuted && query.Batches[0].HasError, "first batch should be executed and have error");
            Assert.True(query.Batches[1].HasExecuted, "last batch should be executed");


            string sqlCmdQueryFilaure = $@"
:on error exit
GO
select * from sys.databases_wrong where name = 'master'
GO
select * from sys.databases where name = 'master'
GO";

            query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQueryFilaure, connInfo, fileStreamFactory, IsSqlCmd: true);
            Assert.True(query.Batches[0].HasExecuted && query.Batches[0].HasError, "first batch should be executed and have error");
            Assert.False(query.Batches[1].HasExecuted, "last batch should NOT be executed");
        }
예제 #2
0
        public static QueryExecutionService GetPrimedExecutionService(
            TestResultSet[] data,
            bool isConnected,
            bool throwOnExecute,
            bool throwOnRead,
            WorkspaceService <SqlToolsSettings> workspaceService,
            out ConcurrentDictionary <string, byte[]> storage,
            int sizeFactor = 1)
        {
            // Create a place for the temp "files" to be written
            storage = new ConcurrentDictionary <string, byte[]>();

            // Mock the connection service
            var            connectionService = new Mock <ConnectionService>();
            ConnectionInfo ci = CreateConnectedConnectionInfo(data, throwOnExecute, throwOnRead);
            ConnectionInfo outValMock;

            connectionService
            .Setup(service => service.TryFindConnection(It.IsAny <string>(), out outValMock))
            .OutCallback((string owner, out ConnectionInfo connInfo) => connInfo = isConnected ? ci : null)
            .Returns(isConnected);

            return(new QueryExecutionService(connectionService.Object, workspaceService)
            {
                BufferFileStreamFactory = MemoryFileSystem.GetFileStreamFactory(storage, sizeFactor)
            });
        }
예제 #3
0
        public async Task QueryExecuteMultipleNoOpBatches()
        {
            // Setup:
            // ... Keep track of how many messages were sent
            List <ResultMessage> messages = new List <ResultMessage>();

            // If:
            // ... I create a query from a two batches (with separator)
            ConnectionInfo ci                = Common.CreateTestConnectionInfo(null, false, false);
            string         queryText         = string.Format("{0}\r\nGO\r\n{1}", Common.NoOpQuery, Common.NoOpQuery);
            var            fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            Query          query             = new Query(queryText, ci, new QueryExecutionSettings(), fileStreamFactory);

            BatchCallbackHelper(query,
                                b => { throw new Exception("Batch start handler was called"); },
                                b => { throw new Exception("Batch completed handler was called"); },
                                m => messages.Add(m));

            // .. I then execute the query
            query.Execute();
            await query.ExecutionTask;

            // Then:
            // ... I should get back a query with no batches
            Assert.Equal(2, query.Batches.Length);

            // ... The query shouldn't have completed successfully
            Assert.False(query.HasExecuted);

            // ... The message callback should have been called exactly once
            Assert.Equal(0, messages.Count);
        }
예제 #4
0
        public void TestConnectSqlCmdCommand()
        {
            var            fileStreamFactory  = MemoryFileSystem.GetFileStreamFactory();
            var            liveConnection     = LiveConnectionHelper.InitLiveConnectionInfo("master");
            ConnectionInfo connInfo           = liveConnection.ConnectionInfo;
            string         serverName         = liveConnection.ConnectionInfo.ConnectionDetails.ServerName;
            string         sqlCmdQuerySuccess = $@"
:Connect {serverName}
select * from sys.databases where name = 'master'
GO";

            Query query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQuerySuccess, connInfo, fileStreamFactory, IsSqlCmd: true);

            Assert.True(query.Batches.Length == 1, $"Expected: 1 parsed batch, actual : {query.Batches.Length}");
            Assert.True(query.Batches[0].HasExecuted && !query.Batches[0].HasError && query.Batches[0].ResultSets.Count == 1, "Query should be executed and have one result set");

            string sqlCmdQueryFilaure = $@"
:Connect SomeWrongName
select * from sys.databases where name = 'master'
GO";

            query = ExecuteTests.CreateAndExecuteQuery(sqlCmdQueryFilaure, connInfo, fileStreamFactory, IsSqlCmd: true);
            Assert.True(query.Batches.Length == 1, $"Expected: 1 parsed batch, actual : {query.Batches.Length}");
            Assert.True(query.Batches[0].HasError, "Query should have error");
        }
예제 #5
0
        public async Task QueryExecuteSingleNoOpBatch()
        {
            // Setup: Keep track of all the messages received
            List <ResultMessage> messages = new List <ResultMessage>();

            // If:
            // ... I create a query from a single batch that does nothing
            ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false, false);
            var            fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            Query          query             = new Query(Common.NoOpQuery, ci, new QueryExecutionSettings(), fileStreamFactory);

            BatchCallbackHelper(query,
                                b => { throw new Exception("Batch startup callback should not have been called."); },
                                b => { throw new Exception("Batch completion callback was called"); },
                                m => messages.Add(m));

            // If:
            // ... I Then execute the query
            query.Execute();
            await query.ExecutionTask;

            // Then:
            // ... There should be no batches
            Assert.Equal(1, query.Batches.Length);

            // ... The query shouldn't have completed successfully
            Assert.False(query.HasExecuted);

            // ... The message callback should have been called 0 times
            Assert.Equal(0, messages.Count);
        }
예제 #6
0
        public void DatabaseChangesWhenCallingUseDatabase()
        {
            const string master   = "master";
            const string tempdb   = "tempdb";
            const string useQuery = "USE {0}";

            // Given a connection to a live database
            var            result   = LiveConnectionHelper.InitLiveConnectionInfo();
            ConnectionInfo connInfo = result.ConnectionInfo;
            DbConnection   connection;

            connInfo.TryGetConnection(ConnectionType.Default, out connection);

            var fileStreamFactory = MemoryFileSystem.GetFileStreamFactory(new Dictionary <string, byte[]>());

            // If I use master, the current database should be master
            CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);
            Assert.Equal(master, connection.Database);

            // If I use tempdb, the current database should be tempdb
            CreateAndExecuteQuery(string.Format(useQuery, tempdb), connInfo, fileStreamFactory);
            Assert.Equal(tempdb, connection.Database);

            // If I switch back to master, the current database should be master
            CreateAndExecuteQuery(string.Format(useQuery, master), connInfo, fileStreamFactory);
            Assert.Equal(master, connection.Database);
        }
예제 #7
0
        [InlineData(1, 20)]    // Asking for too many rows at a non-zero start
        public async Task GetSubsetSuccess(int startRow, int rowCount)
        {
            // If:
            // ... I create a new result set with a valid db data reader
            // ... And execute the result set
            DbDataReader mockReader        = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
            var          fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            ResultSet    resultSet         = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory);
            await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);

            // ... And attempt to get a subset with valid number of rows
            ResultSetSubset subset = await resultSet.GetSubset(startRow, rowCount);

            // Then:
            // ... rows sub-array and RowCount field of the subset should match
            Assert.Equal(subset.RowCount, subset.Rows.Length);

            // Then:
            // ... There should be rows in the subset, either the number of rows or the number of
            //     rows requested or the number of rows in the result set, whichever is lower
            long availableRowsFromStart = resultSet.RowCount - startRow;

            Assert.Equal(Math.Min(availableRowsFromStart, rowCount), subset.RowCount);

            // ... The rows should have the same number of columns as the resultset
            Assert.Equal(resultSet.Columns.Length, subset.Rows[0].Length);
        }
예제 #8
0
        public async Task SaveAsWithoutRowSelection()
        {
            // Setup:
            // ... Create a mock reader/writer for reading the result
            IFileStreamFactory resultFactory = MemoryFileSystem.GetFileStreamFactory();

            // ... Create a result set with dummy data and read to the end
            ResultSet rs = new ResultSet(
                Common.Ordinal, Common.Ordinal,
                resultFactory);
            await rs.ReadResultToEnd(GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery), CancellationToken.None);

            // ... Create a mock writer for writing the save as file
            Mock <IFileStreamWriter> saveWriter  = GetMockWriter();
            IFileStreamFactory       saveFactory = GetMockFactory(saveWriter.Object, resultFactory.GetReader);

            // If: I attempt to save results and await completion
            rs.SaveAs(new SaveResultsRequestParams {
                FilePath = Constants.OwnerUri
            }, saveFactory, null, null);
            Assert.True(rs.SaveTasks.ContainsKey(Constants.OwnerUri));
            await rs.SaveTasks[Constants.OwnerUri];

            // Then:
            // ... The task should have completed successfully
            Assert.Equal(TaskStatus.RanToCompletion, rs.SaveTasks[Constants.OwnerUri].Status);

            // ... All the rows should have been written successfully
            saveWriter.Verify(
                w => w.WriteRow(It.IsAny <IList <DbCellValue> >(), It.IsAny <IList <DbColumnWrapper> >()),
                Times.Exactly(Common.StandardRows));
        }
예제 #9
0
        public async Task BatchExecuteOneResultSet()
        {
            // Setup:
            // ... Keep track of callbacks being called
            int batchStartCalls           = 0;
            int batchEndCalls             = 0;
            int resultSetCalls            = 0;
            List <ResultMessage> messages = new List <ResultMessage>();

            // ... Build a data set to return
            const int      resultSets = 1;
            ConnectionInfo ci         = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false, false);

            // If I execute a query that should get one result set
            var   fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            Batch batch             = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);

            BatchCallbackHelper(batch,
                                b => batchStartCalls++,
                                b => batchEndCalls++,
                                m => messages.Add(m),
                                r => resultSetCalls++);
            await batch.Execute(GetConnection(ci), CancellationToken.None);

            // Then:
            // ... Callbacks should have been called the appropriate number of times
            Assert.Equal(1, batchStartCalls);
            Assert.Equal(1, batchEndCalls);
            Assert.Equal(1, resultSetCalls);

            // ... There should be exactly one result set
            ValidateBatch(batch, resultSets, false);
            ValidateBatchSummary(batch);
            ValidateMessages(batch, 1, messages);
        }
예제 #10
0
        public async Task BatchExecuteNoResultSets()
        {
            // Setup:
            // ... Keep track of callbacks being called
            int batchStartCalls           = 0;
            int batchEndCalls             = 0;
            int resultSetCalls            = 0;
            List <ResultMessage> messages = new List <ResultMessage>();

            // If I execute a query that should get no result sets
            var   fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            Batch batch             = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);

            BatchCallbackHelper(batch,
                                b => batchStartCalls++,
                                b => batchEndCalls++,
                                m => messages.Add(m),
                                r => resultSetCalls++);
            await batch.Execute(GetConnection(Common.CreateTestConnectionInfo(null, false, false)), CancellationToken.None);

            // Then:
            // ... Callbacks should have been called the appropriate number of times
            Assert.Equal(1, batchStartCalls);
            Assert.Equal(1, batchEndCalls);
            Assert.Equal(0, resultSetCalls);

            // ... The batch and the summary should be correctly assigned
            ValidateBatch(batch, 0, false);
            ValidateBatchSummary(batch);
            ValidateMessages(batch, 1, messages);
        }
예제 #11
0
        public async Task BatchExecuteExecuted()
        {
            // Setup: Build a data set to return
            const int      resultSets = 1;
            ConnectionInfo ci         = Common.CreateTestConnectionInfo(Common.GetTestDataSet(resultSets), false, false);

            // If I execute a batch
            var   fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            Batch batch             = new Batch(Constants.StandardQuery, Common.SubsectionDocument, Common.Ordinal, fileStreamFactory);
            await batch.Execute(GetConnection(ci), CancellationToken.None);

            // Then:
            // ... It should have executed without error
            Assert.True(batch.HasExecuted, "The batch should have been marked executed.");

            // If I execute it again
            // Then:
            // ... It should throw an invalid operation exception
            BatchCallbackHelper(batch,
                                b => { throw new Exception("Batch start callback should not have been called"); },
                                b => { throw new Exception("Batch completion callback should not have been called"); },
                                m => { throw new Exception("Message callback should not have been called"); },
                                null);
            await Assert.ThrowsAsync <InvalidOperationException>(
                () => batch.Execute(GetConnection(ci), CancellationToken.None));

            // ... The data should still be available without error
            ValidateBatch(batch, resultSets, false);
            ValidateBatchSummary(batch);
        }
예제 #12
0
        public async Task CancelQueryBeforeExecutionStartedTest()
        {
            // Setup query settings
            QueryExecutionSettings querySettings = new QueryExecutionSettings
            {
                ExecutionPlanOptions = new ExecutionPlanOptions
                {
                    IncludeActualExecutionPlanXml    = false,
                    IncludeEstimatedExecutionPlanXml = true
                }
            };

            // Create query with a failure callback function
            ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false, false);

            ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;
            Query query = new Query(Constants.StandardQuery, ci, querySettings, MemoryFileSystem.GetFileStreamFactory());

            string errorMessage = null;

            Query.QueryAsyncErrorEventHandler failureCallback = async(q, e) =>
            {
                errorMessage = "Error Occured";
            };
            query.QueryFailed += failureCallback;

            query.Cancel();
            query.Execute();
            await query.ExecutionTask;

            // Validate that query has not been executed but cancelled and query failed called function was called
            Assert.Equal(true, query.HasCancelled);
            Assert.Equal(false, query.HasExecuted);
            Assert.Equal("Error Occured", errorMessage);
        }
예제 #13
0
        public async Task UpdateRowSuccess()
        {
            // Setup:
            // ... Create a standard result set with standard data
            var       fileFactory = MemoryFileSystem.GetFileStreamFactory();
            var       mockReader  = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
            ResultSet resultSet   = new ResultSet(Common.Ordinal, Common.Ordinal, fileFactory);
            await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);

            // ... Create a mock reader that has one row
            object[] row = Enumerable.Range(0, Common.StandardColumns).Select(i => "QQQ").ToArray();
            IEnumerable <object[]> rows = new List <object[]> {
                row
            };

            TestResultSet[] results      = { new TestResultSet(TestResultSet.GetStandardColumns(Common.StandardColumns), rows) };
            var             newRowReader = GetReader(results, false, Constants.StandardQuery);

            // If: I add a new row to the result set
            await resultSet.UpdateRow(0, newRowReader);

            // Then:
            // ... There should be the same number of rows
            Assert.Equal(Common.StandardRows, resultSet.RowCount);

            // ... The new row should be readable and all cells contain the test value
            Assert.All(resultSet.GetRow(0), cell => Assert.Equal("QQQ", cell.RawObject));
        }
예제 #14
0
        public static Batch GetExecutedBatchWithExecutionPlan()
        {
            Batch batch = new Batch(Constants.StandardQuery, SubsectionDocument, 1,
                                    MemoryFileSystem.GetFileStreamFactory());

            batch.Execute(CreateTestConnection(ExecutionPlanTestDataSet, false, false), CancellationToken.None).Wait();
            return(batch);
        }
예제 #15
0
 public async Task ReadToEndNullReader()
 {
     // If: I create a new result set with a null db data reader
     // Then: I should get an exception
     var       fsf       = MemoryFileSystem.GetFileStreamFactory();
     ResultSet resultSet = new ResultSet(Common.Ordinal, Common.Ordinal, fsf);
     await Assert.ThrowsAsync <ArgumentNullException>(() => resultSet.ReadResultToEnd(null, CancellationToken.None));
 }
예제 #16
0
 public async Task ResultSetNotReadTest()
 {
     // If:
     // ... I have a resultset that hasn't been executed and I request a valid result set from it
     // Then:
     // ... It should throw an exception for having not been read
     ResultSet rs = new ResultSet(Common.Ordinal, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());
     await Assert.ThrowsAsync <InvalidOperationException>(() => rs.GetSubset(0, 1));
 }
        private static async Task <ResultSet> GetResultSet(DbColumn[] columns, object[] row)
        {
            object[][] rows          = { row };
            var        testResultSet = new TestResultSet(columns, rows);
            var        testReader    = new TestDbDataReader(new [] { testResultSet });
            var        resultSet     = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory());
            await resultSet.ReadResultToEnd(testReader, CancellationToken.None);

            return(resultSet);
        }
예제 #18
0
        public async Task RowInvalidParameter(Action <ResultSet> actionToPerform)
        {
            // If: I create a new result set and execute it
            var       mockReader        = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
            var       fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            ResultSet resultSet         = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory);
            await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);

            // Then: Attempting to read an invalid row should fail
            Assert.ThrowsAny <Exception>(() => actionToPerform(resultSet));
        }
예제 #19
0
        public static async Task <ResultSet> GetResultSet(DbColumn[] columns, bool includeIdentity, int rowCount = 1)
        {
            IEnumerable <object[]> rows = includeIdentity
                ? Enumerable.Repeat(new object[] { "id", "1", "2", "3" }, rowCount)
                : Enumerable.Repeat(new object[] { "1", "2", "3" }, rowCount);
            var testResultSet = new TestResultSet(columns, rows);
            var reader        = new TestDbDataReader(new[] { testResultSet });
            var resultSet     = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory());
            await resultSet.ReadResultToEnd(reader, CancellationToken.None);

            return(resultSet);
        }
예제 #20
0
        public void CallMethodWithoutReading(Action <ResultSet> testMethod)
        {
            // Setup: Create a new result set with valid db data reader
            var       fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            ResultSet resultSet         = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory);

            // If:
            // ... I have a result set that has not been read
            // ... and I attempt to call a method on it
            // Then: It should throw an exception
            Assert.ThrowsAny <Exception>(() => testMethod(resultSet));
        }
예제 #21
0
        public void SaveAsNullFactory()
        {
            // If: I attempt to save with a null set of params
            // Then: I should get a null argument exception
            ResultSet rs = new ResultSet(
                Common.Ordinal, Common.Ordinal,
                MemoryFileSystem.GetFileStreamFactory());

            Assert.Throws <ArgumentNullException>(() => rs.SaveAs(
                                                      new SaveResultsRequestParams(),
                                                      null, null, null));
        }
예제 #22
0
        public void TestBatchExecutionTime()
        {
            var            result              = LiveConnectionHelper.InitLiveConnectionInfo();
            ConnectionInfo connInfo            = result.ConnectionInfo;
            var            fileStreamFactory   = MemoryFileSystem.GetFileStreamFactory();
            Query          query               = CreateAndExecuteQuery("select * from sys.databases", connInfo, fileStreamFactory);
            DateTime       elapsedTime         = Convert.ToDateTime(query.Batches[0].ExecutionElapsedTime);
            Query          mutipleQuery        = CreateAndExecuteQuery("select * from sys.databases\r\nGO 15", connInfo, fileStreamFactory);
            DateTime       multipleElapsedTime = Convert.ToDateTime(mutipleQuery.Batches[0].ExecutionElapsedTime);

            Assert.True(multipleElapsedTime > elapsedTime);
        }
예제 #23
0
        public void SaveAsFailedIncomplete()
        {
            // If: I attempt to save a result set that hasn't completed execution
            // Then: I should get an invalid operation exception
            ResultSet rs = new ResultSet(
                Common.Ordinal, Common.Ordinal,
                MemoryFileSystem.GetFileStreamFactory());

            Assert.Throws <InvalidOperationException>(() => rs.SaveAs(
                                                          new SaveResultsRequestParams(),
                                                          MemoryFileSystem.GetFileStreamFactory(),
                                                          null, null));
        }
예제 #24
0
        public void QueryCreationCorrect()
        {
            // If:
            // ... I create a query
            ConnectionInfo ci = Common.CreateTestConnectionInfo(null, false, false);
            var            fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            Query          query             = new Query(Constants.StandardQuery, ci, new QueryExecutionSettings(), fileStreamFactory);

            // Then:
            // ... I should get back two batches to execute that haven't been executed
            Assert.NotEmpty(query.QueryText);
            Assert.False(query.HasExecuted);
            Assert.Throws <InvalidOperationException>(() => query.BatchSummaries);
        }
예제 #25
0
        [InlineData(0, -1)] // Negative row count
        public async Task GetSubsetInvalidParameters(int startRow, int rowCount)
        {
            // If:
            // ... I create a new result set with a valid db data reader
            // ... And execute the result
            DbDataReader mockReader        = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
            var          fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            ResultSet    resultSet         = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory);
            await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);

            // ... And attempt to get a subset with invalid parameters
            // Then:
            // ... It should throw an exception for an invalid parameter
            await Assert.ThrowsAsync <ArgumentOutOfRangeException>(() => resultSet.GetSubset(startRow, rowCount));
        }
예제 #26
0
        public static Query GetBasicExecutedQuery(QueryExecutionSettings querySettings)
        {
            ConnectionInfo ci = CreateConnectedConnectionInfo(StandardTestDataSet, false, false);

            // Query won't be able to request a new query DbConnection unless the ConnectionService has a
            // ConnectionInfo with the same URI as the query, so we will manually set it
            ConnectionService.Instance.OwnerToConnectionMap[ci.OwnerUri] = ci;

            Query query = new Query(Constants.StandardQuery, ci, querySettings,
                                    MemoryFileSystem.GetFileStreamFactory());

            query.Execute();
            query.ExecutionTask.Wait();
            return(query);
        }
예제 #27
0
        public void SetCellHasCorrections()
        {
            // Setup:
            // ... Generate a result set with a single binary column
            DbColumn[] cols =
            {
                new TestDbColumn
                {
                    DataType     = typeof(byte[]),
                    DataTypeName = "binary"
                }
            };
            object[][] rows          = { new object[] { new byte[] { 0x00 } } };
            var        testResultSet = new TestResultSet(cols, rows);
            var        testReader    = new TestDbDataReader(new[] { testResultSet });
            var        rs            = new ResultSet(0, 0, MemoryFileSystem.GetFileStreamFactory());

            rs.ReadResultToEnd(testReader, CancellationToken.None).Wait();

            // ... Generate the metadata
            var etm = Common.GetStandardMetadata(cols);

            // ... Create the row update
            RowUpdate ru = new RowUpdate(0, rs, etm);

            // If: I set a cell in the newly created row to something that will be corrected
            EditUpdateCellResult eucr = ru.SetCell(0, "1000");

            // Then:
            // ... A edit cell was returned
            Assert.NotNull(eucr);
            Assert.NotNull(eucr.Cell);

            // ... The value we used won't be returned
            Assert.NotEmpty(eucr.Cell.DisplayValue);
            Assert.NotEqual("1000", eucr.Cell.DisplayValue);
            Assert.False(eucr.Cell.IsNull);

            // ... The cell should be dirty
            Assert.True(eucr.Cell.IsDirty);

            // ... The row is still dirty
            Assert.True(eucr.IsRowDirty);

            // ... There should be a cell update in the cell list
            Assert.Contains(0, ru.cellUpdates.Keys);
            Assert.NotNull(ru.cellUpdates[0]);
        }
예제 #28
0
        public async Task RemoveRowSuccess()
        {
            // Setup: Create a result set that has the standard data set on it
            var       fileFactory = MemoryFileSystem.GetFileStreamFactory();
            var       mockReader  = GetReader(Common.StandardTestDataSet, false, Constants.StandardQuery);
            ResultSet resultSet   = new ResultSet(Common.Ordinal, Common.Ordinal, fileFactory);
            await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);

            // If: I delete a row from the result set
            resultSet.RemoveRow(0);

            // Then:
            // ... The row count should decrease
            // ... The last row should have moved up by 1
            Assert.Equal(Common.StandardRows - 1, resultSet.RowCount);
            Assert.Throws <ArgumentOutOfRangeException>(() => resultSet.GetRow(Common.StandardRows - 1));
        }
예제 #29
0
        public async Task ReadToEndForXmlJson(string forType)
        {
            // Setup:
            // ... Build a FOR XML or FOR JSON data set
            DbColumn[]      columns  = { new TestDbColumn(string.Format("{0}_F52E2B61-18A1-11d1-B105-00805F49916B", forType)) };
            object[][]      rows     = Enumerable.Repeat(new object[] { "test data" }, Common.StandardRows).ToArray();
            TestResultSet[] dataSets = { new TestResultSet(columns, rows) };

            // ... Create a callback for resultset completion
            ResultSetSummary resultSummary = null;

            ResultSet.ResultSetAsyncEventHandler callback = r =>
            {
                resultSummary = r.Summary;
                return(Task.FromResult(0));
            };

            // If:
            // ... I create a new resultset with a valid db data reader that is FOR XML/JSON
            // ... and I read it to the end
            DbDataReader mockReader        = GetReader(dataSets, false, Constants.StandardQuery);
            var          fileStreamFactory = MemoryFileSystem.GetFileStreamFactory();
            ResultSet    resultSet         = new ResultSet(Common.Ordinal, Common.Ordinal, fileStreamFactory);

            resultSet.ResultCompletion += callback;
            await resultSet.ReadResultToEnd(mockReader, CancellationToken.None);

            // Then:
            // ... There should only be one column
            // ... There should only be one row
            // ... The result should be marked as complete
            Assert.Equal(1, resultSet.Columns.Length);
            Assert.Equal(1, resultSet.RowCount);

            // ... The callback should have been called
            Assert.NotNull(resultSummary);

            // If:
            // ... I attempt to read back the results
            // Then:
            // ... I should only get one row
            var subset = await resultSet.GetSubset(0, 10);

            Assert.Equal(1, subset.RowCount);
        }
예제 #30
0
        public void ResultCreation()
        {
            // If:
            // ... I create a new result set with a valid db data reader
            ResultSet resultSet = new ResultSet(Common.Ordinal, Common.Ordinal, MemoryFileSystem.GetFileStreamFactory());

            // Then:
            // ... There should not be any data read yet
            Assert.Null(resultSet.Columns);
            Assert.Equal(0, resultSet.RowCount);
            Assert.Equal(Common.Ordinal, resultSet.Id);

            // ... The summary should include the same info
            Assert.Null(resultSet.Summary.ColumnInfo);
            Assert.Equal(0, resultSet.Summary.RowCount);
            Assert.Equal(Common.Ordinal, resultSet.Summary.Id);
            Assert.Equal(Common.Ordinal, resultSet.Summary.BatchId);
        }