8 Commits

Author SHA1 Message Date
Railz
8816110211 Improved Exception messages (variables)
CLassAction: Added GetList
Set Version to 1.5.11
2019-05-30 13:16:48 +02:00
Alexander B
40936fafcd Set version to 1.5.9 2019-05-15 12:11:23 +02:00
Alexander B
800941d59c Implemented:
QueryBuilder.SelectWithWhere()
ClassAction.GetListWithWhere()
2019-05-15 12:11:01 +02:00
Railz
64c8711754 Set version 2019-05-09 08:02:49 +02:00
Railz
ad3c1da0cd Fixes:
- Fields not matching
- FieldType being lookedUp wrong
- dictionary-access-violation
- guid saved as string not casting
- InsertQuery built wrong
2019-05-08 23:22:20 +02:00
Railz
ba0646f27c Set version to 1.5.7 2019-05-08 21:56:55 +02:00
Railz
76922a4039 Changed cache-check to dictionary
> Fixed bug, not restoring cache
2019-05-08 21:56:34 +02:00
Railz
e3869b26c3 removed inner Exception 2019-04-20 10:29:52 +02:00
6 changed files with 106 additions and 27 deletions

View File

@@ -30,7 +30,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
{ {
this.parentField = fi; this.parentField = fi;
this.classAttribute = classAttribute; this.classAttribute = classAttribute;
this.foreignObjectType = fi.GetType(); this.foreignObjectType = fi.FieldType;
// Init foreign-object class // Init foreign-object class
DbObject foreignClassAttribute = ClassAction.Init(this.foreignObjectType); DbObject foreignClassAttribute = ClassAction.Init(this.foreignObjectType);
@@ -45,7 +45,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
if(this._foreignKeyName != null) // If i have a name if(this._foreignKeyName != null) // If i have a name
{ {
// check if name matches // check if name matches
if (foreignKey.parentField.Name.ToLower() == this._foreignKeyName) if (foreignKey.parentField.Name.ToLower() == this._foreignKeyName.ToLower())
{ {
if(foreignKey.parentField.GetType() == primaryKeyType) if(foreignKey.parentField.GetType() == primaryKeyType)
{ {

View File

@@ -71,7 +71,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System.Attributes
} }
catch(InvalidOperationException ex) catch(InvalidOperationException ex)
{ {
throw new InvalidOperationException($"Cannot init foreignObject-field '{fi.Name}' of '{classType.Name}'. {ex.Message}", ex); throw new InvalidOperationException($"Cannot init foreignObject-field='{fi.Name}' of class='{classType.Name}'.", ex);
} }
} }
} }

View File

@@ -8,7 +8,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
{ {
public class ClassAction public class ClassAction
{ {
private static List<Type> initiatedClassTypes = new List<Type>() { }; private static Dictionary<Type, DbObject> initiatedClassTypes = new Dictionary<Type, DbObject>() { };
/// <summary> /// <summary>
/// Initiates the attribute-system and preloads all necessary information<para/> /// Initiates the attribute-system and preloads all necessary information<para/>
/// INFO: Will initiate necessary foreignObjects recursively!<para/> /// INFO: Will initiate necessary foreignObjects recursively!<para/>
@@ -17,17 +17,22 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
/// <param name="classType">The classType to preload</param> /// <param name="classType">The classType to preload</param>
/// <returns>DbObject-attribute corresponding to the class</returns> /// <returns>DbObject-attribute corresponding to the class</returns>
public static DbObject Init(Type classType) public static DbObject Init(Type classType)
{
DbObject cachedDbObject;
initiatedClassTypes.TryGetValue(classType, out cachedDbObject);
if (cachedDbObject == null)
{ {
// Check if given class is marked as dbObject // Check if given class is marked as dbObject
if (!(classType.GetCustomAttribute(typeof(DbObject), true) is DbObject dbObject)) throw new InvalidOperationException($"Cannot init '{classType.Name}'. Missing Attribute 'DbObject'"); if (!(classType.GetCustomAttribute(typeof(DbObject), true) is DbObject dbObject)) throw new InvalidOperationException($"Cannot init '{classType.Name}'. Missing Attribute 'DbObject'");
if (!initiatedClassTypes.Contains(classType))
{
dbObject.Init(classType); // Init dbObject dbObject.Init(classType); // Init dbObject
initiatedClassTypes.Add(classType); // Set it to the list initiatedClassTypes.Add(classType, dbObject); // Set it to the list
cachedDbObject = dbObject;
} }
return dbObject; return cachedDbObject;
} }
@@ -55,7 +60,10 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
// If its a match, set the value // If its a match, set the value
if (baseAttribute._attributeName.ToLower() == data_keySet.Key.ToLower()) if (baseAttribute._attributeName.ToLower() == data_keySet.Key.ToLower())
{ {
baseAttribute.parentField.SetValue(classObject, data_keySet.Value); object value = data_keySet.Value;
if (baseAttribute.parentField.FieldType == typeof(Guid)) value = new Guid((string)value); // If its a guid, i need to convert
baseAttribute.parentField.SetValue(classObject, value);
break; break;
} }
} }
@@ -119,18 +127,57 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
return obj; return obj;
} }
// ----
/// <summary> /// <summary>
/// Resolves dbObject by primaryKey/s<pragma/> /// Gets all dbObjects of class/table
/// Object needs to have primaryKey/s set!
/// </summary> /// </summary>
/// <typeparam name="T"></typeparam> /// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param> /// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param> /// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
public static void ResolveByPrimaryKey<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor) public static List<T> GetList<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor) where T : new()
{ {
string query = QueryBuilder.SelectByPrimaryKey(classObject); // Generate query // Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.SelectByAttribute(dbObject._tableName); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
FillObject(classObject, dataSet[0]); // Fill the object
List<T> objs = new List<T>() { };
foreach (Dictionary<string, object> data in dataSet)
{
T obj = new T(); // New object
FillObject(obj, data); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
}
/// <summary>
/// Gets an dbObject by primaryKey/s
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="whereClause">Custom where-clause params attached to query (SELECT * FROM tableName WHERE whereClause)</param>
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
public static List<T> GetListWithWhere<T>(Type classType, Func<string, List<Dictionary<string, object>>> queryExecutor, params object[] whereClause) where T : new()
{
// Read dbObject - attribute
DbObject dbObject = ClassAction.Init(classType);
string query = QueryBuilder.SelectWithWhere(dbObject._tableName, whereClause); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
List<T> objs = new List<T>() { };
foreach (Dictionary<string, object> data in dataSet)
{
T obj = new T(); // New object
FillObject(obj, data); // Fill it
objs.Add(obj); // Add to list
}
return objs; // Return list
} }
/// <summary> /// <summary>
@@ -163,7 +210,21 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
return objs; // Return list return objs; // Return list
} }
// -----
/// <summary>
/// Resolves dbObject by primaryKey/s<pragma/>
/// Object needs to have primaryKey/s set!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="classObject">Given object (marked with Db-attributes)</param>
/// <param name="queryExecutor">Function to handle query-calls - Has to return Dictionary[attributeName, attributeValue]</param>
public static void ResolveByPrimaryKey<T>(T classObject, Func<string, List<Dictionary<string, object>>> queryExecutor)
{
string query = QueryBuilder.SelectByPrimaryKey(classObject); // Generate query
List<Dictionary<string, object>> dataSet = queryExecutor(query); // Execute
FillObject(classObject, dataSet[0]); // Fill the object
}
/// <summary> /// <summary>
/// Resolves all foreignKeys with the database<pragma/> /// Resolves all foreignKeys with the database<pragma/>
@@ -188,7 +249,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
// When its empty, get it // When its empty, get it
if(foreignObject_value == null) if(foreignObject_value == null)
{ {
foreignObject_value = GetByPrimaryKey<T>(classType, foreignObjectAtt.foreignKeyAttribute.parentField.GetValue(classObject), queryExecutor); ; foreignObject_value = GetByPrimaryKey<T>(classType, foreignObjectAtt.foreignKeyAttribute.parentField.GetValue(classObject), queryExecutor);
} }
// Recursive resolving // Recursive resolving

