Ejemplo n.º 1
0
        //public UnitOfWorkBase(ContextCache contextCache)
        //{
        //    this.contextCache = contextCache;
        //}

        //public UnitOfWorkBase(DbContext dbcontext)
        //{
        //    dbContext = dbcontext;
        //    ticks = DateTime.Now.Ticks;
        //}

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="contextCache"></param>
        /// <param name="dbcontext"></param>
        public UnitOfWorkBase(ContextCache contextCache, DBContextBase dbcontext)
        {
            dbContext         = dbcontext;
            this.contextCache = contextCache;
            ticks             = DateTime.Now.Ticks;
            // 记录sql
            dbContext.Database.Log = (sql) =>
            {
                if (string.IsNullOrEmpty(sql) == false)
                {
                    SqlLog.AppendLine(sql);
                    if (DebugSql)
                    {
                        Debug.WriteLine(sql);
                    }
                }
            };
        }
Ejemplo n.º 2
0
        private void OpenWithCheck(string checkQueryString)
        {
            bool connectionChecked = false;
            bool restoreTriggered  = false;

            while (!connectionChecked)
            {
                base.Open();
                try {
                    using (var command = underlyingConnection.CreateCommand()) {
                        command.CommandText = checkQueryString;
                        command.ExecuteNonQuery();
                    }
                    connectionChecked = true;
                }
                catch (Exception exception) {
                    if (SqlHelper.ShouldRetryOn(exception))
                    {
                        if (restoreTriggered)
                        {
                            SqlLog.Error(exception, Strings.LogConnectionRestoreFailed);
                            throw;
                        }
                        SqlLog.Warning(exception, Strings.LogGivenConnectionIsCorruptedTryingToRestoreTheConnection);

                        var newConnection = new SqlServerConnection(underlyingConnection.ConnectionString);
                        try
                        {
                            underlyingConnection.Close();
                            underlyingConnection.Dispose();
                        }
                        catch { }

                        underlyingConnection = newConnection;
                        restoreTriggered     = true;
                        continue;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        public void MakeSavepoint(Session session, SqlConnection connection, string name)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXMakeSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                return; // Driver does not support save points, so let's fail later (on rollback)
            }

            try {
                connection.MakeSavepoint(name);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     存储过程查询所有值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbs"></param>
        /// <param name="procName">The procName.</param>
        /// <param name="parms">The parms.</param>
        /// <returns></returns>
        public static IEnumerable <T> StoredProcWithParams <T>(this DbBase dbs, string procName, dynamic parms)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = procName,
                Parameter  = parms == null ? "" : parms.ToString()
            };
            var result = dbs.DbConnecttion.Query <T>(procName, (object)parms, commandType: CommandType.StoredProcedure);

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
        public void RollbackToSavepoint(Session session, SqlConnection connection, string name)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXRollbackToSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                throw new NotSupportedException(Strings.ExCurrentStorageProviderDoesNotSupportSavepoints);
            }

            try {
                connection.RollbackToSavepoint(name);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///     返回符合要求的第一个
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbs"></param>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static T SqlWithParamsSingle <T>(this DbBase dbs, string sql, dynamic parms = null)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = sql,
                Parameter  = parms == null ? "" : parms.ToString()
            };
            var result = dbs.DbConnecttion.Query <T>(sql, (object)parms).FirstOrDefault();

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
        public void BeginTransaction(Session session, SqlConnection connection, IsolationLevel?isolationLevel)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXBeginningTransactionWithYIsolationLevel, session.ToStringSafely(), isolationLevel);
            }

            if (isolationLevel == null)
            {
                isolationLevel = IsolationLevelConverter.Convert(GetConfiguration(session).DefaultIsolationLevel);
            }

            try {
                connection.BeginTransaction(isolationLevel.Value);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public void CloseConnection(Session session, SqlConnection connection)
        {
            if (connection.State != ConnectionState.Open)
            {
                return;
            }

            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXClosingConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            try {
                connection.Close();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     存储过程增加删除修改
        /// </summary>
        /// <param name="dbs"></param>
        /// <param name="procName">存储过程名称</param>
        /// <param name="parms">参数</param>
        /// <returns>影响条数</returns>
        public static int InsertUpdateOrDeleteStoredProc(this DbBase dbs, string procName, dynamic parms = null)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = procName,
                Parameter  = parms == null ? "" : parms.ToString()
            };
            var result = dbs.DbConnecttion.Execute(procName, (object)parms, commandType: CommandType.StoredProcedure);

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
        public async Task CloseConnectionAsync(Session session, SqlConnection connection)
        {
            if (connection.State != ConnectionState.Open)
            {
                return;
            }

            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXClosingConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            try {
                await connection.CloseAsync().ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async ValueTask MakeSavepointAsync(
            Session session, SqlConnection connection, string name, CancellationToken token = default)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXMakeSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                return; // Driver does not support save points, so let's fail later (on rollback)
            }

            try {
                await connection.MakeSavepointAsync(name, token).ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
        public async ValueTask RollbackToSavepointAsync(
            Session session, SqlConnection connection, string name, CancellationToken token = default)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXRollbackToSavepointY, session.ToStringSafely(), name);
            }

            if (!hasSavepoints)
            {
                throw new NotSupportedException(Strings.ExCurrentStorageProviderDoesNotSupportSavepoints);
            }

            try {
                await connection.RollbackToSavepointAsync(name, token).ConfigureAwait(false);
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        ///     执行语句返回bool
        /// </summary>
        /// <param name="dbs"></param>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static bool SqlWithParamsBool(this DbBase dbs, string sql, dynamic parms = null)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            sql = sql.Replace("$ParamPrefix", dbs.ParamPrefix);
            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = sql,
                Parameter  = parms == null ? "" : parms.ToString()
            };
            var result = dbs.DbConnecttion.Query(sql, (object)parms).Any();

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///     执行增加删除修改语句
        /// </summary>
        /// <param name="dbs"></param>
        /// <param name="sql">Sql语句</param>
        /// <param name="parms">参数信息</param>
        /// <param name="isSetConnectionStr">是否需要重置连接字符串</param>
        /// <returns>影响数</returns>
        public static int InsertUpdateOrDeleteSql(this DbBase dbs, string sql, dynamic parms = null,
                                                  bool isSetConnectionStr = true)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = sql,
                Parameter  = parms == null ? "" : parms.ToString(),
            };
            var result = dbs.DbConnecttion.Execute(sql, (object)parms);

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
        public SqlConnection CreateConnection(Session session)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXCreatingConnection, session.ToStringSafely());
            }

            SqlConnection connection;

            try {
                connection = underlyingDriver.CreateConnection();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }

            if (connectionAccessorFactories != null)
            {
                connection.AssignConnectionAccessors(
                    CreateConnectionAccessorsFast(configuration.Types.DbConnectionAccessors));
            }

            var sessionConfiguration = GetConfiguration(session);

            connection.CommandTimeout = sessionConfiguration.DefaultCommandTimeout;
            var connectionInfo = GetConnectionInfo(session) ?? sessionConfiguration.ConnectionInfo;

            if (connectionInfo != null)
            {
                connection.ConnectionInfo = connectionInfo;
            }

            var connectionInitializationSql = GetInitializationSql(session) ?? configuration.ConnectionInitializationSql;

            if (!string.IsNullOrEmpty(connectionInitializationSql))
            {
                SetInitializationSql(connection, connectionInitializationSql);
            }

            return(connection);
        }
