public static void ExecuteNonQuery(this IDatabaseAccessor instance, string commandText, dynamic parameterValues)
        {
            using (SqlConnection connection = instance.CreateConnection())
            {
                string outputValue = null;
                connection.Open();
                SqlCommand command = instance.CreateCommand(connection, commandText, CommandType.StoredProcedure);
                IEnumerable <PropertyInfo> properties = ((Type)parameterValues.GetType()).GetProperties().Where(property => property.CanRead);
                properties.ForEach(property =>
                {
                    object value                 = property.GetValue(parameterValues, null);
                    SqlDbType?valType            = null;
                    ParameterDirection direction = ParameterDirection.Input;
                    string parameterName         = property.Name;
                    if (parameterName.StartsWith("_"))
                    {
                        direction     = ParameterDirection.InputOutput;
                        parameterName = parameterName.Substring(1);
                        outputValue   = parameterName;
                    }
                    if (!parameterName.Equals("IncludeDeleted", StringComparison.OrdinalIgnoreCase))
                    {
                        command.SetParameter(parameterName, value, direction, valType);
                    }
                    else
                    {
                        command.SetIncludeDeletedParameter((bool)value);
                    }
                });

                var reader = command.ExecuteNonQuery();
            }
        }
Example #2
0
        public SqlWriter ColumnDefinition(string name, Type clrType, SqlDbType?sqlType, int?length, int?precision, int?scale, bool isPrimaryKey, bool isIdentity,
                                          bool nullable, bool autoGenerated, string computation, bool?computationPersisted, object defaultValue)
        {
            Action <SqlWriter> writeNullable = x => { if (nullable)
                                                      {
                                                          x.Nullable.Flush();
                                                      }
                                                      else
                                                      {
                                                          x.NotNullable.Flush();
                                                      } };
            var writer = QuotedName(name);

            if (!string.IsNullOrEmpty(computation))
            {
                return(writer.As.OpenBlock.Trim().Write(computation).Trim().CloseBlock.Do(
                           computationPersisted.HasValue && computationPersisted.Value, x => x.Persisted.Do(writeNullable).Flush()));
            }
            var type = sqlType ?? (clrType?.GetSqlType() ?? SqlDbType.NVarChar);

            writer.DataTypeDefinition(type, length, precision, scale);
            if (type == SqlDbType.Int && isIdentity)
            {
                IntegerIdentity.Flush();
            }
            writeNullable(writer);
            if (!isIdentity)
            {
                if (autoGenerated || (defaultValue != null && defaultValue != DBNull.Value))
                {
                    Default.Flush();
                }
                if (defaultValue != null && defaultValue != DBNull.Value)
                {
                    Value(defaultValue, type);
                }
                else if (autoGenerated)
                {
                    if (type == SqlDbType.DateTime || type == SqlDbType.SmallDateTime ||
                        type == SqlDbType.DateTime2 || type == SqlDbType.Date ||
                        type == SqlDbType.Time || type == SqlDbType.Timestamp)
                    {
                        GetDate();
                    }
                    else if (type == SqlDbType.UniqueIdentifier && !isPrimaryKey)
                    {
                        NewId();
                    }
                    else if (type == SqlDbType.UniqueIdentifier && isPrimaryKey)
                    {
                        NewSequentialId();
                    }
                    else
                    {
                        throw new Exception($"Cannot generate value for type {type}");
                    }
                }
            }
            return(this);
        }
