Пример #1
0
        public bool HasColumnOrAnnotation(string columnOrAnnotationName)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(columnOrAnnotationName, "columnOrAnnotationName");

            bool success;

            return(TryGetColumnIdx(columnOrAnnotationName, out success) != -1 || TryGetAnnotationIdx(columnOrAnnotationName, out success) != -1);
        }
Пример #2
0
        public static object ReadProperty(object o, string propertyName)
        {
            ArgumentValidator.ThrowIfNull(o, "o");
            ArgumentValidator.ThrowIfNullOrEmpty(propertyName, "propertyName");

            PropertyInfo propertyInfo = GetPropertyOrDie(o.GetType(), propertyName);

            return(propertyInfo.GetValue(o, null));
        }
Пример #3
0
        public static void SetProperty(object o, string propertyName, object value)
        {
            ArgumentValidator.ThrowIfNull(o, "o");
            ArgumentValidator.ThrowIfNullOrEmpty(propertyName, "propertyName");

            var propertyInfo = GetPropertyOrDie(o.GetType(), propertyName);

            SetProperty(o, propertyInfo, value);
        }
Пример #4
0
        public static T TryGet <T>(this Dictionary <string, object> d, string key)
        {
            ArgumentValidator.ThrowIfNull(d, "d");
            ArgumentValidator.ThrowIfNullOrEmpty(key, "key");

            object o;

            return(d.TryGetValue(key, out o) ? (T)o : default(T));
        }
Пример #5
0
        public bool DoesObjectExist(string dbObjectName)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(dbObjectName, "dbObjectName");

            bool exists;

            TryExecuteScalar <Int32>("SELECT OBJECT_ID({0})".FormatSql(dbObjectName), out exists);

            return(exists);
        }
Пример #6
0
        public static string Get(this Dictionary <string, string> d, string firstKey, string secondKey)
        {
            ArgumentValidator.ThrowIfNull(d, "d");
            ArgumentValidator.ThrowIfNullOrEmpty(firstKey, "firstKey");
            ArgumentValidator.ThrowIfNullOrEmpty(secondKey, "secondKey");

            string v;

            return(d.TryGetValue(firstKey, out v) ? v : d[secondKey]);
        }
Пример #7
0
        private void SetColumnAsKey(string name)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(name, "name");

            var c = ColumnsByName[name];

            c.IsKey       = true;
            c.AllowDbNull = false;
            LoadKeyNames();
        }
Пример #8
0
        public static Database ConnectToMasterDb(string connectionStringToServer)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(connectionStringToServer, "connectionStringToServer");

            var b = new SqlConnectionStringBuilder(connectionStringToServer)
            {
                InitialCatalog = "master"
            };
            var masterDb = new Database(b.ToString(), typeof(Database).FullName);

            return(masterDb);
        }
Пример #9
0
        public static string AddApplicationNameToConnectionString(string connectionString, string applicationName)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(connectionString, "connectionString");
            ArgumentValidator.ThrowIfNullOrEmpty(applicationName, "applicationName");

            var b = new SqlConnectionStringBuilder(connectionString)
            {
                ApplicationName = applicationName
            };

            return(b.ToString());
        }
Пример #10
0
        public static bool DoesDbExist(string connectionStringToDb)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(connectionStringToDb, "connectionStringToDb");

            var masterDb = ConnectToMasterDb(connectionStringToDb);
            var dbName   = DbNameFromConnectionString(connectionStringToDb);

            bool exists;

            masterDb.TryExecuteScalar <Int16>("SELECT DB_ID({0})".FormatSql(dbName), out exists);
            return(exists);
        }
Пример #11
0
        public static void ThrowIfConnectionStringLacksAppName(string connectionString)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(connectionString, "connectionString");

            var b = new SqlConnectionStringBuilder(connectionString);

            if (string.IsNullOrEmpty(b.ApplicationName))
            {
                throw new ArgumentException("You have not specified an ApplicationName in your connection string. This makes it very "
                                            + "hard to profile and troubleshoot SQL Server, because connections appear as a generic '.NET Application' instead "
                                            + "of your actual app. Please add an 'Application Name=YourAppName;' field to your connection string.", "connectionString");
            }
        }
Пример #12
0
        public TableChanges(string tableName, Database database)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(tableName, "tableName");
            ArgumentValidator.ThrowIfNull(database, "database");

            Annotations      = new List <string>();
            m_rowCacheByKeys = new Dictionary <object, object>();
            m_tableName      = tableName;
            m_rowChanges     = new List <RowChange>(32);
            m_database       = database;

            InitTableSchema();
        }
