Browse Source

[WebApiUtils] Refractor; edit; delete

feature/authentication-tests
Robin Thoni 9 years ago
parent
commit
2b2525b355

+ 74
- 0
WebApiUtils/BusinessManager/SqlServerBasicManager.cs View File

@@ -0,0 +1,74 @@
1
+using System;
2
+using System.Collections.Generic;
3
+using System.Data.Entity;
4
+using System.Linq.Expressions;
5
+using iiie.Logs.DataAccess;
6
+using iiie.Logs.DBO;
7
+
8
+namespace iiie.WebApiUtils.BusinessManager
9
+{
10
+    /// <summary>
11
+    /// Helper for SQL Server data access
12
+    /// </summary>
13
+    public abstract class SqlServerBasicManager<TDbObject, TEntities, TThis>
14
+        where TDbObject : class
15
+        where TEntities : DbContext, new()
16
+        where TThis : SqlServerBasicManager<TDbObject, TEntities, TThis>, new()
17
+    {
18
+        /// <summary>
19
+        /// Return the table to be used
20
+        /// </summary>
21
+        /// <param name="db">The database</param>
22
+        /// <returns>The table instance</returns>
23
+        public abstract DbSet<TDbObject> GetTable(TEntities db);
24
+
25
+        /// <summary>
26
+        /// Return the database table to use
27
+        /// </summary>
28
+        /// <param name="db">The database instance</param>
29
+        /// <returns>The table</returns>
30
+        public static DbSet<TDbObject> GetTableStatic(TEntities db)
31
+        {
32
+            var type = new TThis();
33
+            return type.GetTable(db);
34
+        }
35
+
36
+        /// <summary>
37
+        /// Get a predicate form the given keys and values
38
+        /// </summary>
39
+        /// <param name="keys">The keys and values to select data</param>
40
+        /// <returns>The predicate</returns>
41
+        public static Expression<Func<TDbObject, bool>> GetExpression(params KeyValuePair<string, object>[] keys)
42
+        {
43
+            var param = Expression.Parameter(typeof(TDbObject), "x");
44
+            Expression totalExp = null;
45
+            foreach (var pair in keys)
46
+            {
47
+                var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
48
+                totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
49
+            }
50
+            return Expression.Lambda<Func<TDbObject, bool>>(totalExp, param);
51
+        }
52
+
53
+        /// <summary>
54
+        /// Execute SQL quries in try catch
55
+        /// </summary>
56
+        /// <param name="func">The queries to be performed</param>
57
+        /// <returns>The result or an error</returns>
58
+        public static OpResult<U> Execute<U>(Func<TEntities, DbSet<TDbObject>, OpResult<U>> func)
59
+        {
60
+            try
61
+            {
62
+                using (var db = new TEntities())
63
+                {
64
+                    var table = GetTableStatic(db);
65
+                    return func(db, table);
66
+                }
67
+            }
68
+            catch (Exception e)
69
+            {
70
+                return Logger.Error<U>(ResultStatus.DBError, e);
71
+            }
72
+        }
73
+    }
74
+}

+ 133
- 110
WebApiUtils/BusinessManager/SqlServerManager.cs View File

@@ -5,56 +5,50 @@ using System.Linq;
5 5
 using System.Linq.Expressions;
6 6
 using iiie.Logs.DataAccess;
7 7
 using iiie.Logs.DBO;
8
-using System.Linq.Dynamic;
9 8
 
10 9
 namespace iiie.WebApiUtils.BusinessManager
