コード例 #1
0
 public ExecuteStoredProcedureDesigner(IFunctionData data, IDesignerContext context) : base(data, context)
 {
     foreach (var nextResultSet in ResultSets.Where(r => r.CustomType != null))
     {
         nextResultSet.CustomType = context.CustomTypes.FirstOrDefault(t => t.Id == nextResultSet.CustomType.Id);
     }
 }
コード例 #2
0
        public ResultSets ReadArrayElements(NestedLoop args)
        {
            int    tests = 500;
            var    timer = new Stopwatch();
            Random rand  = new Random();

            // Initialize arrays
            loops    = args.Loop1;
            subLoops = args.Loop2;

            array = new int[subLoops];
            for (int i = 0; i < subLoops; i++)
            {
                array[i] = (int)(rand.NextDouble() * 2);
            }

            randIndexes = new int[loops];
            for (int i = 0; i < loops; i++)
            {
                randIndexes[i] = (int)(rand.NextDouble() * loops);
            }

            long baseTotal       = 0;
            long baseRandomTotal = 0;
            long randomTotal     = 0;
            long orderedTotal    = 0;

            for (int a = 0; a < tests; a++)
            {
                timer.Restart();
                BaseIncrement(loops, subLoops);
                baseTotal += timer.StopNanos();

                timer.Restart();
                BaseRandom(loops, subLoops);
                baseRandomTotal += timer.StopNanos();

                timer.Restart();
                ArrayOrdered(loops, subLoops);
                orderedTotal += timer.StopNanos();

                timer.Restart();
                ArrayRandom(loops, subLoops);
                randomTotal += timer.StopNanos();
            }

            return(ResultSets.builder("Array lookups by type")
                   .StartGroup((string)null)
                   .AddStepResult(StepDescriptor.Of("base (loop>loop>var++)", tests, loops, subLoops), baseTotal)
                   .AddStepResult(StepDescriptor.Of("base random (loop>array[i]>loop>var++)", tests, loops, subLoops), baseRandomTotal)
                   .AddStepResult(StepDescriptor.Of("random (loop>array[i]>loop>array[i])", tests, loops, subLoops), randomTotal)
                   .AddStepResult(StepDescriptor.Of("ordered (loop>loop>array[i])", tests, loops, subLoops), orderedTotal)
                   .EndGroup()
                   .Build());
        }
コード例 #3
0
ファイル: Assessment.cs プロジェクト: wondeltd/dotnet-client
        /// <summary>
        /// Internal Constructor so object can only be retrieved through Wonde.Endpoints.Schools object
        /// </summary>
        /// <param name="token">Api Token</param>
        /// <param name="id">Assessment id to set</param>
        internal Assessment(string token, string id = "") : base(token, "")
        {
            _token = token;

            if (id.Trim().Length > 0)
            {
                Uri = Uri + id;
            }

            templates  = new Templates(token, Uri);
            aspects    = new Aspects(token, Uri);
            marksheets = new MarkSheets(token, Uri);
            results    = new Results(token, Uri);
            resultsets = new ResultSets(token, Uri);
        }
コード例 #4
0
 protected override void ApplyAction(TestResultDto editObject)
 {
     editObject.SampleResultSets.Clear();
     if (string.IsNullOrEmpty(HeaderRow.Value1) && string.IsNullOrEmpty(HeaderRow.Value2) &&
         string.IsNullOrEmpty(HeaderRow.Value3) && string.IsNullOrEmpty(HeaderRow.Value4) &&
         string.IsNullOrEmpty(HeaderRow.Value5) && string.IsNullOrEmpty(HeaderRow.Value6) &&
         string.IsNullOrEmpty(HeaderRow.Value7) && string.IsNullOrEmpty(HeaderRow.Value8) &&
         string.IsNullOrEmpty(HeaderRow.Value9) && string.IsNullOrEmpty(HeaderRow.Value10) &&
         string.IsNullOrEmpty(HeaderRow.Title))
     {
         return;
     }
     editObject.SampleResultSets.Add(HeaderRow);
     ResultSets.DoForEach(dto => editObject.SampleResultSets.Add(dto));
 }
コード例 #5
0
 private void OnExecute(Document document)
 {
     ResultSets.Clear();
     try
     {
         IEnumerable <DataTable> results;
         if (string.IsNullOrEmpty(ActiveDocumentSelectedText))
         {
             results = _sqliteService.ExecuteQuery(_activeDocument.Text, _activeDocument.DatabasePath);
         }
         else
         {
             results = _sqliteService.ExecuteQuery(ActiveDocumentSelectedText, _activeDocument.DatabasePath);
         }
         foreach (DataTable table in results)
         {
             ResultSets.Add(table);
         }
     }
     catch (Exception ex)
     {
         WpfMessageBox.ShowDialog("Execution Error", ex.Message, MessageBoxButton.OK, MessageIcon.Error);
     }
 }