Ejemplo n.º 16
0
        /// <summary>
        ///     插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbs"></param>
        /// <param name="t"></param>
        /// <param name="transaction"></param>
        /// <param name="commandTimeout"></param>
        /// <returns></returns>
        public static int Insert <T>(this DbBase dbs, T t, IDbTransaction transaction = null, int?commandTimeout = null)
            where T : class
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            var db  = dbs.DbConnecttion;
            var sql = SqlQuery <T> .Builder(dbs);

            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = sql.InsertSql
            };
            var result = db.Execute(sql.InsertSql, t, transaction, commandTimeout);

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
        public void OpenConnection(Session session, SqlConnection connection)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXOpeningConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            try {
                connection.Open();
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }

            var extension = connection.Extensions.Get <InitializationSqlExtension>();

            if (!string.IsNullOrEmpty(extension?.Script))
            {
                using (var command = connection.CreateCommand(extension.Script))
                    ExecuteNonQuery(session, command);
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        ///     使用SqlBulkCopy批量进行插入数据
        /// </summary>
        /// <typeparam name="T">实体对象</typeparam>
        /// <param name="dbs"></param>
        /// <param name="entitys">实体对象集合</param>
        public static int InsertWithBulkCopy <T>(this DbBase dbs, List <T> entitys) where T : new()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            int result = 1;

            using (var destinationConnection = (SqlConnection)dbs.DbConnecttion)
            {
                using (var bulkCopy = new SqlBulkCopy(destinationConnection))
                {
                    Type   type      = entitys[0].GetType();
                    object classAttr = type.GetCustomAttributes(false)[0];
                    if (classAttr is TableAttribute)
                    {
                        TableAttribute tableAttr = classAttr as TableAttribute;
                        bulkCopy.DestinationTableName = tableAttr.Name; //要插入的表的表明
                    }
                    ModelHandler <T> mh = new ModelHandler <T>();
                    DataTable        dt = mh.FillDataTable(entitys);
                    if (dt != null && dt.Rows.Count != 0)
                    {
                        bulkCopy.WriteToServer(dt);
                    }
                }
            }
            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = "BulkCopy批量插入"
            };

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
Ejemplo n.º 19
0
        /// <summary>
        ///     执行Sql语句带参数
        /// </summary>
        /// <param name="dbs"></param>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static DataTable SqlWithParamsDataTable(this DbBase dbs, string sql, string tableName, dynamic parms = null)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            sql = sql.Replace("$ParamPrefix", dbs.ParamPrefix);
            SqlLog log = new SqlLog
            {
                CreateTime = DateTime.Now,
                OperateSql = sql,
                Parameter  = parms == null ? "" : parms.ToString()
            };
            var       resultReader = dbs.DbConnecttion.ExecuteReader(sql, (object)parms);
            DataTable result       = new DataTable(tableName);

            result.Load(resultReader);

            stopwatch.Stop();
            log.EndDateTime = DateTime.Now;
            log.ElapsedTime = stopwatch.Elapsed.TotalSeconds;
            WriteSqlLog(log);
            return(result);
        }
        public void OpenConnection(Session session, SqlConnection connection)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXOpeningConnectionY, session.ToStringSafely(), connection.ConnectionInfo);
            }

            var script = connection.Extensions.Get <InitializationSqlExtension>()?.Script;

            try {
                if (!string.IsNullOrEmpty(script))
                {
                    connection.OpenAndInitialize(script);
                }
                else
                {
                    connection.Open();
                }
            }
            catch (Exception exception) {
                throw ExceptionBuilder.BuildException(exception);
            }
        }
