private static IBatchRunner ResolveRunner(ObjectContext context)
        {
            DbConnection theConnection = (context.Connection as EntityConnection).StoreConnection;

            IBatchRunner provider = null;

            if (theConnection is SqlConnection)
            {
                provider = new SqlServerBatchRunner();
            }
            else if (theConnection.GetType().FullName == "MySql.Data.MySqlClient.MySqlConnection")
            {
                provider = new MySqlBatchRunner();
            }

            if (provider == null)
            {
                var ex = new InvalidOperationException("Could not resolve the IBatchRunner. Current database is not supported");
                ex.Data["DbConnection"] = theConnection;

                throw ex;
            }

            return(provider);
        }
        public static string GetSelectSql <TModel>(ObjectQuery <TModel> query, IEnumerable <string> selectedProperties, DbCommand command = null,
                                                   IBatchRunner runner = null, IList <string> fields = null)
        {
            if (selectedProperties == null || selectedProperties.Count() < 1)
            {
                throw new ArgumentException("The selected properties must be defined.", "selectedProperties");
            }

            var selector    = new StringBuilder(string.Join(",", selectedProperties)).Insert(0, "new (").Append(")");
            var selectQuery = DynamicQueryable.Select(query, selector.ToString());
            var objectQuery = selectQuery as ObjectQuery;

            if (objectQuery == null)
            {
                throw new ArgumentException("The query must be of type ObjectQuery.", "query");
            }

            string selectSql = objectQuery.ToTraceString();

            if (command != null)
            {
                objectQuery.Parameters.CopyTo(command, runner: runner);
            }

            if (fields != null)
            {
                GetPropertyPositions(selectQuery, fields);
            }

            return(selectSql);
        }
Пример #3
0
 /// <summary>
 /// Default constructor creates a control with no messages, and
 /// nothing currently running.
 /// </summary>
 public BatchRunnerControl()
 {
     InitializeComponent();
     m_Messages = new List<string>();
     m_Runner = null;
     m_CommandFile = null;
 }
Пример #4
0
 /// <summary>
 /// Default constructor creates a control with no messages, and
 /// nothing currently running.
 /// </summary>
 public BatchRunnerControl()
 {
     InitializeComponent();
     m_Messages    = new List <string>();
     m_Runner      = null;
     m_CommandFile = null;
 }
Пример #5
0
 public static void WaitForCompletion(this IBatchRunner runner, BatchRequest request)
 {
     while (!runner.IsCompleted(request))
     {
         Thread.Sleep(0);
     }
 }
Пример #6
0
        public static string GetSelectSql <TModel>(ObjectQuery <TModel> query, IEnumerable <string> selectedProperties, DbCommand command = null,
                                                   IBatchRunner runner = null, IList <string> fields = null)
        {
            if (selectedProperties == null || selectedProperties.Count() < 1)
            {
                throw new ArgumentException("The selected properties must be defined.", "selectedProperties");
            }

            var selector    = new StringBuilder(string.Join(",", selectedProperties)).Insert(0, "new (").Append(")");
            var selectQuery = DynamicQueryable.Select(query, selector.ToString());
            var objectQuery = selectQuery as ObjectQuery;

            if (objectQuery == null)
            {
                throw new ArgumentException("The query must be of type ObjectQuery.", "query");
            }

            string selectSql = objectQuery.ToTraceString();

            if (command != null)
            {
                objectQuery.Parameters.CopyTo(command, runner: runner);
            }

            if (fields != null)
            {
                fields.Clear();
                var maps = new NonPublicMember(objectQuery).GetProperty("QueryState").GetField("_cachedPlan").GetField("CommandDefinition")
                           .GetField("_columnMapGenerators").Idx(0).GetField("_columnMap").GetProperty("Element").GetProperty("Properties").Value as Array;
                foreach (var m in maps)
                {
                    var    mm   = new NonPublicMember(m);
                    int    pos  = (int)mm.GetProperty("ColumnPos").Value;
                    string name = (string)mm.GetProperty("Name").Value;
                    while (pos + 1 > fields.Count)
                    {
                        fields.Add(null);
                    }
                    fields[pos] = name;
                }
            }

            return(selectSql);
        }