View File

@@ -4,7 +4,7 @@
<TargetFramework>netcoreapp2.1</TargetFramework> <TargetFramework>netcoreapp2.1</TargetFramework>
<RootNamespace>eu.railduction.netcore.dll.Database_Attribute_System</RootNamespace> <RootNamespace>eu.railduction.netcore.dll.Database_Attribute_System</RootNamespace>
<SignAssembly>false</SignAssembly> <SignAssembly>false</SignAssembly>
<Version>1.5.6</Version> <Version>1.5.11</Version>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@@ -56,6 +56,25 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
return BuildQuery(param); return BuildQuery(param);
} }
/// <summary>
/// Builds an SELECT-Sql-query based on an object with custom where clause<para/>
/// Object needs to have at least 1 attribute!
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableName">The db-table-name</param>
/// <param name="whereClause">Custom where-clause params attached to query (SELECT * FROM tableName WHERE whereClause)</param>
/// <returns>SELECT-Sql-query</returns>
public static string SelectWithWhere(string tableName, params object[] whereClause)
{
string sqlCmd = $"SELECT * FROM {tableName}";
// Add SQL-command part
if (!(whereClause[0] is string)) throw new InvalidOperationException("Cannot generate SQL-query. WhereClause-params not starting with string!");
whereClause[0] = $"{sqlCmd} WHERE {whereClause[0]}";
// Build and return the query
return BuildQuery(whereClause);
}
/// <summary> /// <summary>
/// Builds an UPDATE-Sql-query based on an object<para/> /// Builds an UPDATE-Sql-query based on an object<para/>
/// Object needs to have at least 1 primary-key! /// Object needs to have at least 1 primary-key!
@@ -181,14 +200,14 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
if (attributes.Count != data.Count) throw new InvalidOperationException("Cannot generate SQL-Query. Attribute-count and data-count not equal."); if (attributes.Count != data.Count) throw new InvalidOperationException("Cannot generate SQL-Query. Attribute-count and data-count not equal.");
string attributesSeperatedByComma = ""; string attributesSeperatedByComma = "";
object[] attributeData = new object[attributes.Count*2]; object[] attributeData = new object[attributes.Count*2 -1];
int c = 0; int c = 0;
for(int i=0; i<attributes.Count*2; i+=2) for(int i=0; i< attributes.Count; i++)
{ {
attributesSeperatedByComma += attributes[i]; attributesSeperatedByComma += attributes[i];
attributeData[c] = data[i+1]; attributeData[c] = data[i];
if(c+1 != attributes.Count*2) if(c+1 != attributeData.Length)
{ {
attributesSeperatedByComma += ", "; attributesSeperatedByComma += ", ";
attributeData[c+1] = ","; attributeData[c+1] = ",";

View File

@@ -79,6 +79,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
{ {
// Read dbObject-attribute // Read dbObject-attribute
DbObject dbObject = ClassAction.Init(classType); DbObject dbObject = ClassAction.Init(classType);
Dictionary<string, object> convertedAttributeNameAndValues = new Dictionary<string, object>();
foreach (KeyValuePair<string, object> attributeNameAndValue in attributeNameAndValues) foreach (KeyValuePair<string, object> attributeNameAndValue in attributeNameAndValues)
{ {
@@ -87,16 +88,14 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
{ {
if (attributeNameAndValue.Key.ToLower() == baseAttribute.parentField.Name.ToLower()) if (attributeNameAndValue.Key.ToLower() == baseAttribute.parentField.Name.ToLower())
{ {
attributeNameAndValues.Remove(attributeNameAndValue.Key); convertedAttributeNameAndValues.Add(baseAttribute._attributeName, attributeNameAndValue.Value);
attributeNameAndValues.Add(baseAttribute._attributeName, attributeNameAndValue.Value);
nameFound = true; nameFound = true;
break; break;
} }
} }
if (!nameFound) throw new InvalidOperationException($"{attributeNameAndValue.Key} has no classField!"); if (!nameFound) throw new InvalidOperationException($"'{attributeNameAndValue.Key}' has no classField!");
} }
} }
internal static void ConvertAttributeToDbAttributes(Type classType, List<string> attributeNames) internal static void ConvertAttributeToDbAttributes(Type classType, List<string> attributeNames)
@@ -118,7 +117,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
} }
} }
if (!nameFound) throw new InvalidOperationException($"{attributeNames[i]} has no classField!"); if (!nameFound) throw new InvalidOperationException($"'{attributeNames[i]}' has no classField!");
} }
} }
@@ -142,7 +141,7 @@ namespace eu.railduction.netcore.dll.Database_Attribute_System
DateTime dateTime = (DateTime)obj; DateTime dateTime = (DateTime)obj;
return "'" + SqlSerialise(dateTime) + "'"; // wrap in sql-brackets and convert to sql-datetime return "'" + SqlSerialise(dateTime) + "'"; // wrap in sql-brackets and convert to sql-datetime
} }
else if (obj.GetType() == typeof(Guid)) // Handle DateTime else if (obj.GetType() == typeof(Guid)) // Handle Guid
{ {
string guid = ((Guid)obj).ToString(); // Get Guid as string string guid = ((Guid)obj).ToString(); // Get Guid as string
return "'" + guid + "'"; // wrap in sql-brackets return "'" + guid + "'"; // wrap in sql-brackets