Ejemplo n.º 21
0
        public LogBase CreateLogger(LogType logType)
        {
            LogBase log;

            switch (logType)
            {
            case LogType.None:
                throw new NotImplementedException();

            case LogType.Sql:
                log = new SqlLog();
                break;

            case LogType.File:
                log = new FileLog();
                break;

            default:
                log = new SqlLog();
                break;
            }
            return(log);
        }
Ejemplo n.º 22
0
        private UpgradeActionSequence TranslateActions(SchemaExtractionResult extractedSchema, StorageModel sourceModel,
                                                       StorageModel targetModel, ActionSequence upgradeActions)
        {
            var enforceChangedColumns = context.Hints
                                        .OfType <ChangeFieldTypeHint>()
                                        .SelectMany(hint => hint.AffectedColumns)
                                        .ToList();

            var skipConstraints = context.Stage == UpgradeStage.Upgrading;

            var translator = new SqlActionTranslator(
                session.Handlers, executor, context.Services.MappingResolver,
                upgradeActions, extractedSchema, sourceModel, targetModel,
                enforceChangedColumns, !skipConstraints);

            var result = translator.Translate();

            if (SqlLog.IsLogged(LogLevel.Info))
            {
                LogStatements(result);
            }

            return(result);
        }
        private TResult ExecuteCommand <TResult>(Session session, DbCommand command, Func <DbCommand, TResult> action)
        {
            if (isLoggingEnabled)
            {
                SqlLog.Info(Strings.LogSessionXQueryY, session.ToStringSafely(), command.ToHumanReadableString());
            }

            session?.Events.NotifyDbCommandExecuting(command);

            TResult result;

            try {
                result = action.Invoke(command);
            }
            catch (Exception exception) {
                var wrapped = ExceptionBuilder.BuildException(exception, command.ToHumanReadableString());
                session?.Events.NotifyDbCommandExecuted(command, wrapped);
                throw wrapped;
            }

            session?.Events.NotifyDbCommandExecuted(command);

            return(result);
        }