Пример #7
0
        /// <summary>
        /// Executes a command script.
        /// </summary>
        /// <param name="runner">The object invoking the command (will be notified
        /// on completion or failure)</param>
        /// <param name="cmdFile">The command file to run</param>
        /// <param name="args">Any command line arguments for the script</param>
        /// <exception cref="ArgumentNullException">If the supplied <paramref name="runner"/>
        /// is null</exception>
        /// <exception cref="InvalidAsynchronousStateException">If a previous
        /// run has not yet completed</exception>
        public void RunCommand(IBatchRunner runner, string cmdFile, string args)
        {
            // Disallow an attempt to run something if a prior call is still executing.
            if (IsBusy)
            {
                throw new InvalidAsynchronousStateException();
            }

            if (runner == null)
            {
                throw new ArgumentNullException();
            }

            // I don't see how anything here could lead to an exception,
            // but who knows...

            try
            {
                m_Runner               = runner;
                m_CommandFile          = cmdFile;
                richTextBox.ScrollBars = RichTextBoxScrollBars.None;

                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.WorkingDirectory = Path.GetDirectoryName(cmdFile);
                processStartInfo.FileName         = cmdFile;
                processStartInfo.Arguments        = args;

                processStartInfo.UseShellExecute        = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError  = true;
                processStartInfo.CreateNoWindow         = true;

                stdoutWorker.RunWorkerAsync(processStartInfo);
            }

            catch (Exception ex)
            {
                m_Runner = null;
                runner.RunCompleted(ex);
            }
        }
 internal static async Task <int> InternalInsert <TModel>(this IBatchRunner runner, IQueryable <TModel> query, ObjectQuery <TModel> objectQuery,
                                                          EntityMap entityMap, bool async = false)
     where TModel : class
        public static string GetSelectKeySql <TEntity>(ObjectQuery <TEntity> query, EntityMap entityMap, DbCommand command, IBatchRunner runner, IList <string> fields = null)
            where TEntity : class
        {
            // TODO change to esql?

            // changing query to only select keys
            var    idFields = entityMap.KeyMaps.Select(key => key.PropertyName);
            string sql      = GetSelectSql(query, idFields, command, runner, fields);

            //if (fields != null)
            //{
            //    for (int i = 0; i < fields.Count; i++) if (!idFields.Contains(fields[i])) fields[i] = null;
            //}
            return(sql);
        }
        public static void CopyTo(this ObjectParameterCollection parameters, DbCommand command, Func <string, string> fnGetParamName = null, IBatchRunner runner = null)
        {
            fnGetParamName = fnGetParamName ?? (paramName => paramName);
            runner         = runner ?? BatchExtensions.ResolveRunner();
            var nullValue = runner.DbNull;

            foreach (var objectParameter in parameters)
            {
                var parameter = command.CreateParameter();
                parameter.ParameterName = fnGetParamName(objectParameter.Name);
                parameter.Value         = objectParameter.Value ?? nullValue;
                command.Parameters.Add(parameter);
            }
        }
Пример #11
0
        /// <summary>
        /// Executes a command script.
        /// </summary>
        /// <param name="runner">The object invoking the command (will be notified
        /// on completion or failure)</param>
        /// <param name="cmdFile">The command file to run</param>
        /// <param name="args">Any command line arguments for the script</param>
        /// <exception cref="ArgumentNullException">If the supplied <paramref name="runner"/>
        /// is null</exception>
        /// <exception cref="InvalidAsynchronousStateException">If a previous 
        /// run has not yet completed</exception>
        public void RunCommand(IBatchRunner runner, string cmdFile, string args)
        {
            // Disallow an attempt to run something if a prior call is still executing.
            if (IsBusy)
                throw new InvalidAsynchronousStateException();

            if (runner == null)
                throw new ArgumentNullException();

            // I don't see how anything here could lead to an exception,
            // but who knows...

            try
            {
                m_Runner = runner;
                m_CommandFile = cmdFile;
                richTextBox.ScrollBars = RichTextBoxScrollBars.None;

                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.WorkingDirectory = Path.GetDirectoryName(cmdFile);
                processStartInfo.FileName = cmdFile;
                processStartInfo.Arguments = args;

                processStartInfo.UseShellExecute = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.RedirectStandardError = true;
                processStartInfo.CreateNoWindow = true;

                stdoutWorker.RunWorkerAsync(processStartInfo);
            }

            catch (Exception ex)
            {
                m_Runner = null;
                runner.RunCompleted(ex);
            }
        }
Пример #12
0
        public static string GetSelectKeySql <TEntity>(ObjectQuery <TEntity> query, EntityMap entityMap, DbCommand command, IBatchRunner runner)
            where TEntity : class
        {
            // TODO change to esql?

            // changing query to only select keys
            return(GetSelectSql(query, entityMap.KeyMaps.Select(key => key.PropertyName), command, runner));
        }
Пример #13
0
 /// <summary>
 /// Executes a command script that requires no command line arguments.
 /// </summary>
 /// <param name="runner">The object invoking the command (will be notified
 /// on completion or failure)</param>
 /// <param name="cmdFile">The command file to run</param>
 /// <exception cref="InvalidAsynchronousStateException">If a previous
 /// run has not yet completed</exception>
 /// <exception cref="ArgumentNullException">If the supplied <paramref name="runner"/>
 /// is null</exception>
 public void RunCommand(IBatchRunner runner, string cmdFile)
 {
     RunCommand(runner, cmdFile, String.Empty);
 }
 public SubmissionDataMessageHandler(IBatchRunner batchRuunner, BaseLog logger)
 {
     _batchRuunner = batchRuunner;
     _logger       = logger;
 }
        internal static int InternalInsert <TModel>(this IBatchRunner runner, IQueryable <TModel> query, ObjectQuery <TModel> objectQuery,
                                                    EntityMap entityMap, bool async = false)
            where TModel : class