Example #3
0
 public SQLParameter(string parameterName, object parameterValue, SqlDbType dbType, ParameterDirection paramDirection)
 {
     _parameterName  = parameterName;
     _parameterValue = parameterValue;
     _dbType         = dbType;
     _direction      = paramDirection;
 }
 public static SqlPersistenceParameterOptions ParamOptions(SqlDbType?dbType = null, int?size = null)
 {
     return(new SqlPersistenceParameterOptions()
     {
         SqlDbType = dbType, Size = size
     });
 }
        //Overrides the binding process so we can use the correct database types
        public override void BindParameters(DbCommand command, List <Parameter> results)
        {
            if (results != null)
            {
                //Morphs the command object intot he sql version
                SqlCommand sqlCommand = command as SqlCommand;

                foreach (Parameter param in results)
                {
                    //Overrides the binding if its an sp variable
                    string bindingStart = (sqlCommand.CommandType == CommandType.StoredProcedure) ? "@" : InternalDatabaseBinding;

                    string bindingDefinition = $"{bindingStart}{param.BindingName}";
                    sqlCommand.Parameters.AddWithValue(bindingDefinition, (param.Value ?? DBNull.Value));
                    if (param.Value != null)
                    {
                        if (param.DatabaseType != null)
                        {
                            SQLServerDatabaseType dbType = param.DatabaseType as SQLServerDatabaseType;
                            sqlCommand.Parameters[bindingDefinition].SqlDbType = dbType.SQLDBType.Value;
                        }
                        else//Use our automatic conversion system
                        {
                            SqlDbType?dbType = BindingConvertor.ToSqlDbType(param.Type);
                            if (dbType.HasValue)
                            {
                                sqlCommand.Parameters[bindingDefinition].SqlDbType = dbType.Value;
                            }
                        }
                    }
                }
            }
        }
Example #6
0
        internal static (object value, SqlDbType?dbType) CLRValueToDB(MsSqlDataStoreBase store, object value, string explicitDbType)
        {
            SqlDbType?convertedDbType = null;

            if (explicitDbType.IsNotNullOrWhiteSpace())
            {
                convertedDbType = explicitDbType.AsNullableEnum <SqlDbType>();
            }

            if (value == null)
            {
                return(null, convertedDbType);
            }

            if (value is ulong ulng)
            {
                value           = (decimal)ulng;
                convertedDbType = SqlDbType.Decimal;
            }
            else if (value is DateTime clrDt && convertedDbType == SqlDbType.Date)
            {
                // Expected DATE got NUmber
                // convertedDbType = OracleDbType.Int64;
                // value = clrDt.Ticks;// new global::Oracle.ManagedDataAccess.Types.OracleDate(clrDt);

                //Expected NUMBER got DATE
                // value = new global::Oracle.ManagedDataAccess.Types.OracleTimeStamp(clrDt);
                // value = new global::Oracle.ManagedDataAccess.Types.OracleDate(clrDt);
                // convertedDbType = OracleDbType.NVarchar2;
                // value = clrDt.ToString("yyyyMMddHHmmss");
            }
 public SqlQueryParameter(string _name, object _value, SqlDbType _db_type, int _size)
 {
     name    = _name;
     value   = _value;
     db_type = _db_type;
     size    = _size;
 }
 public SqlQueryParameter(string _name, object _value)
 {
     name    = _name;
     value   = _value;
     db_type = null;
     size    = null;
 }
Example #9
0
        public virtual ISqlCommandWrapper WithParameter <T>(string name, T value, SqlDbType?type = null, int?size = null)
        {
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }

            SqlParameter param;

            if (value != null)
            {
                param = Command.Parameters.AddWithValue(name, value);
            }
            else
            {
                param = Command.Parameters.AddWithValue(name, DBNull.Value);
            }

            if (type.HasValue)
            {
                param.SqlDbType = type.Value;
            }

            if (size.HasValue)
            {
                param.Size = size.Value;
            }

            return(this);
        }
Example #10
0
        /// <summary>
        /// Converts a value to a string suitable for use in a SQL statement.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="dbType">Optional database column type.</param>
        /// <returns></returns>
        public override string ValueToSqlValue(object value, SqlDbType?dbType)
        {
            switch (value)
            {
            case string s:
            {
                switch (dbType)
                {
                case SqlDbType.Char:
                case SqlDbType.VarChar:
                case SqlDbType.Text:
                    return("'" + s.Replace("'", "''", StringComparison.OrdinalIgnoreCase) + "'");

                case SqlDbType.NChar:
                case SqlDbType.NVarChar:
                case SqlDbType.NText:
                    return("N'" + s.Replace("'", "''", StringComparison.OrdinalIgnoreCase) + "'");

                default:             //Assume Unicode
                    return("N'" + s.Replace("'", "''", StringComparison.OrdinalIgnoreCase) + "'");
                }
            }

            default:
                return(base.ValueToSqlValue(value, dbType));
            }
        }