コード例 #6
0
        /// <summary>
        /// Call a stored procedure and get the results back.
        /// </summary>
        /// <param name="instance">Database Context to use for the call.</param>
        /// <param name="storedProcedureName">The name of the stored procedure to execute.</param>
        /// <param name="token">Cancellation token (optional).</param>
        /// <param name="inputParameters">An instance of an <see cref="Object"/> containing data to be sent to the stored procedure (INPUT and OUTPUT parameters).</param>
        /// <param name="commandTimeout">The wait time before terminating the attempt to execute a command and generating an error.</param>
        /// <param name="returnedTypes">The data types of resultsets returned by the stored procedure. Order is important.</param>
        /// <returns>A list of lists containing result data from the stored procedure.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="instance"/> is NULL or <paramref name="storedProcedureName"/> is NULL.</exception>
        /// <exception cref="ArgumentException"><paramref name="storedProcedureName"/> is empty or whitespace.</exception>
        /// <exception cref="Exception">An <see cref="Exception"/> occured while reading the result from the stored procedure.</exception>
        internal static async Task <ResultSets> ReadFromStoredProcedureAsync(this DbContext instance, string storedProcedureName, CancellationToken token, IEnumerable <SqlParameter> inputParameters = null, int?commandTimeout = null, params Type[] returnedTypes)
        {
            if (instance == null)
            {
                throw new ArgumentNullException(nameof(instance));
            }
            if (storedProcedureName == null)
            {
                throw new ArgumentNullException(nameof(storedProcedureName));
            }
            if (String.IsNullOrWhiteSpace(storedProcedureName))
            {
                throw new ArgumentException(nameof(storedProcedureName));
            }

            var isConnectionOpen = false;
            var results          = new ResultSets();
            var currentType      = (returnedTypes == null) ? new Type[0].GetEnumerator() : returnedTypes.GetEnumerator();
            var connection       = (SqlConnection)instance.Database.GetDbConnection();

            try
            {
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                    isConnectionOpen = true;
                }

                using (var sqlCommand = connection.CreateCommand())
                {
                    sqlCommand.CommandText    = storedProcedureName;
                    sqlCommand.CommandType    = CommandType.StoredProcedure;
                    sqlCommand.CommandTimeout = commandTimeout ?? sqlCommand.CommandTimeout;

                    //	Add input parameters
                    if (inputParameters != null)
                    {
                        foreach (var inputParameter in inputParameters)
                        {
                            sqlCommand.Parameters.Add(inputParameter);
                        }
                    }

                    //	Execute the stored procedure
                    var sqlDataReader = await sqlCommand.ExecuteReaderAsync(CommandBehavior.SequentialAccess, token);

                    //	Get the type we're expecting for the first result. If no types specified, ignore all results.
                    if (currentType.MoveNext())
                    {
                        #region Process results

                        //	Repeat this loop for each result set returned by the stored procedure for which we have a result type specified.
                        do
                        {
                            var mappedProperties = ((Type)currentType.Current).GetMappedProperties().ToList();                                  //	Get properties to save for the current destination type.
                            var currentResult    = new List <object>();                                                                         //	Create a destination for our results.

                            while (sqlDataReader.Read())
                            {
                                //	Create an object to hold this result.
                                var constructorInfo = ((Type)currentType.Current).GetConstructor(Type.EmptyTypes);
                                if (constructorInfo != null)
                                {
                                    var item = constructorInfo.Invoke(new object[0]);

                                    sqlDataReader.ReadRecord(item, mappedProperties.ToArray());                                                 //	Copy data elements by parameter name from result to destination object.
                                    currentResult.Add(item);                                                                                    //	Add newly populated item to our output list.
                                }
                            }

                            //	Add this result set to our return list.
                            results.Add(currentResult);
                        }while (sqlDataReader.NextResult() && currentType.MoveNext());

                        #endregion
                    }

                    //	If we opened the reader, then close up the reader, we're done saving results.
                    if (isConnectionOpen)
                    {
                        sqlDataReader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(String.Format("Error reading from stored procedure {0}: {1}", storedProcedureName, ex.Message), ex);
            }
            finally
            {
                connection.Close();
            }

            return(results);
        }
コード例 #7
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            (_xmlSettings as IXmlSerializable).ReadXml(reader);
            int depth1 = reader.Depth + 1;

            if (reader.ReadToFirstChildElement())
            {
                while (reader.Depth >= depth1)
                {
                    if (reader.NodeType == XmlNodeType.Element && reader.Depth == depth1)
                    {
                        switch (reader.Name)
                        {
                        case "ResultSets":
                            if (ResultSets == null)
                            {
                                ResultSets = new List <IList <BindableDynamicObject> >();
                            }
                            else if (ResultSets.Count > 0)
                            {
                                ResultSets.Clear();
                            }

                            int depthResultSet = reader.Depth + 1;

                            if (reader.ReadToFirstChildElement())
                            {
                                while (reader.Depth >= depthResultSet)
                                {
                                    if (reader.NodeType == XmlNodeType.Element && reader.Depth == depthResultSet && reader.Name == "ResultSet")
                                    {
                                        List <BindableDynamicObject> resultSet = new List <BindableDynamicObject>();
                                        int depthRecord = reader.Depth + 1;

                                        if (reader.ReadToFirstChildElement())
                                        {
                                            while (reader.Depth >= depthRecord)
                                            {
                                                if (reader.NodeType == XmlNodeType.Element && reader.Depth == depthRecord && reader.Name == "Record")
                                                {
                                                    resultSet.Add(reader.ReadDynamicObject(_xmlSettings));
                                                }
                                                else
                                                {
                                                    reader.Read();
                                                }
                                            }
                                        }
                                        ResultSets.Add(resultSet);
                                    }
                                    else
                                    {
                                        reader.Read();
                                    }
                                }
                            }
                            break;

                        case "OutputParameters":
                            OutputParameters = reader.ReadDynamicObject(_xmlSettings);
                            break;

                        case "ReturnValue":
                            ReturnValue = reader.ReadValue(_xmlSettings);
                            break;

                        default:
                            reader.Read();
                            break;
                        }
                    }
                    else
                    {
                        reader.Read();
                    }
                }
            }
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: TeamworkGuy2/CsBenchmark
 private static void Print(ResultSets res)
 {
     Console.WriteLine(res.ToString(TimeUnit.MILLI));
 }
コード例 #9
0
        public override void Assert(DbConnection validationConnection, SqlExecutionResult[] results)
        {
            base.Assert(validationConnection, results);

            var result        = results[0];
            var resultSetList = new List <int>();

            try
            {
                if (ResultSets.ToUpper() == "ALL")
                {
                    resultSetList.AddRange(Enumerable.Range(1, result.DataSet.Tables.Count));
                }
                else if (ResultSets.Contains(","))
                {
                    resultSetList.AddRange(ResultSets.Split(',').Select(rs => Convert.ToInt16(rs)).Select(dummy => (int)dummy));
                }
                else if (ResultSets.Contains(":"))
                {
                    var temp = ResultSets.Split(':');
                    resultSetList.AddRange(Enumerable.Range(Convert.ToInt32(temp[0]), Convert.ToInt32(temp[1])));
                }
                else
                {
                    throw new ArgumentException("Invalid specification for result sets");
                }
            }
            catch
            {
                throw new ArgumentException(String.Format("{0} is an invalid result set specification.", ResultSets));
            }

            foreach (var rs in resultSetList.Where(rs => rs > result.DataSet.Tables.Count))
            {
                throw new ArgumentException(String.Format("Result Set {0} does not exist", rs));
            }

            var currentResultSetId = resultSetList[0];
            var table        = result.DataSet.Tables[currentResultSetId - 1];
            var numberOfRows = table.Rows.Count;

            resultSetList.RemoveAt(0);

            //loop through batches verifying that the column count for each batch is the same
            foreach (var rs in resultSetList)
            {
                //verify resultset exists
                if (result.DataSet.Tables.Count < rs)
                {
                    throw new Exception(String.Format("Result Set {0} does not exist", rs));
                }

                //actual condition verification
                //verify resultset row count matches expected
                table = result.DataSet.Tables[rs - 1];

                if (table.Rows.Count != numberOfRows)
                {
                    throw new Exception
                          (
                              String.Format
                              (
                                  "Result Set {0}: {1} rows does not match the {2} rows in Result Set {3}",
                                  rs,
                                  table.Rows.Count,
                                  numberOfRows,
                                  currentResultSetId
                              )
                          );
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// Saves pending changes
        /// </summary>
        /// <param name="acceptOption">Defines when changes should be accepted locally</param>
        /// <param name="clearErrors">If set to true, all error entries are cleared before saving chnages</param>
        /// <param name="failOnValidationErrors">If set to true, exception is thrown if IsValid=false, otherwise invalid entities are skipped from saving silently</param>
        /// <param name="clientInfo">Optional client info object, to be submitted to the server</param>
        public override void SaveChanges(AcceptOption acceptOption = AcceptOption.Default, bool clearErrors = true, bool failOnValidationErrors = true, ClientInfo clientInfo = null)
        {
            if (acceptOption == AcceptOption.Default)
            {
                acceptOption = System.Transactions.Transaction.Current != null ? AcceptOption.AcceptChangesOnTransactionCompleted : AcceptOption.AcceptChangesAfterSave;
            }

            if (clearErrors)
            {
                ClearErrors();
            }

            if (failOnValidationErrors && !IsValid)
            {
                throw new ValidationException("Validation failed for one or more entities.");
            }

            // submit data
            TResultSet resultSet;

            try
            {
                resultSet = SubmitChanges(clientInfo ?? ClientInfo);
            }
            catch (FaultException ex)
            {
                var faultExceptionType = ex.GetType();
                if (faultExceptionType.IsGenericType)
                {
                    var detailType     = faultExceptionType.GetGenericArguments()[0];
                    var detailProperty = typeof(FaultException <>).MakeGenericType(detailType).GetProperty("Detail");
                    var detail         = detailProperty.GetValue(ex, null);
                    if (detail is OptimisticConcurrencyFault)
                    {
                        var stateEntries = GetStateEntries(((OptimisticConcurrencyFault)detail).Entities);
                        throw new OptimisticConcurrencyException(null, stateEntries);
                    }
                    if (detail is UpdateFault)
                    {
                        var stateEntries = GetStateEntries(((UpdateFault)detail).Entities);
                        throw new UpdateException(null, stateEntries);
                    }
                }
                throw;
            }

            // accept changes
            switch (acceptOption)
            {
            case AcceptOption.AcceptChangesAfterSave:
            {
                // refresh local data
                var hasValidationErrors = IsServerValidationExceptionSuppressed ? false : resultSet.Any(entity => entity.Errors.Any(e => e.IsError));
                Refresh(resultSet);
                if (hasValidationErrors)
                {
                    throw new ServerValidationException();
                }
                AcceptChanges(true);
            }
            break;

            case AcceptOption.None:
            {
                // store result in private list
                // allowes user to apply result (accept changes) asynchronousely
                ResultSets.Add(resultSet);

                // remove result from private list in case of a transaction rollback
                var transaction = System.Transactions.Transaction.Current;
                if (transaction != null)
                {
                    transaction.TransactionCompleted += (sender, e) =>
                    {
                        if (e.Transaction.TransactionInformation.Status != TransactionStatus.Committed)
                        {
                            ResultSets.Remove(resultSet);
                        }
                    };
                }
            }
            break;

            case AcceptOption.AcceptChangesOnTransactionCompleted:
            {
                var transaction = System.Transactions.Transaction.Current;
                if (transaction == null)
                {
                    throw new Exception(string.Format("{0}.{1} requires an active transaction scope.", acceptOption.GetType().Name, acceptOption));
                }

                // accept changes upon successfull completion of transaction
                transaction.TransactionCompleted += (sender, e) =>
                {
                    if (e.Transaction.TransactionInformation.Status == TransactionStatus.Committed)
                    {
                        // refresh local data
                        var hasValidationErrors = IsServerValidationExceptionSuppressed ? false : resultSet.Any(entity => entity.Errors.Any(error => error.IsError));
                        Refresh(resultSet);
                        if (hasValidationErrors)
                        {
                            throw new ServerValidationException();
                        }
                    }
                };
            }
            break;

            default:
                throw new Exception(string.Format("This {0} is not implemented: {1}", acceptOption.GetType().Name, acceptOption));
            }

            //if (resultSet.HasConcurrencyConflicts)
            //{
            //    HandleConcurrencyConflicts(resultSet);
            //}
        }
コード例 #11
0
        public string GenerateScript(ScriptingOptions so)
        {
            StringBuilder sql = new StringBuilder();

            int resultSetCount = 0;

            if (so.PartitionFunctions)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.PartitionFunctions.sql"));
                sql.AppendLine();
                ResultSets.Add("PartitionFunctionCollection", resultSetCount++);
                ResultSets.Add("PartitionFunctionRangeValuesCollection", resultSetCount++);
            }
            if (so.Tables)
            {
                sql.Append("SELECT COUNT(*) FROM sys.tables;");
                sql.AppendLine();
                ResultSets.Add("TableCount", resultSetCount++);
                sql.Append(GetResourceScript("ObjectHelper.SQL.Tables_" + so.ServerMajorVersion.ToString() + ".sql"));
                sql.AppendLine();
                ResultSets.Add("TableCollection", resultSetCount++);

                if (so.DataCompression)
                {
                    if (so.ServerMajorVersion >= 10)
                    {
                        sql.Append(GetResourceScript("ObjectHelper.SQL.TableDataCompression_" + so.ServerMajorVersion.ToString() + ".sql"));
                        sql.AppendLine();
                        ResultSets.Add("TableDataCompressionCollection", resultSetCount++);
                    }
                    else
                    {
                        so.DataCompression = false;
                    }
                }
                if (so.DefaultConstraints)
                {
                    sql.Append(GetResourceScript("ObjectHelper.SQL.DefaultConstraints.sql"));
                    sql.AppendLine();
                    ResultSets.Add("DefaultConstraintCollection", resultSetCount++);
                }
                if (so.CheckConstraints)
                {
                    sql.Append(GetResourceScript("ObjectHelper.SQL.CheckConstraints.sql"));
                    sql.AppendLine();
                    ResultSets.Add("CheckConstraintCollection", resultSetCount++);
                }
                if (so.ForeignKeys)
                {
                    sql.Append(GetResourceScript("ObjectHelper.SQL.ForeignKeys.sql"));
                    sql.AppendLine();
                    ResultSets.Add("ForeignKeyCollection", resultSetCount++);
                    ResultSets.Add("ForeignKeyColumnCollection", resultSetCount++);
                }
                if (so.FullTextIndexes)
                {
                    sql.Append(GetResourceScript("ObjectHelper.SQL.FullTextIndexes_" + so.ServerMajorVersion + ".sql"));
                    sql.AppendLine();
                    ResultSets.Add("FullTextIndexCollection", resultSetCount++);
                    ResultSets.Add("FullTextIndexColumnCollection", resultSetCount++);
                }
                sql.Append(GetResourceScript("ObjectHelper.SQL.Columns_" + so.ServerMajorVersion.ToString() + ".sql"));
                sql.AppendLine();
                ResultSets.Add("ColumnCollection", resultSetCount++);
            }
            if (so.Contracts)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Contracts.sql"));
                sql.AppendLine();
                ResultSets.Add("ContractCollection", resultSetCount++);
                ResultSets.Add("ContractMessageTypeCollection", resultSetCount++);
            }
            if (so.MessageTypes)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.MessageTypes.sql"));
                sql.AppendLine();
                ResultSets.Add("MessageTypeCollection", resultSetCount++);
            }
            if (so.XMLSchemaCollections)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.XMLSchemaCollections.sql"));
                sql.AppendLine();
                ResultSets.Add("XMLSchemaCollection", resultSetCount++);
            }
            if (so.UniqueConstraints || so.PrimaryKeys || so.ClusteredIndexes || so.NonClusteredIndexes)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Indexes_" + so.ServerMajorVersion + ".sql"));
                sql.AppendLine();
                ResultSets.Add("IndexCollection", resultSetCount++);
                sql.Append(GetResourceScript("ObjectHelper.SQL.IndexColumns.sql"));
                sql.AppendLine();
                ResultSets.Add("IndexColumnCollection", resultSetCount++);
            }
            if (so.DMLTriggers || so.DDLTriggers)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Triggers_" + so.ServerMajorVersion + ".sql"));
                sql.AppendLine();
                ResultSets.Add("TriggerCollection", resultSetCount++);
            }
            if (so.CLRTriggers)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.CLRTriggers_" + so.ServerMajorVersion + ".sql"));
                sql.AppendLine();
                ResultSets.Add("CLRTriggerCollection", resultSetCount++);
                ResultSets.Add("CLRTriggerEventCollection", resultSetCount++);
            }
            if (so.StoredProcedures)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.StoredProcedures.sql"));
                sql.AppendLine();
                ResultSets.Add("SPCollection", resultSetCount++);
            }
            if (so.Aggregates || so.StoredProcedures || so.SQLUserDefinedFunctions || so.CLRUserDefinedFunctions)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Parameters_" + so.ServerMajorVersion + ".sql"));
                sql.AppendLine();
                ResultSets.Add("ParameterCollection", resultSetCount++);
            }
            if (so.Aggregates)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Aggregates.sql"));
                sql.AppendLine();
                ResultSets.Add("AggregateCollection", resultSetCount++);
            }
            if (so.Views)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Views.sql"));
                sql.AppendLine();
                ResultSets.Add("ViewCollection", resultSetCount++);
            }

            if (so.ApplicationRoles || so.DatabaseRoles || so.Users) //DOROBIT DALSIE
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Principals.sql"));
                sql.AppendLine();
                ResultSets.Add("PrincipalCollection", resultSetCount++);
            }

            if (so.Assemblies)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Assemblies_" + so.ServerMajorVersion.ToString() + ".sql"));
                sql.AppendLine();
                ResultSets.Add("AssemblyCollection", resultSetCount++);
            }

            if (so.Defaults)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Defaults.sql"));
                sql.AppendLine();
                ResultSets.Add("DefaultCollection", resultSetCount++);
            }

            if (so.Synonyms)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Synonyms.sql"));
                sql.AppendLine();
                ResultSets.Add("SynonymCollection", resultSetCount++);
            }

            if (so.ServiceQueues)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.ServiceQueues.sql"));
                sql.AppendLine();
                ResultSets.Add("QueueCollection", resultSetCount++);
            }
            if (so.FullTextCatalogs)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.FullTextCatalogs.sql"));
                sql.AppendLine();
                ResultSets.Add("FullTextCatalogCollection", resultSetCount++);
            }

            if (so.FullTextStopLists)
            {
                if (so.ServerMajorVersion >= 10)
                {
                    sql.Append(GetResourceScript("ObjectHelper.SQL.FullTextStopLists.sql"));
                    sql.AppendLine();
                    ResultSets.Add("FullTextStopListCollection", resultSetCount++);
                    ResultSets.Add("FullTextStopWordCollection", resultSetCount++);
                }
                else
                {
                    so.FullTextStopLists = false;
                }
            }
            if (so.Services)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Services.sql"));
                sql.AppendLine();
                ResultSets.Add("ServiceCollection", resultSetCount++);
                ResultSets.Add("ServiceContractCollection", resultSetCount++);
            }
            if (so.BrokerPriorities)
            {
                if (so.ServerMajorVersion >= 10)
                {
                    sql.Append(GetResourceScript("ObjectHelper.SQL.BrokerPriorities.sql"));
                    sql.AppendLine();
                    ResultSets.Add("BrokerPriorityCollection", resultSetCount++);
                }
                else
                {
                    so.BrokerPriorities = false;
                }
            }
            if (so.PartitionSchemes)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.PartitionSchemes.sql"));
                sql.AppendLine();
                ResultSets.Add("PartitionSchemeCollection", resultSetCount++);
                ResultSets.Add("PartitionSchemeFileGroupCollection", resultSetCount++);
            }
            if (so.RemoteServiceBindings)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.RemoteServiceBindings.sql"));
                sql.AppendLine();
                ResultSets.Add("RemoteServiceBindingCollection", resultSetCount++);
            }
            if (so.Rules)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Rules.sql"));
                sql.AppendLine();
                ResultSets.Add("RuleCollection", resultSetCount++);
            }
            if (so.Routes)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Routes.sql"));
                sql.AppendLine();
                ResultSets.Add("RouteCollection", resultSetCount++);
            }
            if (so.Schemas)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.Schemas.sql"));
                sql.AppendLine();
                ResultSets.Add("SchemaCollection", resultSetCount++);
            }
            if (so.SQLUserDefinedFunctions)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.SQLUserDefinedFunctions.sql"));
                sql.AppendLine();
                ResultSets.Add("UserDefinedFunctionCollection", resultSetCount++);
            }
            if (so.CLRUserDefinedFunctions)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.CLRUserDefinedFunctions_" + so.ServerMajorVersion + ".sql"));
                sql.AppendLine();
                ResultSets.Add("CLRUserDefinedFunctionCollection", resultSetCount++);
                ResultSets.Add("CLRUserDefinedFunctionColumnCollection", resultSetCount++);
            }
            if (so.UserDefinedDataTypes)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.UserDefinedDataTypes_" + so.ServerMajorVersion + ".sql"));
                sql.AppendLine();
                ResultSets.Add("UserDefinedDataTypeCollection", resultSetCount++);
            }
            if (so.UserDefinedTypes)
            {
                sql.Append(GetResourceScript("ObjectHelper.SQL.UserDefinedTypes.sql"));
                sql.AppendLine();
                ResultSets.Add("UserDefinedTypeCollection", resultSetCount++);
            }
            if (so.UserDefinedTableTypes)
            {
                if (so.ServerMajorVersion >= 10)
                {
                    sql.Append(GetResourceScript("ObjectHelper.SQL.UserDefinedTableTypes.sql"));
                    sql.AppendLine();
                    ResultSets.Add("UserDefinedTableTypeCollection", resultSetCount++);
                    ResultSets.Add("UserDefinedTableTypeColumnCollection", resultSetCount++);
                    ResultSets.Add("UserDefinedTableTypeIndexCollection", resultSetCount++);
                    ResultSets.Add("UserDefinedTableTypeIndexColumnCollection", resultSetCount++);
                    ResultSets.Add("UserDefinedTableTypeCheckConstraintCollection", resultSetCount++);
                }
                else
                {
                    so.UserDefinedTableTypes = false;
                }
            }

            return(sql.ToString());
        }
