-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathCoreAdminDataController.cs
More file actions
366 lines (291 loc) · 16.5 KB
/
CoreAdminDataController.cs
File metadata and controls
366 lines (291 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
using DotNetEd.CoreAdmin.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace DotNetEd.CoreAdmin.Controllers
{
[CoreAdminAuth]
public class CoreAdminDataController : Controller
{
private readonly IEnumerable<DiscoveredDbSetEntityType> dbSetEntities;
public CoreAdminDataController(IEnumerable<DiscoveredDbSetEntityType> dbSetEntities)
{
this.dbSetEntities = dbSetEntities;
}
[HttpGet]
public IActionResult Index(string id)
{
var viewModel = new DataListViewModel();
foreach (var dbSetEntity in dbSetEntities.Where(db => db.Name.ToLowerInvariant() == id.ToLowerInvariant()))
{
foreach (var dbSetProperty in dbSetEntity.DbContextType.GetProperties())
{
if (dbSetProperty.PropertyType.IsGenericType && dbSetProperty.PropertyType.Name.StartsWith("DbSet") && dbSetProperty.Name.ToLowerInvariant() == id.ToLowerInvariant())
{
viewModel.EntityType = dbSetProperty.PropertyType.GetGenericArguments().First();
viewModel.DbSetProperty = dbSetProperty;
if (Attribute.IsDefined(viewModel.EntityType, typeof(DisplayAttribute)))
{
viewModel.DbDisplayName = viewModel.EntityType.GetCustomAttribute<DisplayAttribute>().Name;
}
var dbContextObject = (DbContext)this.HttpContext.RequestServices.GetRequiredService(dbSetEntity.DbContextType);
var query = dbContextObject.Set(viewModel.EntityType);
var dbSetValue = dbSetProperty.GetValue(dbContextObject);
var navProperties = dbContextObject.Model.FindEntityType(viewModel.EntityType).GetNavigations();
foreach (var property in navProperties)
{
// Only display One to One relationships on the Grid
if(property.GetCollectionAccessor() == null)
query = query.Include(property.Name);
}
viewModel.Data = (IEnumerable<object>)query;
viewModel.DbContext = dbContextObject;
}
}
}
if (viewModel.DbContext == null)
{
return NotFound();
}
return View(viewModel);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Usage", "EF1001:Internal EF Core API usage.", Justification = "<Pending>")]
private object GetDbSetValueOrNull(string dbSetName, out DbContext dbContextObject,
out Type typeOfEntity,
out Dictionary<string, Dictionary<object, string>> relationships)
{
foreach (var dbSetEntity in dbSetEntities.Where(db => db.Name.ToLowerInvariant() == dbSetName.ToLowerInvariant()))
{
foreach (var dbSetProperty in dbSetEntity.DbContextType.GetProperties())
{
if (dbSetProperty.PropertyType.IsGenericType && dbSetProperty.PropertyType.Name.StartsWith("DbSet") && dbSetProperty.Name.ToLowerInvariant() == dbSetName.ToLowerInvariant())
{
dbContextObject = (DbContext)this.HttpContext.RequestServices.GetRequiredService(dbSetEntity.DbContextType);
typeOfEntity = dbSetProperty.PropertyType.GetGenericArguments()[0];
var fks = dbContextObject.Model.FindEntityType(typeOfEntity)
.GetForeignKeyProperties().Cast<Microsoft.EntityFrameworkCore.Metadata.RuntimeProperty>();
var relationshipDictionary = new Dictionary<string, Dictionary<object, string>>();
foreach (var f in fks)
{
var childValues = new Dictionary<object, string>();
if (f.ForeignKeys.Count == 1)
{
var typeOfChild = f.ForeignKeys.First();
var propsOnDbContext = dbContextObject.GetType().GetProperties();
var targetChildListOnDbContext = dbContextObject.GetType().GetProperties()
.FirstOrDefault(p => p.PropertyType.IsGenericType
&& p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)
&& p.PropertyType.GetGenericArguments().First().FullName == typeOfChild.PrincipalEntityType.Name);
var primaryKey2 = dbContextObject.Model.FindEntityType(typeOfChild.PrincipalEntityType.Name).FindPrimaryKey();
var allChildren2 = (IEnumerable<object>)dbContextObject.GetType().GetProperty(targetChildListOnDbContext.Name).GetValue(dbContextObject);
NullabilityInfoContext _nullabilityContext = new NullabilityInfoContext();
var nullabilityInfo = _nullabilityContext.Create(typeOfEntity.GetProperty(f.Name));
if (nullabilityInfo.WriteState == NullabilityState.Nullable)
{
childValues.Add(string.Empty, String.Empty);
}
foreach (var childValue in allChildren2)
{
var childPkValue = childValue.GetType().GetProperty(primaryKey2.Properties.First().Name).GetValue(childValue);
childValues.Add(childPkValue, childValue.ToString());
}
}
relationshipDictionary.Add(f.Name, childValues);
}
relationships = relationshipDictionary;
return dbSetProperty.GetValue(dbContextObject);
}
}
}
dbContextObject = null;
typeOfEntity = null;
relationships = null;
return null;
}
private object GetEntityFromDbSet(string dbSetName, string id,
out DbContext dbContextObject, out Type typeOfEntity,
out Dictionary<string, Dictionary<object, string>> relationships)
{
var dbSetValue = GetDbSetValueOrNull(dbSetName, out dbContextObject, out typeOfEntity, out relationships);
var primaryKey = dbContextObject.Model.FindEntityType(typeOfEntity).FindPrimaryKey();
var clrType = primaryKey.Properties[0].ClrType;
object convertedPrimaryKey = id;
if (clrType == typeof(Guid))
{
convertedPrimaryKey = Guid.Parse(id);
}
else if (clrType == typeof(int))
{
convertedPrimaryKey = int.Parse(id);
}
else if (clrType == typeof(long))
{
convertedPrimaryKey = long.Parse(id);
}
return dbSetValue.GetType().InvokeMember("Find", BindingFlags.InvokeMethod, null, dbSetValue, args: new object[] { convertedPrimaryKey });
}
[HttpPost]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> CreateEntityPost(string dbSetName, string id, [FromForm] object formData)
{
var dbSetValue = GetDbSetValueOrNull(dbSetName, out var dbContextObject, out var entityType, out var relationships);
var newEntity = System.Activator.CreateInstance(entityType);
var databaseGeneratedProperties =
newEntity.GetType().GetProperties()
.Where(p => p.GetCustomAttributes().Any(a => a.GetType().Name.Contains("DatabaseGenerated"))).Select(p => p.Name);
await AddByteArrayFiles(newEntity);
await TryUpdateModelAsync(newEntity, entityType, string.Empty,
await CompositeValueProvider.CreateAsync(this.ControllerContext, this.ControllerContext.ValueProviderFactories),
(ModelMetadata meta) => !databaseGeneratedProperties.Contains(meta.PropertyName));
// remove any errors from fk properties - ef will handle this validation
foreach (var fkProperty in newEntity.GetType().GetProperties()
.Where(p => p.GetCustomAttributes().Any(a => a.GetType().Name.Contains("ForeignKey"))).Select(p => p.Name))
{
if (ModelState.ContainsKey(fkProperty))
{
ModelState[fkProperty].Errors.Clear();
ModelState[fkProperty].ValidationState = ModelValidationState.Skipped;
}
}
if (ModelState.ValidationState == ModelValidationState.Valid)
{
// updated model with new values
dbContextObject.Add(newEntity);
await dbContextObject.SaveChangesAsync();
return RedirectToAction("Index", new {id = dbSetName });
}
ViewBag.DbSetName = id;
ViewBag.IgnoreFromForm = databaseGeneratedProperties;
ViewBag.Relationships = relationships;
return View("Create", newEntity);
}
[HttpGet]
[IgnoreAntiforgeryToken]
public IActionResult Create(string id)
{
var dbSetValue = GetDbSetValueOrNull(id, out var dbContextObject, out var entityType, out var relationships);
var newEntity = System.Activator.CreateInstance(entityType);
ViewBag.DbSetName = id;
var autoGeneratedPropertyNames =
newEntity.GetType().GetProperties()
.Where(p => p.GetCustomAttributes().Any(a => a.GetType().Name.Contains("DatabaseGenerated"))).Select(p => p.Name);
ViewBag.DbDisplayName = entityType.GetCustomAttribute<DisplayAttribute>().Name ?? id;
ViewBag.IgnoreFromForm = autoGeneratedPropertyNames;
ViewBag.Relationships = relationships;
return View(newEntity);
}
[HttpGet]
public IActionResult EditEntity(string dbSetName, string id)
{
var entityToEdit = GetEntityFromDbSet(dbSetName, id, out var dbContextObject, out var entityType, out var relationships);
var databaseGeneratedProperties =
entityToEdit.GetType().GetProperties()
.Where(p => p.GetCustomAttributes().Any(a => a.GetType().Name.Contains("DatabaseGenerated"))).Select(p => p.Name);
ViewBag.DbSetName = dbSetName;
ViewBag.DbDisplayName = entityType.GetCustomAttribute<DisplayAttribute>().Name ?? dbSetName;
ViewBag.Id = id;
ViewBag.Relationships = relationships;
ViewBag.IgnoreFromForm = databaseGeneratedProperties;
return View("Edit", entityToEdit);
}
[HttpPost]
public async Task<IActionResult> EditEntityPost(string dbSetName, string id, [FromForm] object formData)
{
var entityToEdit = GetEntityFromDbSet(dbSetName, id, out var dbContextObject, out var entityType, out var relationships);
dbContextObject.Attach(entityToEdit);
await AddByteArrayFiles(entityToEdit);
var databaseGeneratedProperties =
entityToEdit.GetType().GetProperties()
.Where(p => p.GetCustomAttributes().Any(a => a.GetType().Name.Contains("DatabaseGenerated"))).Select(p => p.Name);
await TryUpdateModelAsync(entityToEdit, entityType, string.Empty, await CompositeValueProvider.CreateAsync(this.ControllerContext, this.ControllerContext.ValueProviderFactories),
(ModelMetadata meta) => !databaseGeneratedProperties.Contains(meta.PropertyName));
// remove any errors from fk properties - ef will handle this validation
foreach (var fkProperty in entityToEdit.GetType().GetProperties()
.Where(p => p.GetCustomAttributes().Any(a => a.GetType().Name.Contains("ForeignKey"))).Select(p => p.Name))
{
if (ModelState.ContainsKey(fkProperty))
{
ModelState[fkProperty].Errors.Clear();
ModelState[fkProperty].ValidationState = ModelValidationState.Skipped;
}
}
if (ModelState.ValidationState == ModelValidationState.Valid)
{
await dbContextObject.SaveChangesAsync();
return RedirectToAction("Index", new { id = dbSetName });
}
ViewBag.DbSetName = dbSetName;
ViewBag.Id = id;
ViewBag.Relationships = relationships;
ViewBag.IgnoreFromForm = databaseGeneratedProperties;
return View("Edit", entityToEdit);
}
private async Task AddByteArrayFiles(object entityToEdit)
{
foreach (var file in Request.Form.Files)
{
var matchingProperty = entityToEdit.GetType().GetProperties()
.FirstOrDefault(prop => prop.Name == file.Name && prop.PropertyType == typeof(byte[]));
if (matchingProperty != null)
{
var memoryStream = new MemoryStream();
await file.CopyToAsync(memoryStream);
matchingProperty.SetValue(entityToEdit, memoryStream.ToArray());
}
}
}
[HttpGet]
public IActionResult DeleteEntity(string dbSetName, string id)
{
var viewModel = new DataDeleteViewModel();
viewModel.DbSetName = dbSetName;
viewModel.Id = id;
viewModel.Object = GetEntityFromDbSet(dbSetName, id, out var dbContext, out var entityType, out var relationships);
if (viewModel.Object == null) return NotFound();
return View(viewModel);
}
[HttpPost]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> DeleteEntityPost([FromForm] DataDeleteViewModel viewModel)
{
foreach (var dbSetEntity in dbSetEntities.Where(db => db.Name.ToLowerInvariant() == viewModel.DbSetName.ToLowerInvariant()))
{
foreach (var dbSetProperty in dbSetEntity.DbContextType.GetProperties())
{
if (dbSetProperty.PropertyType.IsGenericType && dbSetProperty.PropertyType.Name.StartsWith("DbSet") && dbSetProperty.Name.ToLowerInvariant() == viewModel.DbSetName.ToLowerInvariant())
{
var dbContextObject = (DbContext)this.HttpContext.RequestServices.GetRequiredService(dbSetEntity.DbContextType);
var dbSetValue = dbSetProperty.GetValue(dbContextObject);
var primaryKey = dbContextObject.Model.FindEntityType(dbSetProperty.PropertyType.GetGenericArguments()[0]).FindPrimaryKey();
var clrType = primaryKey.Properties[0].ClrType;
object convertedPrimaryKey = viewModel.Id;
if (clrType == typeof(Guid))
{
convertedPrimaryKey = Guid.Parse(viewModel.Id);
}
else if(clrType == typeof(int))
{
convertedPrimaryKey = int.Parse(viewModel.Id);
}
else if (clrType == typeof(Int64))
{
convertedPrimaryKey = Int64.Parse(viewModel.Id);
}
var entityToDelete = dbSetValue.GetType().InvokeMember("Find", BindingFlags.InvokeMethod, null, dbSetValue, args: new object[] { convertedPrimaryKey });
dbSetValue.GetType().InvokeMember("Remove", BindingFlags.InvokeMethod, null, dbSetValue, args: new object[] {entityToDelete});
await dbContextObject.SaveChangesAsync();
}
}
}
return RedirectToAction("Index", new { Id = viewModel.DbSetName});
}
}
}