Example #11
0
 public StoreProcedureInfo Setting(SqlDbType?dbType                       = null,
                                   int?size                               = null,
                                   ParameterDirection?direction           = null,
                                   byte?precision                         = null,
                                   byte?scale                             = null,
                                   string sourceColumn                    = null,
                                   DataRowVersion?sourceVersion           = null,
                                   bool?sourceColumnNullMapping           = null,
                                   string xmlSchemaCollectionDatabase     = null,
                                   string xmlSchemaCollectionOwningSchema = null,
                                   string xmlSchemaCollectionName         = null)
 {
     if (lastAdded == null)
     {
         throw new Exception("There's not element inserted");
     }
     lastAdded.Size                            = size ?? lastAdded.Size;
     lastAdded.Direction                       = direction ?? lastAdded.Direction;
     lastAdded.Precision                       = precision ?? lastAdded.Precision;
     lastAdded.Scale                           = scale ?? lastAdded.Scale;
     lastAdded.SourceColumn                    = sourceColumn ?? lastAdded.SourceColumn;
     lastAdded.SourceVersion                   = sourceVersion ?? lastAdded.SourceVersion;
     lastAdded.SourceColumnNullMapping         = sourceColumnNullMapping ?? lastAdded.SourceColumnNullMapping;
     lastAdded.XmlSchemaCollectionDatabase     = xmlSchemaCollectionDatabase ?? lastAdded.XmlSchemaCollectionDatabase;
     lastAdded.XmlSchemaCollectionOwningSchema = xmlSchemaCollectionOwningSchema ?? lastAdded.XmlSchemaCollectionOwningSchema;
     lastAdded.XmlSchemaCollectionName         = xmlSchemaCollectionName ?? lastAdded.XmlSchemaCollectionName;
     return(this);
 }
Example #12
0
        /// <summary>
        /// This will add an array of parameters to a SqlCommand. This is used for an IN statement.
        /// Use the returned value for the IN part of your SQL call. (i.e. SELECT * FROM table WHERE field IN ({paramNameRoot}))
        /// </summary>
        /// <param name="cmd">The SqlCommand object to add parameters to.</param>
        /// <param name="paramNameRoot">What the parameter should be named followed by a unique value for each value. This value surrounded by {} in the CommandText will be replaced.</param>
        /// <param name="values">The array of strings that need to be added as parameters.</param>
        /// <param name="dbType">One of the System.Data.SqlDbType values. If null, determines type based on T.</param>
        /// <param name="size">The maximum size, in bytes, of the data within the column. The default value is inferred from the parameter value.</param>
        public static SqlParameter[] AddArrayParameters <T>(this SqlCommand cmd, string paramNameRoot,
                                                            IEnumerable <T> values, SqlDbType?dbType = null, int?size = null)
        {
            /* An array cannot be simply added as a parameter to a SqlCommand so we need to loop through things and add it manually.
             * Each item in the array will end up being it's own SqlParameter so the return value for this must be used as part of the
             * IN statement in the CommandText.
             */
            var parameters     = new List <SqlParameter>();
            var parameterNames = new List <string>();
            var paramNbr       = 1;

            foreach (var value in values)
            {
                var paramName = string.Format("@{0}{1}", paramNameRoot, paramNbr++);
                parameterNames.Add(paramName);
                SqlParameter p = new SqlParameter(paramName, value);
                if (dbType.HasValue)
                {
                    p.SqlDbType = dbType.Value;
                }
                if (size.HasValue)
                {
                    p.Size = size.Value;
                }
                cmd.Parameters.Add(p);
                parameters.Add(p);
            }

            cmd.CommandText = cmd.CommandText.Replace("{" + paramNameRoot + "}", string.Join(",", parameterNames));

            return(parameters.ToArray());
        }