コード例 #12
0
        public override void Assert(DbConnection validationConnection, SqlExecutionResult[] results)
        {
            base.Assert(validationConnection, results);
            var result        = results[0];
            var resultSetList = new List <int>();

            try
            {
                if (ResultSets.ToUpper() == "ALL")
                {
                    resultSetList.AddRange(Enumerable.Range(1, result.DataSet.Tables.Count));
                }
                else if (ResultSets.Contains(","))
                {
                    resultSetList.AddRange(ResultSets.Split(',').Select(rs => Convert.ToInt16(rs)).Select(dummy => (int)dummy));
                }
                else if (ResultSets.Contains(":"))
                {
                    var temp = ResultSets.Split(':');
                    resultSetList.AddRange(Enumerable.Range(Convert.ToInt32(temp[0]), Convert.ToInt32(temp[1])));
                }
                else
                {
                    throw new ArgumentException("Invalid specification for result sets");
                }
            }
            catch
            {
                throw new ArgumentException(String.Format("{0} is an invalid result set specification.", ResultSets));
            }

            //validate ResultSetList does not include result sets that do not exist
            foreach (var rs in resultSetList.Where(rs => rs > result.DataSet.Tables.Count))
            {
                throw new ArgumentException(String.Format("Result Set {0} does not exist", rs));
            }

            var currentResultSetId = resultSetList[0];
            var currentColumnSet   = result.DataSet.Tables[currentResultSetId - 1].Columns;

            resultSetList.RemoveAt(0);

            foreach (var rs in resultSetList)
            {
                var comparisonTable = result.DataSet.Tables[rs - 1];

                //verify that the same number of columns is the same for as recorded
                if (comparisonTable.Columns.Count != currentColumnSet.Count)
                {
                    throw new Exception
                          (
                              String.Format
                              (
                                  "Result Set {0}: {1} columns in does not match the {2} columns in Result Set {3}",
                                  rs,
                                  comparisonTable.Columns.Count,
                                  currentColumnSet.Count,
                                  currentResultSetId
                              )
                          );
                }

                //loop through columns and verify the base data type of the columns
                for (var c = 0; c < currentColumnSet.Count; c++)
                {
                    if (String.Compare(currentColumnSet[c].ColumnName, comparisonTable.Columns[c].ColumnName, !IsCaseSensitive) != 0)
                    {
                        throw new Exception
                              (
                                  String.Format
                                  (
                                      "Result Set {0}: Column {1} ({2}) does not match name for column in Result Set {3} ({4})",
                                      rs,
                                      c + 1,
                                      comparisonTable.Columns[c].ColumnName,
                                      currentResultSetId,
                                      currentColumnSet[c].ColumnName
                                  )
                              );
                    }

                    //compare datatypes
                    if (IsLooseComparison)
                    {
                        var currentType    = GetLooseType(currentColumnSet[c].DataType.Name);
                        var comparisonType = GetLooseType(comparisonTable.Columns[c].DataType.Name);

                        if (currentType != comparisonType)
                        {
                            throw new Exception
                                  (
                                      String.Format
                                      (
                                          "Result Set {0} Column {1} ({2}) does not match type for column in Result Set {3} ({4})",
                                          rs,
                                          c + 1,
                                          comparisonTable.Columns[c].DataType,
                                          currentResultSetId,
                                          currentColumnSet[c].DataType
                                      )
                                  );
                        }
                    }
                    else
                    {
                        if (String.Compare(currentColumnSet[c].DataType.ToString(), comparisonTable.Columns[c].DataType.ToString(), !IsCaseSensitive) != 0)
                        {
                            throw new Exception
                                  (
                                      String.Format
                                      (
                                          "Result Set {0} Column {1} ({2}) does not match type for column in Result Set {3} ({4})",
                                          rs,
                                          c + 1,
                                          comparisonTable.Columns[c].DataType,
                                          currentResultSetId,
                                          currentColumnSet[c].DataType
                                      )
                                  );
                        }
                    }
                }
            }
        }