Ejemplo n.º 24
0
        private static void Main(string[] args)
        {
            #region Test
            Log.WriteLine("Log");
            SqlLog.WriteLine("SqlLog");
            #endregion

            // 1. SystemExt
            Sample_SystemExt();

            // 2. Form Animaton
            FormAnimation frm = new FormAnimation();
            frm.ShowAsync();

            // 3. DeviceManager
            var dtUSBDevice    = DeviceManager.GetUSBDevices();
            var dtDriver       = DeviceManager.GetDriver();
            var dtDeviceDetail = DeviceManager.GetDeviceDetail();
            var dtBusInfo      = DeviceManager.GetBusInfo();

            // 4. NetWork Detect
            // Implement Delegate Event "AvailabilityChanged"
            NetworkStatus.AvailabilityChanged += NetworkStatus_AvailabilityChanged;
            Debug.WriteLine("The Network is " + (NetworkStatus.IsAvailable ? "Connect" : "DisConnect"));

            /* Output
             * The Network is Connect
             * //close wifi
             * The Network is DisConnect
             * //open wifi
             * The thread 0xa844 has exited with code 0 (0x0).
             * The Network is Connect
             */

            // 5. Set System Volume
            //SystemVoice.AuInit();
            Debug.WriteLine("The voice volume is " + SystemVoice.GetVolume());
            SystemVoice.SetVolume(0);
            Debug.WriteLine("The voice volume is " + SystemVoice.GetVolume());

            /* Output
             * The voice volume is 10
             * The voice volume is 0
             */

            // 6. Minimize Console UI
            SysUtil.HideApplication();
            SysUtil.KillProcessByName("Sample");

            // 7. Http Extension
            // Setup URL and Header(if neccesary)
            HttpExtension.URL = "http://192.168.100.235:9000/dev/api/v1/";
            var header = new Dictionary <string, string>();
            header.Add("Authorization", "Token 3c1fa688462c30c105df08326406d4fb");
            HttpExtension.Headers = header;

            var dtCity      = HttpExtension.Get <Cities>("lists/cascades?cascade-id=1");
            var dtCityAsync = HttpExtension.GetAsync <Cities>("lists/cascades?cascade-id=1").Result;
            var strCity     = HttpExtension.GetStrAsync("lists/cascades?cascade-id=1").Result;
            //var dtUser = HttpExtension.Post<User>("Users", "{\"ids\":[1,2,3]}");
            //var dtUserAsync = HttpExtension.PostAsync<User>("Users", "{\"ids\":[1,2,3]}").Result;
            //var strUser = HttpExtension.PostStrAsync("Users", "{\"ids\":[1,2,3]}").Result;

            // 8. Monitor Display's Brightness Get/Set
            Debug.WriteLine("The Brightness is " + Display.GetBrightness());
            Debug.WriteLine("Set Brightness to 20 ");
            Display.SetBrightness(20);
            System.Threading.Thread.Sleep(2000);
            Debug.WriteLine("Set Brightness to 100 ");
            Display.SetBrightness(100);

            while (true)
            {
                var result = Console.ReadLine();
                if (result.Equals("q"))
                {
                    break;
                }
            }
        }
Ejemplo n.º 25
0
 public void Log <TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func <TState, Exception, string> formatter)
 {
     SqlLog.LogSql(formatter(state, exception));
 }
