Updated PetaPoco

Upped IIS's priority
Added Byte multiplier to extention method.
This commit is contained in:
kay.one 2011-07-17 12:32:58 -07:00
parent 276e01166a
commit b11a449f65
6 changed files with 1697 additions and 1750 deletions

View File

@ -1,144 +0,0 @@
<Configuration>
<CodeStyleSettings>
<ExternalPath IsNull="False">
</ExternalPath>
<Sharing>SOLUTION</Sharing>
<CSharp>
<FormatSettings>
<MODIFIERS_ORDER IsNull="False">
<Item>public</Item>
<Item>protected</Item>
<Item>internal</Item>
<Item>private</Item>
<Item>new</Item>
<Item>abstract</Item>
<Item>virtual</Item>
<Item>override</Item>
<Item>sealed</Item>
<Item>static</Item>
<Item>readonly</Item>
<Item>extern</Item>
<Item>unsafe</Item>
<Item>volatile</Item>
</MODIFIERS_ORDER>
<WRAP_LIMIT>140</WRAP_LIMIT>
</FormatSettings>
<UsingsSettings />
<Naming2>
<EventHandlerPatternLong>$object$_On$event$</EventHandlerPatternLong>
<EventHandlerPatternShort>$event$Handler</EventHandlerPatternShort>
</Naming2>
</CSharp>
<VB>
<FormatSettings />
<ImportsSettings />
<Naming2>
<EventHandlerPatternLong>$object$_On$event$</EventHandlerPatternLong>
<EventHandlerPatternShort>$event$Handler</EventHandlerPatternShort>
</Naming2>
</VB>
<Web>
<Naming2 />
</Web>
<Xaml>
<Naming2 />
</Xaml>
<XML>
<FormatSettings />
</XML>
<GenerateMemberBody />
<Naming2>
<EventHandlerPatternLong>$object$_On$event$</EventHandlerPatternLong>
<EventHandlerPatternShort>$event$Handler</EventHandlerPatternShort>
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="PrivateStaticReadonly" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="TypesAndNamespaces" />
<PredefinedRule Inspect="True" Prefix="I" Suffix="" Style="AaBb" ElementKind="Interfaces" />
<PredefinedRule Inspect="True" Prefix="T" Suffix="" Style="AaBb" ElementKind="TypeParameters" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="MethodPropertyEvent" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="aaBb" ElementKind="Locals" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="aaBb" ElementKind="LocalConstants" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="aaBb" ElementKind="Parameters" />
<PredefinedRule Inspect="True" Prefix="_" Suffix="" Style="aaBb" ElementKind="PublicFields" />
<PredefinedRule Inspect="True" Prefix="_" Suffix="" Style="aaBb" ElementKind="PrivateInstanceFields" />
<PredefinedRule Inspect="True" Prefix="_" Suffix="" Style="aaBb" ElementKind="PrivateStaticFields" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="Constants" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="PrivateConstants" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="StaticReadonly" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="EnumMember" />
<PredefinedRule Inspect="True" Prefix="" Suffix="" Style="AaBb" ElementKind="Other" />
<Abbreviation Text="IIS" />
<Abbreviation Text="SQ" />
</Naming2>
</CodeStyleSettings>
<CustomStructuralPatterns>
<Pattern Severity="SUGGESTION">
<Comment>Replace with FluentAssertion</Comment>
<ReplacePattern>$arg$.Should().BeTrue();</ReplacePattern>
<SearchPattern><![CDATA[Assert.IsTrue($arg$);
]]></SearchPattern>
<Params />
<Placeholders>
<ArgumentPlaceholder Name="excpected" Minimal="1" Maximal="1" />
</Placeholders>
</Pattern>
<Pattern Severity="SUGGESTION">
<Comment>Replace with FluentAssertion</Comment>
<ReplacePattern>$arg$.Should().BeFalse();</ReplacePattern>
<SearchPattern><![CDATA[Assert.IsFalse($arg$);
]]></SearchPattern>
<Params />
<Placeholders>
<ArgumentPlaceholder Name="excpected" Minimal="1" Maximal="1" />
</Placeholders>
</Pattern>
<Pattern Severity="SUGGESTION">
<ReplacePattern>$actual$.Should().Be($excpected$);</ReplacePattern>
<SearchPattern><![CDATA[Assert.AreEqual($actual$, $excpected$);
]]></SearchPattern>
<Params>
<IgnoreBracesInSingleStatementBlocks>False</IgnoreBracesInSingleStatementBlocks>
<IgnoreParanthesisInExpressions>False</IgnoreParanthesisInExpressions>
<SmartMatchAssociativeExpressions>False</SmartMatchAssociativeExpressions>
<TreatReversedBinaryExpressionsEquivalent>Never</TreatReversedBinaryExpressionsEquivalent>
</Params>
<Placeholders>
<ArgumentPlaceholder Name="excpected" Minimal="1" Maximal="1" />
<ArgumentPlaceholder Name="actual" Minimal="1" Maximal="1" />
</Placeholders>
</Pattern>
<Pattern Severity="HINT">
<ReplacePattern>$excpected$.Should().Be($actual$);</ReplacePattern>
<SearchPattern><![CDATA[$actual$.Should().Be($excpected$);
]]></SearchPattern>
<Params />
<Placeholders>
<ArgumentPlaceholder Name="excpected" Minimal="1" Maximal="1" />
<ArgumentPlaceholder Name="actual" Minimal="1" Maximal="1" />
</Placeholders>
</Pattern>
<Pattern Severity="SUGGESTION">
<ReplacePattern>$arg$.Should().NotBeNull();</ReplacePattern>
<SearchPattern>Assert.IsNotNull($arg$);</SearchPattern>
<Params />
<Placeholders>
<ArgumentPlaceholder Name="arg" Minimal="1" Maximal="1" />
</Placeholders>
</Pattern>
<Pattern Severity="SUGGESTION">
<ReplacePattern>$arg$.Should().NotBeEmpty();</ReplacePattern>
<SearchPattern>Assert.IsNotEmpty($arg$);</SearchPattern>
<Params />
<Placeholders>
<ArgumentPlaceholder Name="arg" Minimal="1" Maximal="1" />
</Placeholders>
</Pattern>
<Pattern Severity="SUGGESTION">
<ReplacePattern>$arg$.Should().BeEmpty();</ReplacePattern>
<SearchPattern>Assert.IsEmpty($arg$);</SearchPattern>
<Params />
<Placeholders>
<ArgumentPlaceholder Name="arg" Minimal="1" Maximal="1" />
</Placeholders>
</Pattern>
</CustomStructuralPatterns>
</Configuration>