コード例 #13
0
        /// <summary>
        /// Saves pending changes
        /// </summary>
        /// <param name="acceptOption">Defines when changes should be accepted locally</param>
        /// <param name="clearErrors">If set to true, all error entries are cleared before saving chnages</param>
        /// <param name="clientInfo">Optional client info object, to be submitted to the server</param>
        public override void SaveChangesAsync(AcceptOption acceptOption = AcceptOption.Default, bool clearErrors = true, bool failOnValidationErrors = true, ClientInfo clientInfo = null, Action <Exception> callback = null)
        {
            if (acceptOption == AcceptOption.Default)
            {
                //acceptOption = Transaction.Current != null ? AcceptOption.AcceptChangesOnTransactionCompleted : AcceptOption.AcceptChangesAfterSave;
                acceptOption = AcceptOption.AcceptChangesAfterSave;
            }

            if (clearErrors)
            {
                ClearErrors();
            }

            if (failOnValidationErrors && !IsValid)
            {
                throw new ValidationException("Validation failed for one or more entities.");
            }

            SubmitChangesAsync(
                clientInfo ?? ClientInfo,
                (resultSet, exception) =>
            {
                var error = exception;
                if (error == null)
                {
                    try
                    {
                        // accept changes
                        switch (acceptOption)
                        {
                        case AcceptOption.AcceptChangesAfterSave:
                            // refresh local data
                            var hasValidationErrors = IsServerValidationExceptionSuppressed ? false : resultSet.Any(entity => entity.Errors.Any(e => e.IsError));
                            Refresh(resultSet);
                            if (hasValidationErrors)
                            {
                                throw new ServerValidationException();
                            }
                            AcceptChanges(true);
                            break;

                        case AcceptOption.None:
                            // store result in private list
                            // allowes user to apply result (accept changes) asynchronousely
                            ResultSets.Add(resultSet);
                            break;

                        default:
                            throw new Exception(string.Format("This {0} is not implemented: {1}", acceptOption.GetType().Name, acceptOption));
                        }
                    }
                    catch (Exception ex)
                    {
                        error = ex;
                    }
                }

                if (error is FaultException)
                {
                    var ex = (FaultException)error;
                    var faultExceptionType = ex.GetType();
                    if (faultExceptionType.IsGenericType)
                    {
                        var detailType     = faultExceptionType.GetGenericArguments()[0];
                        var detailProperty = typeof(FaultException <>).MakeGenericType(detailType).GetProperty("Detail");
                        var detail         = detailProperty.GetValue(ex, null);
                        if (detail is OptimisticConcurrencyFault)
                        {
                            var stateEntries = GetStateEntries(((OptimisticConcurrencyFault)detail).Entities);
                            error            = new OptimisticConcurrencyException(null, stateEntries);
                        }
                        if (detail is UpdateFault)
                        {
                            var stateEntries = GetStateEntries(((UpdateFault)detail).Entities);
                            error            = new UpdateException(null, stateEntries);
                        }
                    }
                }

                if (callback != null)
                {
                    Invoke(delegate
                    {
                        callback(error);
                    });
                }
                OnSaveChangesCompleted(error);
            }
                );
        }