Пример #13
0
        public List <T> ExecuteToEntityList <T>(string query)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(query, "query");
            var list = new List <T>();

            WhileReading(query, r =>
            {
                var item = (T)ReflectionHelper.CreateInstance(typeof(T));
                ReflectionHelper.ApplyDataRecordToObject(r, item);
                list.Add(item);
            });
            return(list);
        }
        public static String GetAttributeOrDefault(this XmlElement xmlElement, String attributeName, String defaultValue)
        {
            ArgumentValidator.ThrowIfNull(xmlElement, "xmlElement");
            ArgumentValidator.ThrowIfNullOrEmpty(attributeName, "attributeName");

            XmlAttribute attr = xmlElement.Attributes[attributeName];

            if (null == attr)
            {
                return(defaultValue);
            }

            return(attr.Value);
        }
Пример #15
0
        public static void DropDatabase(string connectionStringToDb)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(connectionStringToDb, "connectionStringToDb");
            var databaseName = DbNameFromConnectionString(connectionStringToDb);

            var masterDb          = ConnectToMasterDb(connectionStringToDb);
            var activeConnections = masterDb.ExecuteToList <short>("SELECT SPId FROM MASTER..SysProcesses WHERE DBId = DB_ID({0}) AND cmd <> 'CHECKPOINT'".FormatSql(databaseName));

            foreach (var id in activeConnections)
            {
                masterDb.ExecuteNonQuery("KILL {0}".FormatSql(id));
            }

            masterDb.ExecuteNonQuery("IF (DB_ID({0}) IS NOT NULL) DROP DATABASE {0:name}".FormatSql(databaseName));
        }
Пример #16
0
        public static PropertyInfo GetPropertyOrDie(Type t, string propertyName, BindingFlags flags)
        {
            ArgumentValidator.ThrowIfNull(t, "t");
            ArgumentValidator.ThrowIfNullOrEmpty(propertyName, "propertyName");

            PropertyInfo propertyInfo = t.GetProperty(propertyName, flags);

            if (propertyInfo == null)
            {
                string msg = "Failed to get property {0} on type {1} with binding flags {2}".Fi(propertyName, t.FullName, flags);
                throw new AssertionViolationException(msg);
            }

            return(propertyInfo);
        }
Пример #17
0
        public static object InvokeStatic(Type t, string methodName, params object[] arguments)
        {
            ArgumentValidator.ThrowIfNull(t, "t");
            ArgumentValidator.ThrowIfNullOrEmpty(methodName, "methodName");

            bool foundMethod;
            var  r = Invoke(t, null, methodName, PublicStaticIgnoreCase, out foundMethod, arguments);

            if (!foundMethod)
            {
                throw new AssertionViolationException("Could not find static method {0} in type {1}".Fi(methodName, t.FullName));
            }

            return(r);
        }
        public static T TryGet <T>(this IDataRecord r, string columnName)
        {
            ArgumentValidator.ThrowIfNull(r, "r");
            ArgumentValidator.ThrowIfNullOrEmpty(columnName, "columnName");

            var idx = r.GetOrdinalOrMinusOne(columnName);

            if (-1 == idx)
            {
                return(default(T));
            }

            var v = r[idx];

            return(Convert.IsDBNull(v) ? default(T) : (T)v);
        }
Пример #19
0
        public List <T> ExecuteToList <T>(string query)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(query, "query");

            return((List <T>)WithDataReader(query, r =>
            {
                var list = new List <T>();

                while (r.Read())
                {
                    list.Add((T)r[0]);
                }

                return list;
            }));
        }
Пример #20
0
        public int TryGetAnnotationIdx(string annotation, out bool success)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(annotation, "annotation");

            for (int i = 0; i < Annotations.Count; i++)
            {
                if (Annotations[i].OicEquals(annotation))
                {
                    success = true;
                    return(i);
                }
            }

            success = false;
            return(-1);
        }
Пример #21
0
        public T RetrieveOrInsert <T>(string tableName, string columnToRetrieve, T defaultValue, string[] keyNames, object[] keyValues)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(tableName, "tableName");
            ArgumentValidator.ThrowIfNullOrEmpty(columnToRetrieve, "columnToRetrieve");
            ArgumentValidator.ThrowIfNull(keyNames, "keyNames");
            ArgumentValidator.ThrowIfNull(keyValues, "keyValues");

            if (keyNames.Length != keyValues.Length)
            {
                throw new ArgumentException(("The length for the keyNames array is {0}, which is different than the "
                                             + "length for the keyValues array of {1}. The arrays must have the same length: each value corresponds "
                                             + "to a given key name.").Fi(keyNames.Length, keyValues.Length));
            }

            var queryBuilder = new StringBuilder(128);

            queryBuilder.AppendFormat("SELECT {{0}} FROM {0} WHERE ", tableName);

            var sqlKeyValues = new string[keyValues.Length];

            for (var i = 0; i < keyNames.Length; i++)
            {
                sqlKeyValues[i] = keyValues[i].ToSql();
                queryBuilder.AppendFormat("{0} = {1} AND ", keyNames[i], sqlKeyValues[i]);
            }

            queryBuilder.Length -= 4;

            var selectQuery = queryBuilder.ToString();

            var cntFound = ExecuteScalar <int>(selectQuery.Fi("COUNT(1)"));

            if (0 == cntFound)
            {
                queryBuilder.Length = 0;

                queryBuilder.AppendFormat("INSERT {0} ({1},{2}) VALUES ({3},{4})", tableName, keyNames.Join(","), columnToRetrieve,
                                          sqlKeyValues.Join(","), defaultValue.ToSql());

                ExecuteNonQuery(queryBuilder.ToString());
                // we could return here and avoid the query to the database, but I'd rather go ahead and re-select the value
                // we just inserted to make sure everything always works the same (insert is successful, there are no
                // conversion errors, the return value for the first call is guaranteed to be identical to the second, etc.)
            }

            return(ExecuteScalar <T>(selectQuery.Fi(columnToRetrieve)));
        }
        public static int GetOrdinalOrMinusOne(this IDataRecord r, string columnName)
        {
            ArgumentValidator.ThrowIfNull(r, "r");
            ArgumentValidator.ThrowIfNullOrEmpty(columnName, "columnName");

            var cntFields = r.FieldCount;

            for (var i = 0; i < cntFields; i++)
            {
                if (r.GetName(i).OicEquals(columnName))
                {
                    return(i);
                }
            }

            return(-1);
        }