#endif
        {
            using (var db = QueryHelper.GetDb(objectQuery.Context))
            {
                var selectedProperties = QueryHelper.GetSelectedProperties(query.Expression, entityMap);
                if (selectedProperties == null)
                {
                    throw new ArgumentException("Cannot read the selected fields in the query", "sourceQuery");
                }

                var  insertFields       = new List <string>();
                var  selectSql          = GetSelectSql(objectQuery, selectedProperties, db.Command, runner, insertFields);
                bool isThereUnusedField = false;
                foreach (var f in insertFields)
                {
                    if (f == null)
                    {
                        isThereUnusedField = true;  break;
                    }
                }
                var selectFields = isThereUnusedField ? new SelectedFields(selectSql, runner.CharToEscapeQuote) : null;
                var sqlBuilder   = new StringBuilder(selectSql.Length * 2);
                sqlBuilder.Append("INSERT INTO ").Append(entityMap.TableName).Append(" (")
                .Append(string.Join(", ",
                                    from propName in insertFields
                                    join map in entityMap.PropertyMaps on propName equals map.PropertyName
                                    where propName != null
                                    select runner.Quote(map.ColumnName)
                                    ))
                .Append(")")
                .Append(Environment.NewLine);
                if (isThereUnusedField)
                {
                    sqlBuilder.Append("SELECT");
                    string separator = " ";
                    for (int i = 0; i < insertFields.Count; i++)
                    {
                        if (insertFields[i] != null)
                        {
                            sqlBuilder.Append(separator).Append(selectFields[i]);
                            separator = ", ";
                        }
                    }
                    sqlBuilder.Append(Environment.NewLine);
                    sqlBuilder.Append(selectSql.Substring(selectFields.FromIndex));
                }
                else
                {
                    sqlBuilder.Append(selectSql);
                }

                db.Command.CommandText = sqlBuilder.ToString();
                db.Log(db.Command.CommandText);

#if NET45
                int result = async
                    ? await db.Command.ExecuteNonQueryAsync().ConfigureAwait(false)
                    : db.Command.ExecuteNonQuery();
#else
                int result = db.Command.ExecuteNonQuery();
#endif
                // only commit if created transaction
                if (db.OwnTransaction)
                {
                    db.Transaction.Commit();
                }

                return(result);
            }
        }
        internal static Tuple <Db, string, SelectedFields, Dictionary <string, string>, string, SelectedFields, List <string> > UpdateJoinParam <TModel>(this IBatchRunner runner,
                                                                                                                                                         IQueryable <TModel> query, ObjectQuery <TModel> objectQuery, EntityMap entityMap)
            where TModel : class
        {
            var    db        = GetDb(objectQuery.Context);
            string keySelect = null;
            int    i         = 0;
            var    idFields  = new List <string>();

            try
            {
                keySelect = GetSelectKeySql(objectQuery, entityMap, null, runner, idFields);
            }
            catch (NotSupportedException ex)
            {
                //if (ex.HResult == -2146233067)
                throw new ArgumentException("The select statement must include the key(s) of updated table. The keys themselves would not be updated.", "query");
                //throw ex;
            }
            var selectKeyFields = new SelectedFields(keySelect, runner.CharToEscapeQuote);
            var idFieldsMap     = new Dictionary <string, string>();

            for (i = 0; i < idFields.Count; i++)
            {
                if (idFields[i] == null)
                {
                    continue;
                }
                string valueField = selectKeyFields[i];
                if (selectKeyFields.AliasIndexes[i] > 0)
                {
                    valueField = valueField.Substring(0, selectKeyFields.AliasIndexes[i]);
                }
                idFieldsMap[idFields[i]] = valueField;
            }

            var selectedProperties = GetSelectedProperties(query.Expression, entityMap);

            if (selectedProperties == null || selectedProperties.Count() < 1)
            {
                throw new ArgumentException("Cannot read the selected fields in the query", "query");
            }

            var    updateFields = new List <string>();
            string selectSql    = GetSelectSql(objectQuery, selectedProperties, db.Command, runner, updateFields);
            var    selectFields = new SelectedFields(selectSql, runner.CharToEscapeQuote);

            return(Tuple.Create(db, keySelect, selectKeyFields, idFieldsMap, selectSql, selectFields, updateFields));
        }
Пример #17
0
 /// <summary>
 /// Executes a command script that requires no command line arguments.
 /// </summary>
 /// <param name="runner">The object invoking the command (will be notified
 /// on completion or failure)</param>
 /// <param name="cmdFile">The command file to run</param>
 /// <exception cref="InvalidAsynchronousStateException">If a previous 
 /// run has not yet completed</exception>
 /// <exception cref="ArgumentNullException">If the supplied <paramref name="runner"/>
 /// is null</exception>
 public void RunCommand(IBatchRunner runner, string cmdFile)
 {
     RunCommand(runner, cmdFile, String.Empty);
 }