Example #13
0
        public static Table WithColumn(this Table table, string columnName, SqlDbType?type, bool isNullable = false, bool isPrimaryKey = false, Column foreignKey = null, Annotation annotation = null)
        {
            var newColumn = new Column(columnName, table)
            {
                Type         = type,
                IsNullable   = isNullable,
                IsPrimaryKey = isPrimaryKey,
                ForeignKey   = foreignKey,
                Annotations  = annotation != null ? new HashSet <Annotation>()
                {
                    annotation
                } : new HashSet <Annotation>()
            };

            var newColumns = new List <Column>()
            {
                newColumn
            };

            if (table.Columns.Count() > 0)
            {
                newColumns.AddRange(table.Columns);
            }
            table.Columns = newColumns;

            return(table);
        }
Example #14
0
 public Column(
     string name,
     Type type                 = null,
     SqlDbType?sqlType         = null,
     KeyType key               = KeyType.None,
     bool isIdentity           = false,
     short length              = 0,
     byte?precision            = null,
     byte?scale                = null,
     bool isNullable           = false,
     bool isAutoGenerated      = false,
     object defaultValue       = null,
     string computation        = null,
     bool?computationPersisted = null)
 {
     Name = name;
     if (type == null && sqlType == null && string.IsNullOrEmpty(computation))
     {
         throw new Exception("No column data type or computation specified.");
     }
     Type                 = type ?? (sqlType.HasValue ? sqlType.Value.GetClrType(isNullable) : null);
     SqlType              = sqlType ?? (type != null ? type.GetSqlType() : (SqlDbType?)null);
     Key                  = key;
     IsIdentity           = isIdentity;
     Length               = length;
     Precision            = precision;
     Scale                = scale;
     IsAutoGenerated      = isAutoGenerated;
     IsNullable           = isNullable;
     DefaultValue         = defaultValue;
     Computation          = computation;
     ComputationPersisted = computationPersisted;
 }
Example #15
0
 public SQLParameter(string parameterName, object parameterValue, SqlDbType dbType, int size)
 {
     _parameterName  = parameterName;
     _parameterValue = parameterValue;
     _dbType         = dbType;
     _size           = size;
 }
Example #16
0
 //public SqlTypeAttribute(bool? isNullable = null,
 //    int? precision = null,
 //    int? scale = null,
 //    int? length = null,
 //    SqlDbType? type = null)
 //{
 //    IsNullable = isNullable;
 //    Precision = precision;
 //    Scale = scale;
 //    Length = length;
 //    Type = type;
 //}
 public SqlTypeAttribute(SqlDbType? type, bool? isNullable, int? length, int? precision, int? scale)
 {
     IsNullable = isNullable;
     Precision = precision;
     Scale = scale;
     Length = length;
     Type = type;
 }
Example #17
0
        private static SqlDbType GetCommonSqlDbType <TClrType>()
        {
            SqlDbType?result = null;

            Type clrType = typeof(TClrType);

            if (clrType == typeof(int) || clrType == typeof(int?))
            {
                result = SqlDbType.Int;
            }

            if (result == null && clrType == typeof(byte) || clrType == typeof(byte?))
            {
                result = SqlDbType.TinyInt;
            }

            if (result == null && clrType == typeof(short) || clrType == typeof(short?))
            {
                result = SqlDbType.SmallInt;
            }

            if (result == null && clrType == typeof(decimal) || clrType == typeof(decimal?))
            {
                result = SqlDbType.Decimal;
            }

            if (result == null && clrType == typeof(long) || clrType == typeof(long?))
            {
                result = SqlDbType.BigInt;
            }

            if (result == null && clrType == typeof(DateTime) || clrType == typeof(DateTime?))
            {
                result = SqlDbType.DateTime;
            }

            if (result == null && clrType == typeof(bool) || clrType == typeof(bool?))
            {
                result = SqlDbType.Bit;
            }

            if (result == null && clrType == typeof(DateTime) || clrType == typeof(DateTime?))
            {
                result = SqlDbType.DateTime;
            }

            if (result == null && clrType == typeof(string))
            {
                result = SqlDbType.NVarChar;
            }

            if (result == null)
            {
                throw new NotSupportedException("Common SqlDbType for type " + clrType.FullName + " is not supported.");
            }

            return(result.Value);
        }