Ejemplo n.º 26
0
 internal static void DbCommandExecuting(DbCommand cmd)
 {
     if (ExecutionEngine.SqlTranslationsEnabled)
     {
         TextWriter sqlLog = SqlLog;
         if (sqlLog != null)
         {
             lock (sqlLog)
             {
                 bool flag2 = false;
                 if ((cmd.Connection is SqlConnection) || ((cmd.Connection is LINQPadDbConnection) && (((LINQPadDbConnection)cmd.Connection).Proxy is SqlConnection)))
                 {
                     try
                     {
                         string serverVersion = cmd.Connection.ServerVersion;
                         if (!(string.IsNullOrEmpty(serverVersion) || (int.Parse(serverVersion.Split(new char[] { '.' })[0]) < 10)))
                         {
                             flag2 = true;
                         }
                     }
                     catch
                     {
                     }
                 }
                 if (SqlLog.GetStringBuilder().Length > 0)
                 {
                     sqlLog.WriteLine("GO\r\n");
                 }
                 bool flag3 = false;
                 if (cmd.Parameters.Count > 0)
                 {
                     sqlLog.WriteLine("-- Region Parameters");
                     foreach (DbParameter parameter in cmd.Parameters)
                     {
                         SqlParameter parameter2 = parameter as SqlParameter;
                         if (parameter2 == null)
                         {
                             sqlLog.WriteLine(string.Concat(new object[] { "-- ", parameter.ParameterName, ": ", parameter.DbType, " [", parameter.Value, "]" }));
                         }
                         else if ((parameter2.Value == null) && ((parameter2.Direction == ParameterDirection.Input) || (parameter2.Direction == ParameterDirection.InputOutput)))
                         {
                             flag3 = true;
                         }
                         else
                         {
                             sqlLog.WriteLine(SqlParameterFormatter.GetInitializer(parameter2, flag2));
                         }
                     }
                     sqlLog.WriteLine("-- EndRegion");
                 }
                 if (cmd.CommandType == CommandType.Text)
                 {
                     sqlLog.WriteLine(cmd.CommandText);
                 }
                 else if (cmd.CommandType == CommandType.TableDirect)
                 {
                     sqlLog.WriteLine("select * from " + cmd.CommandText);
                 }
                 else
                 {
                     DbParameter   parameter3 = cmd.Parameters.OfType <DbParameter>().FirstOrDefault <DbParameter>(p => p.Direction == ParameterDirection.ReturnValue);
                     StringBuilder builder    = new StringBuilder("exec ");
                     if (parameter3 != null)
                     {
                         builder.Append(parameter3.ParameterName + " = ");
                     }
                     builder.Append(cmd.CommandText);
                     int num = 0;
                     foreach (DbParameter parameter in cmd.Parameters)
                     {
                         if ((parameter.Direction != ParameterDirection.ReturnValue) && (parameter.Value != null))
                         {
                             builder.Append(((num++ > 0) ? "," : "") + " " + (flag3 ? (parameter.ParameterName + "=") : "") + parameter.ParameterName + ((parameter.Direction == ParameterDirection.Input) ? "" : " OUTPUT"));
                         }
                     }
                     sqlLog.WriteLine(builder.ToString());
                 }
             }
         }
     }
 }