11 10
 {
12 11
     /// <summary>
13 12
     /// Helper for SQL Server data access
14 13
     /// </summary>
15
-    public abstract class SqlServerManager<TDbObject, TDbo, TEntities, TThis>
14
+    public abstract class SqlServerManager<TDbObject, TDboGet, TDboAdd, TDboEdit, TEntities, TThis>
15
+        : SqlServerBasicManager<TDbObject, TEntities, TThis>
16 16
         where TDbObject : class
17 17
         where TEntities : DbContext, new()
18
-        where TThis : SqlServerManager<TDbObject, TDbo, TEntities, TThis>,  new()
18
+        where TThis : SqlServerManager<TDbObject, TDboGet, TDboAdd, TDboEdit, TEntities, TThis>, new()
19 19
     {
20
-        private class DbObjectId
21
-        {
22
-            public long id { get; set; }
23
-        }
24 20
 
25 21
         /// <summary>
26
-        /// Return the table to be used
22
+        /// Convert a DB object to DBO
27 23
         /// </summary>
28
-        /// <param name="db">The database</param>
29
-        /// <returns>The table instance</returns>
30
-        public abstract DbSet<TDbObject> GetTable(TEntities db);
31
-
32
-        public abstract TDbo DbToDbo(TDbObject obj);
24
+        /// <param name="obj">The object to be converted</param>
25
+        /// <returns>The DBO</returns>
26
+        public abstract TDboGet DbToDboGet(TDbObject obj);
33 27
 
34
-        public abstract TDbObject DboToDb(TDbo obj);
28
+        /// <summary>
29
+        /// Convert a DBO to DB object
30
+        /// </summary>
31
+        /// <param name="obj">The object to be converted</param>
32
+        /// <returns>The DB object</returns>
33
+        public abstract TDbObject DboAddToDb(TDboAdd obj);
35 34
 
36 35
         /// <summary>
37
-        /// Return the database table to use
36
+        /// Convert a DBO to DB object
38 37
         /// </summary>
39
-        /// <param name="db">The database instance</param>
40
-        /// <returns>The table</returns>
41
-        public static DbSet<TDbObject> GetTableStatic(TEntities db)
42
-        {
43
-            var type = new TThis();
44
-            return type.GetTable(db);
45
-        }
38
+        /// <param name="obj">The object to be converted</param>
39
+        /// <param name="edit">The object beeing edited</param>
40
+        /// <returns>The DB object</returns>
41
+        public abstract TDbObject DboEditToDb(TDboEdit obj, TDbObject edit);
46 42
 
47 43
         /// <summary>
48 44
         /// Helper to convert DB object to DBO
49 45
         /// </summary>
50 46
         /// <param name="res">The result to convert</param>
51 47
         /// <returns>The DBO object</returns>
52
-        public static OpResult<TDbo> DbToDboStatic(OpResult<TDbObject> res)
48
+        public static TDboGet DbToDboGetStatic(TDbObject res)
53 49
         {
54
-            if (!res)
55
-                return OpResult<TDbo>.Error(res);
56 50
             var obj = new TThis();
57
-            return OpResult<TDbo>.Ok(obj.DbToDbo(res.Data));
51
+            return obj.DbToDboGet(res);
58 52
         }
59 53
         
60 54
         /// <summary>
@@ -62,109 +56,106 @@ namespace iiie.WebApiUtils.BusinessManager
62 56
         /// </summary>
63 57
         /// <param name="res">The result to convert</param>
64 58
         /// <returns>The DB object</returns>
65
-        public static OpResult<TDbObject> DboToDbStatic(OpResult<TDbo> res)
59
+        public static TDbObject DboAddToDbStatic(TDboAdd res)
66 60
         {
67
-            if (!res)
68
-                return OpResult<TDbObject>.Error(res);
69 61
             var obj = new TThis();
70
-            return OpResult<TDbObject>.Ok(obj.DboToDb(res.Data));
62
+            return obj.DboAddToDb(res);
71 63
         }
72 64
 
73
-        /// <summary>
74
-        /// Helper to convert DB object to DBO
75
-        /// </summary>
76
-        /// <param name="res">The result to convert</param>
77
-        /// <returns>The DBO object</returns>
78
-        public static TDbo DbToDboStatic(TDbObject res)
79
-        {
80
-            var obj = new TThis();
81
-            return obj.DbToDbo(res);
82
-        }
83
-        
84 65
         /// <summary>
85 66
         /// Helper to convert DBO object to DB
86 67
         /// </summary>
87 68
         /// <param name="res">The result to convert</param>
69
+        /// <param name="edit">The object beeing edited</param>
88 70
         /// <returns>The DB object</returns>
89
-        public static TDbObject DboToDbStatic(TDbo res)
71
+        public static TDbObject DboEditToDbStatic(TDboEdit res, TDbObject edit)
90 72
         {
91 73
             var obj = new TThis();
92
-            return obj.DboToDb(res);
74
+            return obj.DboEditToDb(res, edit);
93 75
         }
94 76
 
95 77
         /// <summary>
96
-        /// Execute SQL quries in try catch
78
+        /// Get a single DB object matching the predicate
97 79
         /// </summary>
98
-        /// <param name="func">The queries to be performed</param>
99
-        /// <returns>The result or an error</returns>
100
-        public static OpResult<U> Execute<U>(Func<TEntities, DbSet<TDbObject>, OpResult<U>> func)
80
+        /// <param name="table">The table to search in</param>
81
+        /// <param name="predicate">The predicate</param>
82
+        /// <returns>The object that match</returns>
83
+        public static OpResult<TDbObject> GetSingleDbObject(DbSet<TDbObject> table, Expression<Func<TDbObject, bool>> predicate)
101 84
         {
102
-            try
85
+            var o = table.FirstOrDefault(predicate);
86
+            if (o == null)
103 87
             {
104
-                using (var db = new TEntities())
105
-                {
106
-                    var table = GetTableStatic(db);
107
-                    return func(db, table);
108
-                }
109
-            }
110
-            catch (Exception e)
111
-            {
112
-                return Logger.Error<U>(ResultStatus.DBError, e);
88
+                return OpResult<TDbObject>.Error(ResultStatus.NotFound, typeof(TThis).Name + ": Value not found", "");
113 89
             }
90
+            return OpResult<TDbObject>.Ok(o);
114 91
         }
115 92
 
116 93
         /// <summary>
117
-        /// Get a single DB object matching the predicate
94
+        /// Get a single DBO matching the predicate
118 95
         /// </summary>
119 96
         /// <param name="predicate">The predicate</param>
120 97
         /// <returns>The object that match, or null</returns>
121
-        public static OpResult<TDbObject> GetSingle(Expression<Func<TDbObject, bool>> predicate)
98
+        public static OpResult<TDboGet> GetSingle(Expression<Func<TDbObject, bool>> predicate)
122 99
         {
123 100
             return Execute((db, table) =>
124 101
             {
125
-                var o = table.FirstOrDefault(predicate);
126
-                if (o == null)
127
-                {
128
-                    return OpResult<TDbObject>.Error(ResultStatus.NotFound, typeof(TThis).Name + ": Value not found", "");
129
-                }
130
-                return OpResult<TDbObject>.Ok(o);
131
-
102
+                var obj = GetSingleDbObject(table, predicate);
103
+                if (!obj)
104
+                    return obj.To<TDboGet>();
105
+                return OpResult<TDboGet>.Ok(DbToDboGetStatic(obj.Data));
132 106
             });
133 107
         }
134 108
 
135 109
         /// <summary>
136
-        /// Get a single DBO matching the predicate
110
+        /// Get an object by its primary key(s)
137 111
         /// </summary>
138
-        /// <param name="predicate">The predicate</param>
139
-        /// <returns>The object that match, or null</returns>
140
-        public static OpResult<TDbo> GetSingleDbo(Expression<Func<TDbObject, bool>> predicate)
112
+        /// <param name="keys">The key names and values</param>
113
+        /// <returns>The object</returns>
114
+        public static OpResult<TDboGet> GetSingleByKeys(params KeyValuePair<string, object>[] keys)
141 115
         {
142
-            return DbToDboStatic(GetSingle(predicate));
116
+            return GetSingle(GetExpression(keys));
117
+        }
118
+
119
+        /// <summary>
120
+        /// Get an object by its id
121
+        /// </summary>
122
+        /// <param name="id">The id of the object</param>
123
+        /// <returns>The object</returns>
124
+        public static OpResult<TDboGet> GetSingleById(long id)
125
+        {
126
+            return GetSingleByKeys(new KeyValuePair<string, object>("id", id));
143 127
         }
144 128
 
145 129
         /// <summary>
146 130
         /// Get all DB object matching the predicate
147 131
         /// </summary>
148 132
         /// <param name="predicate">The predicate</param>
133
+        /// <param name="orderBy">The order by function</param>
134
+        /// <param name="page">The page numeber (0 based)</param>
135
+        /// <param name="perPage">The maximum number of items par page</param>
149 136
         /// <returns>All matching objects</returns>
150
-        public static OpResult<IEnumerable<TDbObject>> GetMultiple(Expression<Func<TDbObject, bool>> predicate)
137
+        public static OpResult<IEnumerable<TDboGet>> GetMultiple<TKey>(Expression<Func<TDbObject, bool>> predicate,
138
+            Expression<Func<TDbObject, TKey>> orderBy, int page = 0,int perPage = Int32.MaxValue)
151 139
         {
152
-            return Execute((db, table) => OpResult<IEnumerable<TDbObject>>.Ok(table.Where(predicate).ToList()));
140
+            return Execute((db, table) =>
141
+            {
142
+                var results = table.OrderBy(orderBy).Where(predicate).Skip(page * perPage).Take(perPage).ToList();
143
+                return OpResult<IEnumerable<TDboGet>>.Ok(results.Select(DbToDboGetStatic));
144
+            });
153 145
         }
154 146
 
155 147
         /// <summary>
156
-        /// Get all DBO matching the predicate
148
+        /// Get all DB object matching the predicate built from keys
157 149
         /// </summary>
158
-        /// <typeparam name="TDbo">The DBO type</typeparam>
159
-        /// <param name="predicate">The predicate</param>
150
+        /// <param name="page">The page numeber (0 based)</param>
151
+        /// <param name="perPage">The maximum number of items par page</param>
152
+        /// <param name="orderBy">The order by function</param>
153
+        /// <param name="keys">The key names and values</param>
160 154
         /// <returns>All matching objects</returns>
161
-        public static OpResult<IEnumerable<TDbo>> GetMultipleDbo(Expression<Func<TDbObject, bool>> predicate)
155
+        public static OpResult<IEnumerable<TDboGet>> GetMultipleByKeys<TKey>(Expression<Func<TDbObject, TKey>> orderBy,
156
+            int page = 0, int perPage = Int32.MaxValue, params KeyValuePair<string, object>[] keys)
162 157
         {
163
-            var res = GetMultiple(predicate);
164
-            if (!res)
165
-                return OpResult<IEnumerable<TDbo>>.Error(res);
166
-            var dbo = res.Data.Select(DbToDboStatic);
167
-            return OpResult<IEnumerable<TDbo>>.Ok(dbo);
158
+            return GetMultiple(GetExpression(keys), orderBy, page, perPage);
168 159
         }
169 160
 
170 161
         /// <summary>
@@ -172,62 +163,94 @@ namespace iiie.WebApiUtils.BusinessManager
172 163
         /// </summary>
173 164
         /// <param name="obj">The object to be added</param>
174 165
         /// <returns>Always true or an OpResult error</returns>
175
-        public static OpResult<bool> Add(TDbObject obj)
166
+        public static OpResult<bool> Add(TDboAdd obj)
176 167
         {
177 168
             return Execute((db, table) =>
178 169
             {
179
-                table.Add(obj);
170
+                table.Add(DboAddToDbStatic(obj));
180 171
                 db.SaveChanges();
181 172
                 return OpResult<bool>.Ok(true);
182 173
             });
183 174
         }
184 175
 
185 176
         /// <summary>
186
-        /// Add an entry in the database
177
+        /// Edit an entry in the database
187 178
         /// </summary>
188
-        /// <param name="obj"></param>
179
+        /// <param name="obj">The object to be added</param>
180
+        /// <param name="predicate">The predicate to be used to select data</param>
189 181
         /// <returns>Always true or an OpResult error</returns>
190
-        public static OpResult<bool> AddDbo(TDbo obj)
182
+        public static OpResult<bool> Edit(TDboEdit obj, Expression<Func<TDbObject, bool>> predicate)
191 183
         {
192
-            return Add(DboToDbStatic(obj));
184
+            return Execute((db, table) =>
185
+            {
186
+                var edit = GetSingleDbObject(table, predicate);
187
+                if (!edit)
188
+                    return edit.To<bool>();
189
+                var res = DboEditToDbStatic(obj, edit.Data);
190
+                db.Entry(edit.Data).CurrentValues.SetValues(res);
191
+                db.SaveChanges();
192
+                return OpResult<bool>.Ok(true);
193
+            });
193 194
         }
194 195
 
195 196
         /// <summary>
196
-        /// Get an object by its primary key(s)
197
+        /// Edit an entry in the database
197 198
         /// </summary>
198
-        /// <param name="pairs">The key names and values</param>
199
-        /// <returns>The object</returns>
200
-        public static OpResult<TDbObject> GetByPrimary(params KeyValuePair<string, object>[] pairs)
199
+        /// <param name="obj">The object to be added</param>
200
+        /// <param name="keys">The keys to be used to select data</param>
201
+        /// <returns>Always true or an OpResult error</returns>
202
+        public static OpResult<bool> Edit(TDboEdit obj, params KeyValuePair<string, object>[] keys)
203
+        {
204
+            return Edit(obj, GetExpression(keys));
205
+        }
206
+
207
+        /// <summary>
208
+        /// Edit an entry in the database
209
+        /// </summary>
210
+        /// <param name="obj">The object to be added</param>
211
+        /// <param name="id">The id to be edited</param>
212
+        /// <returns>Always true or an OpResult error</returns>
213
+        public static OpResult<bool> EditById(TDboEdit obj, long id)
201 214
         {
202
-            var param = Expression.Parameter(typeof(TDbObject), "x");
203
-            Expression totalExp = null;
204
-            foreach (var pair in pairs)
215
+            return Edit(obj, new KeyValuePair<string, object>("id", id));
216
+        }
217
+
218
+        /// <summary>
219
+        /// Delete an entry in the database
220
+        /// </summary>
221
+        /// <param name="predicate">The predicate to be used to delete data</param>
222
+        /// <returns>Always true or an OpResult error</returns>
223
+        public static OpResult<bool> Delete(Expression<Func<TDbObject, bool>> predicate)
224
+        {
225
+            return Execute((db, table) =>
205 226
             {
206
-                var equalExp = Expression.Equal(Expression.Property(param, pair.Key), Expression.Constant(pair.Value));
207
-                totalExp = totalExp == null ? equalExp : Expression.And(equalExp, totalExp);
208
-            }
209
-            var lambda = Expression.Lambda<Func<TDbObject, bool>>(totalExp, param);
210
-            return GetSingle(lambda);
227
+                var del = GetSingleDbObject(table, predicate);
228
+                if (!del)
229
+                    return del.To<bool>();
230
+                table.Remove(del.Data);
231
+                db.SaveChanges();
232
+                return OpResult<bool>.Ok(true);
233
+            });
211 234
         }
212 235
 
213 236
         /// <summary>
214
-        /// Get an object by its id
237
+        /// Delete an entry in the database
215 238
         /// </summary>
216
-        /// <param name="id">The id of the object</param>
217
-        /// <returns>The object</returns>
218
-        public static OpResult<TDbObject> GetById(long id)
239
+        /// <param name="keys">The keys to be used to delete data</param>
240
+        /// <returns>Always true or an OpResult error</returns>
241
+        public static OpResult<bool> Delete(params KeyValuePair<string, object>[] keys)
219 242
         {
220
-            return GetByPrimary(new KeyValuePair<string, object>("id", id));
243
+            return Delete(GetExpression(keys));
221 244
         }
222 245
 
223 246
         /// <summary>
224
-        /// Get an object by its id
247
+        /// Delete an entry in the database
225 248
         /// </summary>
226
-        /// <param name="id">The id of the object</param>
227
-        /// <returns>The object</returns>
228
-        public static OpResult<TDbo> GetByIdDbo(long id)
249
+        /// <param name="id">The id to be deleted</param>
250
+        /// <returns>Always true or an OpResult error</returns>
251
+        public static OpResult<bool> DeleteById(long id)
229 252
         {
230
-            return DbToDboStatic(GetById(id));
253
+            return Delete(new KeyValuePair<string, object>("id", id));
231 254
         }
232 255
     }