Example #18
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="executeString"></param>
        /// <param name="parameter"></param>
        /// <param name="valuecollection"></param>
        /// <exception cref="InvalidOperationException">Open() or Fill()</exception>
        /// <exception cref="SqlException">Open();ExecuteNonQuery()</exception>
        /// <exception cref="System.Configuration.ConfigurationErrorsException">Open()</exception>
        /// <exception cref="ArgumentException">.CommandType</exception>
        /// <returns>DataTable</returns>
        /// <exception cref="SqlException">lỗi SqlException</exception>
        /// <exception cref="IndexOutOfRangeException">kiểm tra lại số lượng danh sách tham số IndexOutOfRangeException</exception>
        /// <exception cref="InvalidCastException">ExecuteNonQuery()</exception>
        /// <exception cref="System.IO.IOException">ExecuteNonQuery()</exception>
        /// <exception cref="InvalidOperationException">ExecuteNonQuery()</exception>
        /// <exception cref="ObjectDisposedException">ExecuteNonQuery()</exception>
        /// <returns>int n: kết quả số lượng dòng bị ảnh hưởng bởi thao tác</returns>
        public static int ExecuteNoneQuery(CommandType EnumCommandType, string CommandText, List <string> InputParamNames, List <object> InputValueCollection,
                                           List <string> OutputParamNames, List <SqlDbType> OutputParamDBType, out List <object> OutputValueCollection,
                                           string ReturnParamName, SqlDbType?ReturnParamSqlDBType, out object ReturnValue)
        {
            int n = 0;

            OutputValueCollection = new List <object>();
            ReturnValue           = new object();
            using (SqlConnection connect = new SqlConnection(ConnectionString)) {
                try {
                    connect.Open();
                    SqlCommand command = connect.CreateCommand();
                    command.CommandType = EnumCommandType;
                    command.CommandText = CommandText;
                    int i = 0, k = 0;
                    if (InputParamNames != null && InputParamNames.Count > 0)
                    {
                        for (i = 0; i < InputParamNames.Count; i++)
                        {
                            command.Parameters.AddWithValue(InputParamNames[i], InputValueCollection[i]);
                        }
                    }
                    if (OutputParamNames != null && OutputParamNames.Count > 0)
                    {
                        for (k = 0; k < OutputParamNames.Count; k++)
                        {
                            command.Parameters.Add(OutputParamNames[k], OutputParamDBType[k]).Direction = ParameterDirection.Output;
                        }
                    }

                    if (!string.IsNullOrEmpty(ReturnParamName))
                    {
                        SqlParameter temp1 = new SqlParameter(ReturnParamName, (SqlDbType)ReturnParamSqlDBType);
                        command.Parameters.Add(temp1).Direction = ParameterDirection.ReturnValue;
                    }

                    n = command.ExecuteNonQuery();
                    if (OutputParamNames != null && OutputParamNames.Count > 0)
                    {
                        for (k = 0; k < OutputParamNames.Count; k++)
                        {
                            object temp = command.Parameters[OutputParamNames[k].ToString()].Value;
                            OutputValueCollection.Add(temp);
                        }
                    }
                    if (!string.IsNullOrEmpty(ReturnParamName))
                    {
                        ReturnValue = command.Parameters[ReturnParamName.ToString()].Value;
                    }
                }
                catch (Exception ex) {
                    throw ex;
                }
                finally { connect.Close(); }
            }
            return(n);
        }