View File

@ -53,7 +53,7 @@ namespace NzbDrone.Core.Datastore
connection = ProfiledDbConnection.Get(sqliteConnection); connection = ProfiledDbConnection.Get(sqliteConnection);
} }
var db = new Database(connection); var db = new Database(connection, Database.DBType.SqlServerCE);
db.ForceDateTimesToUtc = false; db.ForceDateTimesToUtc = false;
if (connection.State != ConnectionState.Open) if (connection.State != ConnectionState.Open)

View File

@ -8,7 +8,7 @@
* and Adam Schroder (@schotime) for lots of suggestions, improvements and Oracle support * and Adam Schroder (@schotime) for lots of suggestions, improvements and Oracle support
*/ */
#define PETAPOCO_NO_DYNAMIC //in your project settings on .NET 3.5 //#define PETAPOCO_NO_DYNAMIC //in your project settings on .NET 3.5
using System; using System;
using System.Collections; using System.Collections;
@ -89,7 +89,7 @@ namespace PetaPoco
[AttributeUsage(AttributeTargets.Property)] [AttributeUsage(AttributeTargets.Property)]
public class VersionColumnAttribute : ColumnAttribute public class VersionColumnAttribute : ColumnAttribute
{ {
public VersionColumnAttribute() {} public VersionColumnAttribute() { }
public VersionColumnAttribute(string name) : base(name) { } public VersionColumnAttribute(string name) : base(name) { }
} }
@ -128,7 +128,7 @@ namespace PetaPoco
{ {
void GetTableInfo(Type t, TableInfo ti); void GetTableInfo(Type t, TableInfo ti);
bool MapPropertyToColumn(PropertyInfo pi, ref string columnName, ref bool resultColumn); bool MapPropertyToColumn(PropertyInfo pi, ref string columnName, ref bool resultColumn);
Func<object, object> GetFromDbConverter(PropertyInfo pi, Type sourceType); Func<object, object> GetFromDbConverter(PropertyInfo pi, Type SourceType);
Func<object, object> GetToDbConverter(Type SourceType); Func<object, object> GetToDbConverter(Type SourceType);
} }
@ -145,7 +145,7 @@ namespace PetaPoco
{ {
return true; return true;
} }
public virtual Func<object, object> GetFromDbConverter(PropertyInfo pi, Type sourceType) public virtual Func<object, object> GetFromDbConverter(PropertyInfo pi, Type SourceType)
{ {
return null; return null;
} }
@ -240,7 +240,9 @@ namespace PetaPoco
void Dispose(); void Dispose();
IDbConnection Connection { get; } IDbConnection Connection { get; }
ITransaction GetTransaction(); ITransaction GetTransaction();
Transaction GetTransaction(IsolationLevel? isolationLevel);
void BeginTransaction(); void BeginTransaction();
void BeginTransaction(IsolationLevel? isolationLevel);
void AbortTransaction(); void AbortTransaction();
void CompleteTransaction(); void CompleteTransaction();
object Insert(string tableName, string primaryKeyName, bool autoIncrement, object poco); object Insert(string tableName, string primaryKeyName, bool autoIncrement, object poco);
@ -274,11 +276,14 @@ namespace PetaPoco
{ {
public const string MsSqlClientProvider = "System.Data.SqlClient"; public const string MsSqlClientProvider = "System.Data.SqlClient";
public Database(IDbConnection connection) public Database(IDbConnection connection) : this(connection, DBType.NotSet) { }
public Database(IDbConnection connection, DBType dbType)
{ {
_sharedConnection = connection; _sharedConnection = connection;
_connectionString = connection.ConnectionString; _connectionString = connection.ConnectionString;
_sharedConnectionDepth = 2; // Prevent closing external connection _sharedConnectionDepth = 2; // Prevent closing external connection
_dbType = dbType;
CommonConstruct(); CommonConstruct();
} }
@ -320,8 +325,9 @@ namespace PetaPoco
CommonConstruct(); CommonConstruct();
} }
enum DBType public enum DBType
{ {
NotSet,
SqlServer, SqlServer,
SqlServerCE, SqlServerCE,
MySql, MySql,
@ -329,7 +335,8 @@ namespace PetaPoco
Oracle, Oracle,
SQLite SQLite
} }
DBType _dbType = DBType.SqlServerCE;
private DBType _dbType = DBType.NotSet;
// Common initialization // Common initialization
private void CommonConstruct() private void CommonConstruct()
@ -341,12 +348,21 @@ namespace PetaPoco
if (_providerName != null) if (_providerName != null)
_factory = DbProviderFactories.GetFactory(_providerName); _factory = DbProviderFactories.GetFactory(_providerName);
string dbtype = (_factory==null ? _sharedConnection.GetType() : _factory.GetType()).Name; if (_dbType == DBType.NotSet)
if (dbtype.StartsWith("MySql")) _dbType = DBType.MySql; {
else if (dbtype.StartsWith("SqlCe")) _dbType = DBType.SqlServerCE; _dbType = DBType.SqlServer;
else if (dbtype.StartsWith("Npgsql")) _dbType = DBType.PostgreSQL; string dbtype = (_factory == null ? _sharedConnection.GetType() : _factory.GetType()).Name;
else if (dbtype.StartsWith("Oracle")) _dbType = DBType.Oracle; if (dbtype.StartsWith("MySql"))
else if (dbtype.StartsWith("SQLite")) _dbType = DBType.SQLite; _dbType = DBType.MySql;
else if (dbtype.StartsWith("SqlCe"))
_dbType = DBType.SqlServerCE;
else if (dbtype.StartsWith("Npgsql"))
_dbType = DBType.PostgreSQL;
else if (dbtype.StartsWith("Oracle"))
_dbType = DBType.Oracle;
else if (dbtype.StartsWith("SQLite"))
_dbType = DBType.SQLite;
}
if (_dbType == DBType.MySql && _connectionString != null && _connectionString.IndexOf("Allow User Variables=true") >= 0) if (_dbType == DBType.MySql && _connectionString != null && _connectionString.IndexOf("Allow User Variables=true") >= 0)
_paramPrefix = "?"; _paramPrefix = "?";
@ -409,24 +425,34 @@ namespace PetaPoco
// Helper to create a transaction scope // Helper to create a transaction scope
public ITransaction GetTransaction() public ITransaction GetTransaction()
{ {
return new Transaction(this); return GetTransaction(null);
}
public Transaction GetTransaction(IsolationLevel? isolationLevel)
{
return new Transaction(this, isolationLevel);
} }
// Use by derived repo generated by T4 templates // Use by derived repo generated by T4 templates
public virtual void OnBeginTransaction() { } public virtual void OnBeginTransaction() { }
public virtual void OnEndTransaction() { } public virtual void OnEndTransaction() { }
public void BeginTransaction()
{
BeginTransaction(null);
}
// Start a new transaction, can be nested, every call must be // Start a new transaction, can be nested, every call must be
// matched by a call to AbortTransaction or CompleteTransaction // matched by a call to AbortTransaction or CompleteTransaction
// Use `using (var scope=db.Transaction) { scope.Complete(); }` to ensure correct semantics // Use `using (var scope=db.Transaction) { scope.Complete(); }` to ensure correct semantics
public void BeginTransaction() public void BeginTransaction(IsolationLevel? isolationLevel)
{ {
_transactionDepth++; _transactionDepth++;
if (_transactionDepth == 1) if (_transactionDepth == 1)
{ {
OpenSharedConnection(); OpenSharedConnection();
_transaction = _sharedConnection.BeginTransaction(); _transaction = isolationLevel == null ? _sharedConnection.BeginTransaction() : _sharedConnection.BeginTransaction(isolationLevel.Value);
_transactionCancelled = false; _transactionCancelled = false;
OnBeginTransaction(); OnBeginTransaction();
} }
@ -540,10 +566,10 @@ namespace PetaPoco
void AddParam(IDbCommand cmd, object item, string ParameterPrefix) void AddParam(IDbCommand cmd, object item, string ParameterPrefix)
{ {
// Convert value to from poco type to db type // Convert value to from poco type to db type
if (Database.Mapper != null && item!=null) if (Database.Mapper != null && item != null)
{ {
var fn = Database.Mapper.GetToDbConverter(item.GetType()); var fn = Database.Mapper.GetToDbConverter(item.GetType());
if (fn!=null) if (fn != null)
item = fn(item); item = fn(item);
} }
@ -810,7 +836,7 @@ namespace PetaPoco
public void BuildPageQueries<T>(long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage) public void BuildPageQueries<T>(long skip, long take, string sql, ref object[] args, out string sqlCount, out string sqlPage)
{ {
// Add auto select clause // Add auto select clause
sql=AddSelectClause<T>(sql); sql = AddSelectClause<T>(sql);
// Split the SQL into the bits we need // Split the SQL into the bits we need
string sqlSelectRemoved, sqlOrderBy; string sqlSelectRemoved, sqlOrderBy;
@ -828,8 +854,8 @@ namespace PetaPoco
sqlSelectRemoved = "peta_inner.* FROM (SELECT " + sqlSelectRemoved + ") peta_inner"; sqlSelectRemoved = "peta_inner.* FROM (SELECT " + sqlSelectRemoved + ") peta_inner";
} }
sqlPage = string.Format("SELECT * FROM (SELECT ROW_NUMBER() OVER ({0}) peta_rn, {1}) peta_paged WHERE peta_rn>@{2} AND peta_rn<=@{3}", sqlPage = string.Format("SELECT * FROM (SELECT ROW_NUMBER() OVER ({0}) peta_rn, {1}) peta_paged WHERE peta_rn>@{2} AND peta_rn<=@{3}",
sqlOrderBy==null ? "ORDER BY (SELECT NULL)" : sqlOrderBy, sqlSelectRemoved, args.Length, args.Length + 1); sqlOrderBy == null ? "ORDER BY (SELECT NULL)" : sqlOrderBy, sqlSelectRemoved, args.Length, args.Length + 1);
args = args.Concat(new object[] { skip, skip+take }).ToArray(); args = args.Concat(new object[] { skip, skip + take }).ToArray();
} }
else if (_dbType == DBType.SqlServerCE) else if (_dbType == DBType.SqlServerCE)
{ {
@ -848,7 +874,7 @@ namespace PetaPoco
public Page<T> Page<T>(long page, long itemsPerPage, string sql, params object[] args) public Page<T> Page<T>(long page, long itemsPerPage, string sql, params object[] args)
{ {
string sqlCount, sqlPage; string sqlCount, sqlPage;
BuildPageQueries<T>((page-1)*itemsPerPage, itemsPerPage, sql, ref args, out sqlCount, out sqlPage); BuildPageQueries<T>((page - 1) * itemsPerPage, itemsPerPage, sql, ref args, out sqlCount, out sqlPage);
// Save the one-time command time out and use it for both queries // Save the one-time command time out and use it for both queries
int saveTimeout = OneTimeCommandTimeout; int saveTimeout = OneTimeCommandTimeout;
@ -898,6 +924,43 @@ namespace PetaPoco
return SkipTake<T>(skip, take, sql.SQL, sql.Arguments); return SkipTake<T>(skip, take, sql.SQL, sql.Arguments);
} }
public Dictionary<TKey, TValue> Dictionary<TKey, TValue>(Sql Sql)
{
return Dictionary<TKey, TValue>(Sql.SQL, Sql.Arguments);
}
public Dictionary<TKey, TValue> Dictionary<TKey, TValue>(string sql, params object[] args)
{
var newDict = new Dictionary<TKey, TValue>();
bool isConverterSet = false;
Func<object, object> converter1 = x => x, converter2 = x => x;
foreach (var line in Query<Dictionary<string, object>>(sql, args))
{
object key = line.ElementAt(0).Value;
object value = line.ElementAt(1).Value;
if (isConverterSet == false)
{
converter1 = PocoData.GetConverter(ForceDateTimesToUtc, null, typeof(TKey), key.GetType()) ?? (x => x);
converter2 = PocoData.GetConverter(ForceDateTimesToUtc, null, typeof(TValue), value.GetType()) ?? (x => x);
isConverterSet = true;
}
var keyConverted = (TKey)Convert.ChangeType(converter1(key), typeof(TKey));
var valueType = Nullable.GetUnderlyingType(typeof(TValue)) ?? typeof(TValue);
var valConv = converter2(value);
var valConverted = valConv != null ? (TValue)Convert.ChangeType(valConv, valueType) : default(TValue);
if (keyConverted != null)
{
newDict.Add(keyConverted, valConverted);
}
}
return newDict;
}
// Return an enumerable collection of pocos // Return an enumerable collection of pocos
public IEnumerable<T> Query<T>(string sql, params object[] args) public IEnumerable<T> Query<T>(string sql, params object[] args)
{ {
@ -966,8 +1029,8 @@ namespace PetaPoco
// Multi Query // Multi Query
public IEnumerable<TRet> Query<T1, T2, TRet>(Func<T1, T2, TRet> cb, string sql, params object[] args) { return Query<TRet>(new Type[] { typeof(T1), typeof(T2) }, cb, sql, args); } public IEnumerable<TRet> Query<T1, T2, TRet>(Func<T1, T2, TRet> cb, string sql, params object[] args) { return Query<TRet>(new Type[] { typeof(T1), typeof(T2) }, cb, sql, args); }
public IEnumerable<TRet> Query<T1, T2, T3, TRet>(Func<T1, T2, T3, TRet> cb, string sql, params object[] args) { return Query<TRet>(new Type[] { typeof(T1), typeof(T2), typeof(T3)}, cb, sql, args); } public IEnumerable<TRet> Query<T1, T2, T3, TRet>(Func<T1, T2, T3, TRet> cb, string sql, params object[] args) { return Query<TRet>(new Type[] { typeof(T1), typeof(T2), typeof(T3) }, cb, sql, args); }
public IEnumerable<TRet> Query<T1, T2, T3, T4, TRet>(Func<T1, T2, T3, T4, TRet> cb, string sql, params object[] args) { return Query<TRet>(new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4)}, cb, sql, args); } public IEnumerable<TRet> Query<T1, T2, T3, T4, TRet>(Func<T1, T2, T3, T4, TRet> cb, string sql, params object[] args) { return Query<TRet>(new Type[] { typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, cb, sql, args); }
// Multi Fetch (SQL builder) // Multi Fetch (SQL builder)
public List<TRet> Fetch<T1, T2, TRet>(Func<T1, T2, TRet> cb, Sql sql) { return Query<T1, T2, TRet>(cb, sql.SQL, sql.Arguments).ToList(); } public List<TRet> Fetch<T1, T2, TRet>(Func<T1, T2, TRet> cb, Sql sql) { return Query<T1, T2, TRet>(cb, sql.SQL, sql.Arguments).ToList(); }
@ -1121,7 +1184,7 @@ namespace PetaPoco
// Call each delegate // Call each delegate
var dels = new List<Delegate>(); var dels = new List<Delegate>();
int pos = 0; int pos = 0;
for (int i=0; i<types.Length; i++) for (int i = 0; i < types.Length; i++)
{ {
// Add to list of delegates to call // Add to list of delegates to call
var del = FindSplitPoint(types[i], i + 1 < types.Length ? types[i + 1] : null, sql, r, ref pos); var del = FindSplitPoint(types[i], i + 1 < types.Length ? types[i + 1] : null, sql, r, ref pos);
@ -1225,7 +1288,7 @@ namespace PetaPoco
var factory = GetMultiPocoFactory<TRet>(types, sql, r); var factory = GetMultiPocoFactory<TRet>(types, sql, r);
if (cb == null) if (cb == null)
cb = GetAutoMapper(types.ToArray()); cb = GetAutoMapper(types.ToArray());
bool bNeedTerminator=false; bool bNeedTerminator = false;
using (r) using (r)
{ {
while (true) while (true)
@ -1402,7 +1465,7 @@ namespace PetaPoco
continue; continue;
// Don't insert the primary key (except under oracle where we need bring in the next sequence value) // Don't insert the primary key (except under oracle where we need bring in the next sequence value)
if (autoIncrement && primaryKeyName != null && string.Compare(i.Key, primaryKeyName, true)==0) if (autoIncrement && primaryKeyName != null && string.Compare(i.Key, primaryKeyName, true) == 0)
{ {
if (_dbType == DBType.Oracle && !string.IsNullOrEmpty(pd.TableInfo.SequenceName)) if (_dbType == DBType.Oracle && !string.IsNullOrEmpty(pd.TableInfo.SequenceName))
{ {
@ -1591,7 +1654,7 @@ namespace PetaPoco
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
var index = 0; var index = 0;
var pd = PocoData.ForObject(poco,primaryKeyName); var pd = PocoData.ForObject(poco, primaryKeyName);
string versionName = null; string versionName = null;
object versionValue = null; object versionValue = null;
@ -1653,11 +1716,12 @@ namespace PetaPoco
OnExecutedCommand(cmd); OnExecutedCommand(cmd);
// Set Version // Set Version
if (!string.IsNullOrEmpty(versionName)) { if (!string.IsNullOrEmpty(versionName))
{
PocoColumn pc; PocoColumn pc;
if (pd.Columns.TryGetValue(versionName, out pc)) if (pd.Columns.TryGetValue(versionName, out pc))
{ {
pc.PropertyInfo.SetValue(poco, Convert.ChangeType(Convert.ToInt64(versionValue)+1, pc.PropertyInfo.PropertyType), null); pc.PropertyInfo.SetValue(poco, Convert.ChangeType(Convert.ToInt64(versionValue) + 1, pc.PropertyInfo.PropertyType), null);
} }
} }
@ -1785,7 +1849,7 @@ namespace PetaPoco
// Do it // Do it
var index = 0; var index = 0;
var sql = string.Format("DELETE FROM {0} WHERE {1}", tableName, BuildPrimaryKeySql(primaryKeyValuePairs, ref index)); var sql = string.Format("DELETE FROM {0} WHERE {1}", tableName, BuildPrimaryKeySql(primaryKeyValuePairs, ref index));
return Execute(sql, primaryKeyValuePairs.Select(x=>x.Value).ToArray()); return Execute(sql, primaryKeyValuePairs.Select(x => x.Value).ToArray());
} }
public int Delete(object poco) public int Delete(object poco)
@ -1915,7 +1979,7 @@ namespace PetaPoco
cmd.CommandTimeout = OneTimeCommandTimeout; cmd.CommandTimeout = OneTimeCommandTimeout;
OneTimeCommandTimeout = 0; OneTimeCommandTimeout = 0;
} }
else if (CommandTimeout!=0) else if (CommandTimeout != 0)
{ {
cmd.CommandTimeout = CommandTimeout; cmd.CommandTimeout = CommandTimeout;
} }
@ -1977,10 +2041,10 @@ namespace PetaPoco
} }
public class ExpandoColumn : PocoColumn public class ExpandoColumn : PocoColumn
{ {
public override void SetValue(object target, object val) { (target as IDictionary<string, object>)[ColumnName]=val; } public override void SetValue(object target, object val) { (target as IDictionary<string, object>)[ColumnName] = val; }
public override object GetValue(object target) public override object GetValue(object target)
{ {
object val=null; object val = null;
(target as IDictionary<string, object>).TryGetValue(ColumnName, out val); (target as IDictionary<string, object>).TryGetValue(ColumnName, out val);
return val; return val;
} }
@ -2002,7 +2066,7 @@ namespace PetaPoco
pd.TableInfo.AutoIncrement = true; pd.TableInfo.AutoIncrement = true;
foreach (var col in (o as IDictionary<string, object>).Keys) foreach (var col in (o as IDictionary<string, object>).Keys)
{ {
if (col!=primaryKeyName) if (col != primaryKeyName)
pd.Columns.Add(col, new ExpandoColumn() { ColumnName = col }); pd.Columns.Add(col, new ExpandoColumn() { ColumnName = col });
} }
return pd; return pd;
@ -2059,7 +2123,7 @@ namespace PetaPoco
public PocoData(Type t) public PocoData(Type t)
{ {
type = t; type = t;
TableInfo=new TableInfo(); TableInfo = new TableInfo();
// Get the table name // Get the table name
var a = t.GetCustomAttributes(typeof(TableNameAttribute), true); var a = t.GetCustomAttributes(typeof(TableNameAttribute), true);
@ -2201,7 +2265,7 @@ namespace PetaPoco
var lblNotNull = il.DefineLabel(); var lblNotNull = il.DefineLabel();
il.Emit(OpCodes.Brfalse_S, lblNotNull); // obj, obj, fieldname, converter?, value il.Emit(OpCodes.Brfalse_S, lblNotNull); // obj, obj, fieldname, converter?, value
il.Emit(OpCodes.Pop); // obj, obj, fieldname, converter? il.Emit(OpCodes.Pop); // obj, obj, fieldname, converter?
if (converter!=null) if (converter != null)
il.Emit(OpCodes.Pop); // obj, obj, fieldname, il.Emit(OpCodes.Pop); // obj, obj, fieldname,
il.Emit(OpCodes.Ldnull); // obj, obj, fieldname, null il.Emit(OpCodes.Ldnull); // obj, obj, fieldname, null
if (converter != null) if (converter != null)
@ -2254,6 +2318,25 @@ namespace PetaPoco
il.MarkLabel(lblFin); il.MarkLabel(lblFin);
il.Emit(OpCodes.Unbox_Any, type); // value converted il.Emit(OpCodes.Unbox_Any, type); // value converted
} }
else if (type == typeof(Dictionary<string, object>))
{
Func<IDataReader, Dictionary<string, object>> func = reader =>
{
var dict = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
for (int i = firstColumn; i < firstColumn + countColumns; i++)
{
var value = reader.IsDBNull(i) ? null : reader.GetValue(i);
var name = reader.GetName(i);
if (!dict.ContainsKey(name))
dict.Add(name, value);
}
return dict;
};
var localDel = Delegate.CreateDelegate(typeof(Func<IDataReader, Dictionary<string, object>>), func.Target, func.Method);
PocoFactories.Add(key, localDel);
return localDel;
}
else else
{ {
// var poco=new T() // var poco=new T()
@ -2368,7 +2451,7 @@ namespace PetaPoco
} }
} }
private static Func<object, object> GetConverter(bool forceDateTimesToUtc, PocoColumn pc, Type srcType, Type dstType) public static Func<object, object> GetConverter(bool forceDateTimesToUtc, PocoColumn pc, Type srcType, Type dstType)
{ {
Func<object, object> converter = null; Func<object, object> converter = null;
@ -2463,10 +2546,12 @@ namespace PetaPoco
public class Transaction : ITransaction public class Transaction : ITransaction
{ {
public Transaction(Database db) public Transaction(Database db) : this(db, null) { }
public Transaction(Database db, IsolationLevel? isolationLevel)
{ {
_db = db; _db = db;
_db.BeginTransaction(); _db.BeginTransaction(isolationLevel);
} }
public virtual void Complete() public virtual void Complete()

View File

@ -18,5 +18,11 @@ namespace NzbDrone.Core
return actual; return actual;
} }
public static double Megabytes(this int megabytes)
{
return megabytes * 1048576;
}
} }
} }

View File

@ -87,8 +87,8 @@ namespace NzbDrone.Core.Providers.Jobs
importedFiles.ForEach(file => _diskScanProvider.MoveEpisodeFile(file)); importedFiles.ForEach(file => _diskScanProvider.MoveEpisodeFile(file));
//Delete the folder only if all files were removed //Delete the folder only if all files were removed
if (_diskProvider.GetFiles(subfolder, SearchOption.AllDirectories).Length == 0) if (_diskProvider.GetDirectorySize(subfolder) < 1.Megabytes())
_diskProvider.DeleteFolder(subfolder, false); _diskProvider.DeleteFolder(subfolder, true);
} }
catch (Exception e) catch (Exception e)
{ {

View File

@ -65,7 +65,7 @@ namespace NzbDrone
Logger.Info("Starting process. [{0}]", IISProcess.StartInfo.FileName); Logger.Info("Starting process. [{0}]", IISProcess.StartInfo.FileName);
IISProcess.PriorityClass = ProcessPriorityClass.AboveNormal;
IISProcess.Start(); IISProcess.Start();
IISProcess.BeginErrorReadLine(); IISProcess.BeginErrorReadLine();