コード例 #14
0
        public override void Assert(DbConnection validationConnection, SqlExecutionResult[] results)
        {
            base.Assert(validationConnection, results);

            var result        = results[0];
            var resultSetList = new List <int>();

            try
            {
                if (ResultSets.ToUpper() == "ALL")
                {
                    resultSetList.AddRange(Enumerable.Range(1, result.DataSet.Tables.Count));
                }
                else if (ResultSets.Contains(","))
                {
                    resultSetList.AddRange(ResultSets.Split(',').Select(rs => Convert.ToInt16(rs)).Select(dummy => (int)dummy));
                }
                else if (ResultSets.Contains(":"))
                {
                    var temp = ResultSets.Split(':');
                    resultSetList.AddRange(Enumerable.Range(Convert.ToInt32(temp[0]), Convert.ToInt32(temp[1])));
                }
                else
                {
                    throw new ArgumentException("Invalid specification for result sets");
                }
            }
            catch
            {
                throw new ArgumentException(String.Format("{0} is an invalid result set specification.", ResultSets));
            }

            foreach (var rs in resultSetList.Where(rs => rs > result.DataSet.Tables.Count))
            {
                throw new ArgumentException(String.Format("ResultSet {0} does not exist", rs));
            }

            var currentResultSetId = resultSetList[0];
            var firstTable         = result.DataSet.Tables[currentResultSetId - 1];

            resultSetList.RemoveAt(0);

            //loop through batches verifying that the column count for each batch is the same
            foreach (var rs in resultSetList)
            {
                //verify resultset exists
                if (result.DataSet.Tables.Count < rs)
                {
                    throw new Exception(String.Format("ResultSet {0} does not exist", rs));
                }

                var secondTable = result.DataSet.Tables[rs - 1];

                //verify that the same number of columns is the same for as recorded
                if (firstTable.Columns.Count != secondTable.Columns.Count)
                {
                    throw new Exception
                          (
                              String.Format
                              (
                                  "Result Set {0}: {1} columns in does not match the {2} columns in Result Set {3}",
                                  currentResultSetId,
                                  firstTable.Columns.Count,
                                  secondTable.Columns.Count,
                                  rs
                              )
                          );
                }

                //verify that the number of rows is the same for as recorded
                if (firstTable.Rows.Count != secondTable.Rows.Count)
                {
                    throw new Exception
                          (
                              String.Format
                              (
                                  "Result Set {0}: {1} rows does not match the {2} rows in Result Set {3}",
                                  currentResultSetId,
                                  firstTable.Rows.Count,
                                  secondTable.Rows.Count,
                                  rs
                              )
                          );
                }

                var differenceTable = DataSetComparison.CompareDataTables(firstTable, secondTable, IsCaseSensitive, EnforceOrder);

                if (differenceTable.Rows.Count != 0)
                {
                    throw new Exception
                          (
                              String.Format
                              (
                                  "Result Set {0} and Result Set {2} had {1} mismatched records total",
                                  currentResultSetId,
                                  differenceTable.Rows.Count,
                                  rs
                              )
                          );
                }
            }
        }