Example #19
0
 public DbTypeMap(ADONETType adonetType, DbType?dbType, SqlDbType?sqlDbType, OleDbType?oleDbType, OdbcType?odbcType)
     : this()
 {
     ADONETType = adonetType;
     DbType     = dbType;
     SqlDbType  = sqlDbType;
     OleDbType  = oleDbType;
     OdbcType   = odbcType;
 }
        /// <summary>
        /// Make a sql parameter.
        /// </summary>
        /// <param name="name">Name of parameter.</param>
        /// <param name="value">Value of parameter.</param>
        /// <param name="dbType">Database type of parameter.</param>
        /// <returns>SqlParameter</returns>
        private SqlParameter MakeSqlParameter(string name, object value, SqlDbType?sqlDbType)
        {
            var param = new SqlParameter(name, value);

            if (sqlDbType.HasValue)
            {
                param.SqlDbType = sqlDbType.Value;
            }
            return(param);
        }
Example #21
0
        public SqlDbType?SqlProviderType()
        {
            SqlDbType?provider = null;

            if (ProviderType != null && ProviderType is int)
            {
                provider = new Nullable <SqlDbType>((SqlDbType)ProviderType);
            }

            return(provider);
        }
Example #22
0
        internal static bool TryGetDbType(DbType type, out SqlDbType?x)
        {
            if (!Enum.TryParse(typeof(SqlDbType), type.ToString(), out object obj))
            {
                x = null;
                return(false);
            }

            x = (SqlDbType)obj;
            return(true);
        }
    public void Add(string name, object value = null, SqlDbType?dbType = null, ParameterDirection direction = ParameterDirection.Input, int?size = null)
    {
        var par = value != null ? new SqlParameter(name, value) : new SqlParameter(name, dbType);

        par.Direction = direction;
        if (size.HasValue)
        {
            par.Size = size.Value;
        }
        Lst.Add(par);
    }
Example #24
0
        public Column(string name, SqlDbType?dbType, Type type, int?length = null, object defaultValue = null, bool isPrimaryKey = false)
        {
            Type = System.Nullable.GetUnderlyingType(type) ?? type;

            if (defaultValue != null)
            {
                if (type == typeof(byte[]))
                {
                    throw new ArgumentException("Byte array column can not have default value.");
                }

                if (Type != defaultValue.GetType())
                {
                    throw new ArgumentException($"Default value ({type.Name}) must be of same type as column ({defaultValue.GetType().Name}).");
                }
            }

            Name         = name;
            Length       = length;
            IsPrimaryKey = isPrimaryKey;

            Nullable = type.CanBeNull() && !IsPrimaryKey;

            if (Type.IsEnum)
            {
                Type = typeof(Enum);
            }

            if (dbType == null)
            {
                var sqlTypeMapping = SqlTypeMap.ForNetType(Type);

                if (sqlTypeMapping == null)
                {
                    throw new ArgumentException("Can only project .NET simple types, Guid, DateTime, DateTimeOffset, TimeSpan and byte[].");
                }

                DbType = sqlTypeMapping.DbType;
            }
            else
            {
                DbType = dbType.Value;
            }

            if (!Nullable && defaultValue == null && dbType != SqlDbType.Timestamp)
            {
                DefaultValue = typeof(string).IsAssignableFrom(Type) ? "" : Activator.CreateInstance(type);
            }
            else
            {
                DefaultValue = defaultValue;
            }
        }