Пример #23
0
        public VarBinaryHelper(SqlConnection connection, string tableName, string columnName, string whereClause)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(tableName, "tableName");
            ArgumentValidator.ThrowIfNullOrEmpty(columnName, "columnName");
            ArgumentValidator.ThrowIfNullOrEmpty(whereClause, "whereClause");
            if (connection.State != ConnectionState.Open)
            {
                throw new ArgumentException("The connection must be open", "connection");
            }

            this.m_connection = connection;
            this.Length       = GetLength(tableName, columnName, whereClause);

            this.m_readCommand       = CreateReadCommand(tableName, columnName, whereClause);
            this.m_writeCommand      = CreateWriteCommand(tableName, columnName, whereClause);
            this.m_initializeCommand = CreateInitializeCommand(tableName, columnName, whereClause);
        }
Пример #24
0
        public static void TrySetProperty(object o, string propertyName, object value)
        {
            ArgumentValidator.ThrowIfNull(o, "o");
            ArgumentValidator.ThrowIfNullOrEmpty(propertyName, "propertyName");

            try
            {
                var propertyInfo = TryGetProperty(o.GetType(), propertyName, InstanceAllInclusiveIgnoreCase);
                if (null == propertyInfo)
                {
                    return;
                }


                SetProperty(o, propertyInfo, value);
            }
            catch { }
        }
Пример #25
0
        public static FileInfo GetFileOrDie(this DirectoryInfo dir, string fileName)
        {
            ArgumentValidator.ThrowIfNull(dir, "dir");
            ArgumentValidator.ThrowIfNullOrEmpty(fileName, "fileName");

            var filez = dir.GetFiles(fileName);

            if (0 == filez.Length)
            {
                var msg = "Failed to find file '{0}' in folder '{1}'".Fi(fileName, dir.FullName);
                throw new FileNotFoundException(msg);
            }

            if (1 < filez.Length)
            {
                var msg = "Expected to find one file name '{0}' in folder '{1}', but multiple matches were found!".Fi(fileName, dir.FullName);
                throw new AssertionViolationException(msg);
            }

            return(filez[0]);
        }
Пример #26
0
        public object WithCommand(string sqlStatement, Func <DbCommand, object> doSomething)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(sqlStatement, "sqlStatement");
            ArgumentValidator.ThrowIfNull(doSomething, "doSomething");

            return(WithConnection(conn =>
            {
                var cmd = conn.CreateCommand();
                cmd.CommandText = sqlStatement;
                cmd.CommandType = CommandType.Text;
                cmd.Connection = conn;
                cmd.Transaction = _transactionResolver.GetTransactionOrNull();
                cmd.CommandTimeout = CommandTimeoutInSeconds;
                try
                {
                    return doSomething(cmd);
                }
                catch (SqlException ex)
                {
                    throw new DatabaseException("Error running statement:\n{0}\n{1}\n\n with user {2}".Fi(sqlStatement, ex.Message, _userName), ex);
                }
            }));
        }
Пример #27
0
        private HttpCompression(string name)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(name, "name");

            this.Name = name;
        }
Пример #28
0
        public object GetAnnotation(string annotation)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(annotation, "annotation");

            return(this.GetAnnotation(this.TableChanges.GetAnnotationIdx(annotation)));
        }
Пример #29
0
        public static DateTime LocalFromExtJs(string extjsIso8601Date)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(extjsIso8601Date, "extjsIso8601Date");

            return(DateTime.ParseExact(extjsIso8601Date, ExtJsIso8601, CultureInfo.InvariantCulture));
        }
Пример #30
0
        public object ParseJson(string json)
        {
            ArgumentValidator.ThrowIfNullOrEmpty(json, "json");

            return(ParseJson(new JsonTextReader(new StringReader(json))));
        }