Ejemplo n.º 27
0
 public virtual SqlLog DeleteSqlLog(SqlLog entity)
 {
     this.DeleteSqlLog(entity.SqlLogId);
     return(entity);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Низкоуровневый метод обновления после запроса
        /// </summary>
        /// <param name="query"></param>
        /// <param name="options"></param>
        /// <param name="c"></param>
        /// <param name="allids"></param>
        /// <param name="cascade"></param>
        public List <long> UpdateSingleQuery(string query, ObjectDataCacheHints options, IDbConnection c, List <long> allids, bool cascade)
        {
            options = options ?? ObjectDataCacheHints.Empty;
            object eq = query;

            if (options.KeyQuery)
            {
                eq = options.Key;
                var external = GetByExternals(eq);
                if (null != external)
                {
                    Set(external);
                    var exids = new[] { ((IWithId)external).Id };
                    if (cascade)
                    {
                        AfterUpdateCache(exids, c, new ObjectDataCacheHints {
                            NoChildren = true
                        });
                    }
                    return(exids.ToList());
                }
            }
            else
            {
                var externals = FindByExternals(eq).ToArray();
                if (externals.Any())
                {
                    var exarray = externals.ToArray();
                    foreach (var e in externals.ToArray())
                    {
                        Set(e);
                    }
                    var exids = exarray.OfType <IWithId>().Select(_ => _.Id).ToArray();
                    if (cascade)
                    {
                        AfterUpdateCache(exids, c, new ObjectDataCacheHints {
                            NoChildren = true
                        });
                    }
                    return(exids.ToList());
                }
            }



            allids = allids ?? new List <long>();
            if (null == c)
            {
                return(allids);
            }
            var q = query;

            if (!q.Contains("from"))
            {
                q = "select Id from " + Adapter.GetTableName();
                if (!string.IsNullOrWhiteSpace(query))
                {
                    q += " where " + query;
                }
            }

            if (string.IsNullOrWhiteSpace(c.ConnectionString))
            {
                throw new Exception("bad connection string!!!");
            }
            c.WellOpen();
            var cmd = c.CreateCommand(q);
            var ids = new List <long>();

            SqlLog.Trace(q);
            using (var idsReader = cmd.ExecuteReader()){
                while (idsReader.Read())
                {
                    var id = Convert.ToInt64(idsReader.GetValue(0));
                    if (!_nativeCache.ContainsKey(id))
                    {
                        ids.Add(id);
                    }
                    if (!allids.Contains(id))
                    {
                        allids.Add(id);
                    }
                }
            }
            if (ids.Count != 0)
            {
                q = "(Id in (" + string.Join(",", ids) + "))";

                cmd = c.CreateCommand(Adapter.PrepareSelectQuery(q));
                SqlLog.Trace(cmd.CommandText);
                using (var reader = cmd.ExecuteReader()){
                    var items = Adapter.ProcessRecordSet(reader, true).ToArray();
                    foreach (var item in items)
                    {
                        Set(item);
                    }
                }
                if (cascade)
                {
                    AfterUpdateCache(ids, c, options);
                }
            }
            return(allids);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 写入SqlLog日志
        /// </summary>
        /// <param name="log"></param>
        public static async Task WriteSqlLog(SqlLog log)
        {
            SqlLogHandler handler = new SqlLogHandler(log.OperateSql, log.EndDateTime, log.ElapsedTime, log.Parameter);

            handler.WriteLog();
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Called by the Server API when this plugin is initialized.
        /// This should never be called by a plugin.
        /// </summary>
        public override void Initialize()
        {
            try
            {
                HandleCommandLine(Environment.GetCommandLineArgs());

                if (!Directory.Exists(SavePath))
                {
                    Directory.CreateDirectory(SavePath);
                }
                if (!Directory.Exists(LogPath))
                {
                    Directory.CreateDirectory(LogPath);
                }
                if (!Directory.Exists(PluginPath))
                {
                    Directory.CreateDirectory(PluginPath);
                }

                ConfigFile.ConfigRead += OnConfigRead;
                if (File.Exists(ConfigPath))
                {
                    Config = ConfigFile.Read(ConfigPath);
                }
                Config.Write(ConfigPath);

                if (Config.StorageType.ToLower() == "sqlite")
                {
                    string sql = Path.Combine(SavePath, "orion.sqlite");
                    Database = new SqliteConnection(String.Format("uri=file://{0},Version=3", sql));
                }
                else if (Config.StorageType.ToLower() == "mysql")
                {
                    try
                    {
                        string[] hostport = Config.MySqlHost.Split(':');
                        Database = new MySqlConnection
                        {
                            ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};",
                                                             hostport[0],
                                                             hostport.Length > 1 ? hostport[1] : "3306",
                                                             Config.MySqlDbName,
                                                             Config.MySqlUsername,
                                                             Config.MySqlPassword
                                                             )
                        };
                    }
                    catch (MySqlException ex)
                    {
                        ServerApi.LogWriter.PluginWriteLine(this, ex.ToString(), TraceLevel.Error);
                        throw new Exception(Strings.MySqlException);
                    }
                }
                else
                {
                    throw new Exception(Strings.InvalidDbTypeException);
                }

                if (Config.UseSqlLogging)
                {
                    Log = new SqlLog(this, Path.Combine(LogPath, "log.log"), false);
                }
                else
                {
                    //Log = new TextLog(this, Path.Combine(LogPath, "log.log"), false);
                    Log = new Log(Path.Combine(SavePath, "log4net.config"));
                }

                Users       = new UserHandler(this);
                Bans        = new BanHandler(this);
                Utils       = new Utils();
                HashHandler = new Hasher(this);

                LoadPlugins();
            }
            catch (Exception ex)
            {
                Log.Error(Strings.StartupException);
                Log.Error(ex.ToString());
                Environment.Exit(1);
            }
        }