Example #25
0
        protected ColumnSchema ParseProperty(PropertyInfo p, int keyIndex)
        {
            Type dotnetType     = p.PropertyType;
            Type underlyingType = Nullable.GetUnderlyingType(dotnetType);

            if (underlyingType != null)
            {
                dotnetType = underlyingType;
            }
            bool isKey = p.GetCustomAttribute <KeyAttribute>() != null;
            int? pk    = isKey ? (int?)keyIndex : null;

            var jsonNested = p.GetCustomAttribute <JsonNestAttribute>();

            if (jsonNested != null)
            {
                return(this.CreateJsonNestedColumn(p, pk, jsonNested, dotnetType));
            }

            int?      maxLength = p.GetCustomAttribute <MaxLengthAttribute>()?.Length;
            SqlDbType?sqlType   = p.GetCustomAttribute <AliasTypeAttribute>()?.AsType;

            if (sqlType == null)
            {
                if (dotnetType.IsEnum)
                {
                    sqlType = SqlDbType.Int;
                }
            }

            bool nullable = underlyingType != null;

            if (dotnetType == typeof(string))
            {
                nullable  = true;
                maxLength = maxLength ?? 256;
            }

            if (pk.HasValue)
            {
                nullable = false;
            }

            return(new ColumnSchema()
            {
                Name = p.Name,
                DotnetType = dotnetType,
                Nullable = nullable,
                MaxLength = maxLength,
                KeyIndex = pk,
                SqlType = sqlType
            });
        }
Example #26
0
        protected SqlParameter GetParameter(string parameter, object value, SqlDbType?type = null)
        {
            var parameterObject = new SqlParameter(parameter, value ?? DBNull.Value)
            {
                Direction = ParameterDirection.Input
            };

            if (type != null)
            {
                parameterObject.SqlDbType = type.Value;
            }
            return(parameterObject);
        }
Example #27
0
        public SQLServerDatabaseType(string bindingName, Type type, object value) : base(type, value)
        {
            if (type == typeof(SqlDbType))
            {
                SQLDBType = (SqlDbType)value;
                TypeFound = true;
            }

            if (!TypeFound)
            {
                throw new Exception($"The parameter type for binding '{bindingName}' is not valid.");
            }
        }
        /// <summary>
        /// Adds a sink that writes log events to a table in a MSSqlServer database.
        /// Adds a column named CorrelationId to the resulting table
        /// Create a database and execute the table creation script found here
        /// https://gist.github.com/mivano/10429656
        /// or use the autoCreateSqlTable option.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="connectionString">The connection string to the database where to store the events.</param>
        /// <param name="tableName">Name of the table to store the events in.</param>
        /// <param name="schemaName">Name of the schema for the table to store the data in. The default is 'dbo'.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param>
        /// <param name="period">The time to wait between checking for event batches.</param>
        /// <param name="formatProvider">Supplies culture-specific formatting information, or null.</param>
        /// <param name="autoCreateSqlTable">Create log table with the provided name on destination sql server.</param>
        /// <param name="columnOptions"></param>
        /// <param name="correlationId">CorrelationId parameter name. Default 'CorrelationId'</param>
        /// <param name="correlationIdType">Type of the correlationId parameter. Default is System.Guid</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="T:System.ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration MsSqlServerWithCorrelation(
            this LoggerSinkConfiguration loggerConfiguration,
            string connectionString,
            string tableName,
            LogEventLevel restrictedToMinimumLevel = LogEventLevel.Verbose,
            int batchPostingLimit          = 50,
            TimeSpan?period                = null,
            IFormatProvider formatProvider = null,
            bool autoCreateSqlTable        = false,
            ColumnOptions columnOptions    = null,
            string schemaName              = "dbo",
            string correlationId           = "CorrelationId",
            SqlDbType?correlationIdType    = null
            )
        {
            if (columnOptions == null)
            {
                columnOptions = new ColumnOptions();
            }

            if (columnOptions.AdditionalColumns == null)
            {
                columnOptions.AdditionalColumns = new List <SqlColumn>();
            }

            if (!columnOptions.AdditionalColumns.Any(x => x.ColumnName.Equals(correlationId)))
            {
                columnOptions.AdditionalColumns.Add(
                    new SqlColumn
                {
                    ColumnName = correlationId,
                    DataType   = correlationIdType ?? SqlDbType.UniqueIdentifier
                });
            }

            return(loggerConfiguration.MSSqlServer(
                       connectionString,
                       new MSSqlServerSinkOptions
            {
                TableName = tableName,
                BatchPostingLimit = batchPostingLimit,
                BatchPeriod = period ?? TimeSpan.FromSeconds(5),
                AutoCreateSqlTable = autoCreateSqlTable,
                SchemaName = schemaName,
            }, null, null,
                       restrictedToMinimumLevel,
                       formatProvider,
                       columnOptions));
        }