233 256
 }

+ 2
- 1
WebApiUtils/WebApiUtils.csproj View File

@@ -43,7 +43,7 @@
43 43
       <Private>True</Private>
44 44
     </Reference>
45 45
     <Reference Include="Logs, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
46
-      <HintPath>..\packages\Logs.dll.1.2.1\lib\net45\Logs.dll</HintPath>
46
+      <HintPath>..\packages\Logs.dll.1.2.2\lib\net45\Logs.dll</HintPath>
47 47
       <Private>True</Private>
48 48
     </Reference>
49 49
     <Reference Include="Microsoft.Practices.EnterpriseLibrary.Common, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
@@ -92,6 +92,7 @@
92 92
     <Compile Include="BusinessManager\BMRHandler.cs" />
93 93
     <Compile Include="BusinessManager\CheckModelForNullAttribute.cs" />
94 94
     <Compile Include="BusinessManager\ExceptionLoggerAttribute.cs" />
95
+    <Compile Include="BusinessManager\SqlServerBasicManager.cs" />
95 96
     <Compile Include="BusinessManager\SqlServerManager.cs" />
96 97
     <Compile Include="BusinessManager\ValidateModelStateAttribute.cs" />
97 98
     <Compile Include="BusinessManager\WebApiUtils.cs" />

+ 1
- 1
WebApiUtils/packages.config View File

@@ -6,7 +6,7 @@
6 6
   <package id="EnterpriseLibrary.Logging" version="6.0.1304.0" targetFramework="net45" />
7 7
   <package id="EnterpriseLibrary.Logging.Database" version="6.0.1304.0" targetFramework="net45" />
8 8
   <package id="EntityFramework" version="6.1.3" targetFramework="net45" />
9
-  <package id="Logs.dll" version="1.2.1" targetFramework="net45" />
9
+  <package id="Logs.dll" version="1.2.2" targetFramework="net45" />
10 10
   <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
11 11
   <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
12 12
   <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" />

Loading…
Cancel
Save