Example #29
0
        public bool IsLengthLimited(SqlDbType?sqlType)
        {
            if (sqlType == null)
            {
                throw new ArgumentNullException(nameof(sqlType));
            }

            var mapping = Mappings.Values.SelectMany(m => m).SingleOrDefault(s => s.SqlType == sqlType);

            if (mapping == null)
            {
                throw new NotImplementedException($"No dotnet type mapping for type {sqlType}");
            }
            return(mapping.HasLength);
        }
        /// <summary>
        ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
        ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
        ///     any release. You should only use it directly in your code with extreme caution and knowing that
        ///     doing so can result in application failures when updating to a new Entity Framework Core release.
        /// </summary>
        protected SqlServerStringTypeMapping(RelationalTypeMappingParameters parameters, SqlDbType?sqlDbType)
            : base(parameters)
        {
            if (parameters.Unicode)
            {
                _maxSpecificSize = parameters.Size.HasValue && parameters.Size <= UnicodeMax ? parameters.Size.Value : UnicodeMax;
                _maxSize         = UnicodeMax;
            }
            else
            {
                _maxSpecificSize = parameters.Size.HasValue && parameters.Size <= AnsiMax ? parameters.Size.Value : AnsiMax;
                _maxSize         = AnsiMax;
            }

            _sqlDbType = sqlDbType;
        }
Example #31
0
 private void CopyMembers(DataType old)
 {
     this.name             = old.name;
     this.type             = old.type;
     this.sqlDbType        = old.sqlDbType;
     this.byteSize         = old.byteSize;
     this.scale            = old.scale;
     this.precision        = old.precision;
     this.length           = old.length;
     this.maxLength        = old.maxLength;
     this.isVarLength      = old.isVarLength;
     this.isSqlArray       = old.isSqlArray;
     this.arrayLength      = old.arrayLength;
     this.isVarArrayLength = old.isVarArrayLength;
     this.isNullable       = old.isNullable;
 }
Example #32
0
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="dbType">Тип БД</param>
 /// <param name="length">Размерность</param>
 /// <param name="scale">Разрядность</param>
 public ColumnType(SqlDbType dbType, int length, int scale)
 {
     this.sqlDbType = dbType;
     this.length = length;
     this.scale = scale;
 }
 public SqlQueryParameter(string _name, object _value, SqlDbType _db_type, int _size)
 {
     name = _name;
     value = _value;
     db_type = _db_type;
     size = _size;
 }
Example #34
0
 private void InitializeMembers()
 {
     this.name = null;
     this.type = null;
     this.sqlDbType = System.Data.SqlDbType.Int;
     this.byteSize = 0;
     this.scale = 0;
     this.precision = 0;
     this.length = 0;
     this.maxLength = 0;
     this.isVarLength = false;
     this.isSqlArray = false;
     this.arrayLength = 0;
     this.isVarArrayLength = false;
     this.isNullable = false;
 }
Example #35
0
 private void CopyMembers(DataType old)
 {
     this.name = old.name;
     this.type = old.type;
     this.sqlDbType = old.sqlDbType;
     this.byteSize = old.byteSize;
     this.scale = old.scale;
     this.precision = old.precision;
     this.length = old.length;
     this.maxLength = old.maxLength;
     this.isVarLength = old.isVarLength;
     this.isSqlArray = old.isSqlArray;
     this.arrayLength = old.arrayLength;
     this.isVarArrayLength = old.isVarArrayLength;
     this.isNullable = old.isNullable;
 }
 public SqlQueryParameter(string _name, object _value)
 {
     name = _name;
     value = _value;
     db_type = null;
     size = null;
 }