1
0
mirror of https://github.com/RaidMax/IW4M-Admin.git synced 2025-06-10 15:20:48 -05:00

Add libraries for EntityFramework

Stats plugin work
Allow plugins to dynamically add EF classes to the context
This commit is contained in:
RaidMax
2018-02-06 23:19:06 -06:00
parent 8ce8db5f30
commit 0b62cba52a
81 changed files with 113748 additions and 802 deletions

View File

@ -236,7 +236,7 @@ namespace SharedLibrary.Commands
public override async Task ExecuteAsync(Event E)
{
String You = String.Format("{0} [^3#{1}^7] {2} [^3@{3}^7] [{4}^7] IP: {5}", E.Origin.Name, E.Origin.ClientNumber, E.Origin.NetworkId, E.Origin.ClientNumber, Utilities.ConvertLevelToColor(E.Origin.Level), E.Origin.IPAddress);
String You = String.Format("{0} [^3#{1}^7] {2} [^3@{3}^7] [{4}^7] IP: {5}", E.Origin.Name, E.Origin.ClientNumber, E.Origin.NetworkId, E.Origin.ClientId, Utilities.ConvertLevelToColor(E.Origin.Level), E.Origin.IPAddress);
await E.Origin.Tell(You);
}
}
@ -351,7 +351,7 @@ namespace SharedLibrary.Commands
await E.Owner.Broadcast($"Fast restarting in ^53 ^7seconds [^5{E.Origin.Name}^7]");
else
await E.Owner.Broadcast($"Fast restarting in ^53 ^7seconds [^5Masked Admin^7]");
await Task.Delay(3000);
Task.Delay(3000).Wait();
await E.Owner.ExecuteCommandAsync("fast_restart");
}
}
@ -368,7 +368,7 @@ namespace SharedLibrary.Commands
await E.Owner.Broadcast($"Map rotating in ^55 ^7seconds [^5{E.Origin.Name}^7]");
else
await E.Owner.Broadcast($"Map rotating in ^55 ^7seconds [^5Masked Admin^7]");
await Task.Delay(5000);
Task.Delay(5000).Wait();
await E.Owner.ExecuteCommandAsync("map_rotate");
}
}
@ -497,14 +497,14 @@ namespace SharedLibrary.Commands
if (m.Name.ToLower() == newMap || m.Alias.ToLower() == newMap)
{
await E.Owner.Broadcast("Changing to map ^2" + m.Alias);
await Task.Delay(5000);
Task.Delay(5000).Wait();
await E.Owner.LoadMap(m.Name);
return;
}
}
await E.Owner.Broadcast("Attempting to change to unknown map ^1" + newMap);
await Task.Delay(5000);
Task.Delay(5000).Wait();
await E.Owner.LoadMap(newMap);
}
}

View File

@ -7,6 +7,7 @@ using System.Threading.Tasks;
using SharedLibrary.Database.Models;
using System.Data.SqlServerCe;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Reflection;
namespace SharedLibrary.Database
{
@ -31,7 +32,6 @@ namespace SharedLibrary.Database
.HasForeignKey(c => c.OffenderId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EFPenalty>()
.HasRequired(p => p.Punisher)
.WithMany(c => c.AdministeredPenalties)
@ -44,18 +44,35 @@ namespace SharedLibrary.Database
.HasForeignKey(a => a.LinkId)
.WillCascadeOnDelete(true);
/* modelBuilder.Entity<EFAlias>()
.HasIndex(a => new { a.IP, a.Name })
.IsUnique();
modelBuilder.Entity<EFAlias>()
.HasIndex(p => new { p.Name, p.IPAddress }).IsUnique();*/
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
// todo: custom load DBSets from plugins
// https://aleemkhan.wordpress.com/2013/02/28/dynamically-adding-dbset-properties-in-dbcontext-for-entity-framework-code-first/
foreach (string dllPath in System.IO.Directory.GetFiles($"{Environment.CurrentDirectory}{System.IO.Path.DirectorySeparatorChar}Plugins"))
{
Assembly library;
try
{
library = Assembly.LoadFile(dllPath);
}
// not a valid assembly, ie plugin files
catch (Exception)
{
continue;
}
foreach(var type in library.ExportedTypes)
{
if (type.IsClass && type.IsSubclassOf(typeof(SharedEntity)))
{
var method = modelBuilder.GetType().GetMethod("Entity");
method = method.MakeGenericMethod(new Type[] { type });
method.Invoke(modelBuilder, null);
}
}
}
base.OnModelCreating(modelBuilder);
}
}

View File

@ -37,9 +37,10 @@ namespace SharedLibrary.Helpers
return (DateTime.Now - StartTime).TotalMilliseconds;
}
public void Update(Task T)
public void Update(Task<bool> T)
{
RequestedTask = T;
Console.WriteLine($"Starting Task {T.Id} ");
RequestedTask.Start();
if (TimesRun > 25)

View File

@ -1,4 +1,5 @@
using System;
using System.Reflection;
namespace SharedLibrary
{

View File

@ -22,8 +22,13 @@ namespace SharedLibrary.Network
COMMAND,
}
static string[] SendQuery(QueryType Type, Server QueryServer, string Parameters = "")
private static DateTime LastQuery;
static string[] SendQuery(QueryType Type, Server QueryServer, string Parameters = "")
{
if ((DateTime.Now - LastQuery).TotalMilliseconds < 30)
Task.Delay(30).Wait();
LastQuery = DateTime.Now;
var ServerOOBConnection = new UdpClient();
ServerOOBConnection.Client.SendTimeout = 5000;
ServerOOBConnection.Client.ReceiveTimeout = 5000;
@ -91,7 +96,7 @@ namespace SharedLibrary.Network
}
Thread.Sleep(1000);
goto retry;
goto retry;
}
}
@ -134,7 +139,11 @@ namespace SharedLibrary.Network
public static async Task<List<Player>> GetStatusAsync(this Server server)
{
#if DEBUG
string[] response = await Task.Run(() => System.IO.File.ReadAllLines("players.txt"));
#else
string[] response = await Task.FromResult(SendQuery(QueryType.DVAR, server, "status"));
#endif
return Utilities.PlayersFromStatus(response);
}

View File

@ -115,7 +115,7 @@ namespace SharedLibrary
/// <returns></returns>
abstract public Task<Command> ValidateCommand(Event E);
virtual public Task ProcessUpdatesAsync(CancellationToken cts)
virtual public Task<bool> ProcessUpdatesAsync(CancellationToken cts)
{
return null;
}

View File

@ -54,11 +54,15 @@ namespace SharedLibrary.Services
public async Task<IList<EFAlias>> Find(Func<EFAlias, bool> expression)
{
using (var context = new DatabaseContext())
return await Task.Run(() => context.Aliases
.AsNoTracking()
.Include(a => a.Link.Children)
.Where(expression).ToList());
return await Task.Run(() =>
{
using (var context = new DatabaseContext())
return context.Aliases
.AsNoTracking()
.Include(a => a.Link.Children)
.Where(expression)
.ToList();
});
}
public async Task<EFAlias> Get(int entityID)

View File

@ -88,12 +88,15 @@ namespace SharedLibrary.Services
public async Task<IList<EFClient>> Find(Func<EFClient, bool> e)
{
using (var context = new DatabaseContext())
return await Task.Run(() => context.Clients
.AsNoTracking()
.Include(c => c.CurrentAlias)
.Include(c => c.AliasLink.Children)
.Where(e).ToList());
return await Task.Run(() =>
{
using (var context = new DatabaseContext())
return context.Clients
.AsNoTracking()
.Include(c => c.CurrentAlias)
.Include(c => c.AliasLink.Children)
.Where(e).ToList();
});
}
public async Task<EFClient> Get(int entityID)
@ -125,7 +128,7 @@ namespace SharedLibrary.Services
// grab the context version of the entity
var client = context.Clients
.Include(c => c.AliasLink)
.Include(c=> c.CurrentAlias)
.Include(c => c.CurrentAlias)
.Single(e => e.ClientId == entity.ClientId);
// if their level has been changed
@ -167,12 +170,12 @@ namespace SharedLibrary.Services
// this is set so future updates don't trigger a new alias add
if (entity.CurrentAlias.AliasId == 0)
entity.CurrentAlias.AliasId = client.CurrentAlias.AliasId;
entity.CurrentAlias.AliasId = client.CurrentAlias.AliasId;
return client;
}
}
#region ServiceSpecific
#region ServiceSpecific
public async Task<IList<EFClient>> GetOwners()
{
using (var context = new DatabaseContext())
@ -230,6 +233,6 @@ namespace SharedLibrary.Services
{
throw new NotImplementedException();
}
#endregion
#endregion
}
}

View File

@ -0,0 +1,146 @@
using SharedLibrary.Database;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace SharedLibrary.Services
{
// https://stackoverflow.com/questions/43677906/crud-operations-with-entityframework-using-generic-type
public class GenericRepository<TEntity> where TEntity : class
{
private dynamic _context;
private DbSet<TEntity> _dbSet;
protected DbContext Context
{
get
{
if (_context == null)
{
_context = new DatabaseContext();
}
return _context;
}
}
protected DbSet<TEntity> DBSet
{
get
{
if (_dbSet == null)
{
_dbSet = this.Context.Set<TEntity>();
}
return _dbSet;
}
}
public virtual IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderExpression = null)
{
return this.GetQuery(predicate, orderExpression).AsEnumerable();
}
public virtual IQueryable<TEntity> GetQuery(Expression<Func<TEntity, bool>> predicate = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderExpression = null)
{
IQueryable<TEntity> qry = this.DBSet;
if (predicate != null)
qry = qry.Where(predicate);
if (orderExpression != null)
return orderExpression(qry);
return qry;
}
public virtual void Insert<T>(T entity) where T : class
{
DbSet<T> dbSet = this.Context.Set<T>();
dbSet.Add(entity);
}
public virtual TEntity Insert(TEntity entity)
{
return this.DBSet.Add(entity);
}
public virtual void Update<T>(T entity) where T : class
{
DbSet<T> dbSet = this.Context.Set<T>();
dbSet.Attach(entity);
this.Context.Entry(entity).State = EntityState.Modified;
}
public virtual void Update(TEntity entity)
{
this.Attach(entity);
this.Context.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete<T>(T entity) where T : class
{
DbSet<T> dbSet = this.Context.Set<T>();
if (this.Context.Entry(entity).State == EntityState.Detached)
dbSet.Attach(entity);
dbSet.Remove(entity);
}
public virtual void Delete(TEntity entity)
{
if (this.Context.Entry(entity).State == EntityState.Detached)
this.Attach(entity);
this.DBSet.Remove(entity);
}
public virtual void Delete<T>(object[] id) where T : class
{
DbSet<T> dbSet = this.Context.Set<T>();
T entity = dbSet.Find(id);
dbSet.Attach(entity);
dbSet.Remove(entity);
}
public virtual void Delete(object id)
{
TEntity entity = this.DBSet.Find(id);
this.Delete(entity);
}
public virtual void Attach(TEntity entity)
{
if (this.Context.Entry(entity).State == EntityState.Detached)
this.DBSet.Attach(entity);
}
public virtual void SaveChanges()
{
this.Context.SaveChanges();
}
public virtual async Task SaveChangesAsync()
{
try
{
await this.Context.SaveChangesAsync();
}
catch (Exception e)
{
throw e;
}
}
}
}

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharedLibrary.Database;
namespace SharedLibrary.Services
{
public class GenericService<T> : Interfaces.IEntityService<T>
{
public async Task<T> Create(T entity)
{
using (var context = new DatabaseContext())
{
var dbSet = context.Set(entity.GetType());
T addedEntity = (T)dbSet.Add(entity);
await context.SaveChangesAsync();
return addedEntity;
}
}
public Task<T> CreateProxy()
{
throw new NotImplementedException();
}
public Task<T> Delete(T entity)
{
throw new NotImplementedException();
}
public Task<IList<T>> Find(Func<T, bool> expression)
{
throw new NotImplementedException();
}
public async Task<T> Get(int entityID)
{
using (var context = new DatabaseContext())
{
var dbSet = context.Set(typeof(T));
return (T)(await dbSet.FindAsync(entityID));
}
}
public async Task<T> Get(params object[] entityKeys)
{
using (var context = new DatabaseContext())
{
var dbSet = context.Set(typeof(T));
return (T)(await dbSet.FindAsync(entityKeys));
}
}
public Task<T> GetUnique(string entityProperty)
{
throw new NotImplementedException();
}
public Task<T> Update(T entity)
{
throw new NotImplementedException();
}
}
}

View File

@ -56,15 +56,16 @@ namespace SharedLibrary.Services
public async Task<IList<EFPenalty>> Find(Func<EFPenalty, bool> expression)
{
using (var context = new DatabaseContext())
return await Task.Run(() =>
{
return await Task.Run(() => context.Penalties
.Include(p => p.Offender)
.Include(p => p.Punisher)
.Where(expression)
.Where(p => p.Active)
.ToList());
}
using (var context = new DatabaseContext())
return context.Penalties
.Include(p => p.Offender)
.Include(p => p.Punisher)
.Where(expression)
.Where(p => p.Active)
.ToList();
});
}
public Task<EFPenalty> Get(int entityID)

View File

@ -137,6 +137,8 @@
<Compile Include="ServerConfiguration.cs" />
<Compile Include="Services\AliasService.cs" />
<Compile Include="Services\ClientService.cs" />
<Compile Include="Services\GenericRepository.cs" />
<Compile Include="Services\GenericService.cs" />
<Compile Include="Services\PenaltyService.cs" />
<Compile Include="Utilities.cs" />
<Compile Include="WebService.cs" />
@ -152,10 +154,6 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>move "$(TargetDir)Newtonsoft.Json.dll" "$(TargetDir)lib\Newtonsoft.Json.dll"
copy /Y "$(TargetDir)SQLite.Interop.dll" "$(SolutionDir)BUILD\lib"
copy /Y "$(TargetDir)System.Data.SQLite.dll" "$(SolutionDir)BUILD\lib"
copy /Y "$(TargetDir)SQLite.Interop.dll" "$(SolutionDir)Admin\lib"
copy /Y "$(TargetDir)System.Data.SQLite.dll" "$(SolutionDir)Admin\lib"
copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)BUILD\lib"
copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)Admin\lib"
copy /Y "$(TargetDir)Newtonsoft.Json.dll" "$(SolutionDir)BUILD\lib"

View File

@ -318,7 +318,8 @@ namespace SharedLibrary
IPAddress = client.CurrentAlias.IPAddress,
Level = client.Level,
LastConnection = DateTime.UtcNow,
CurrentAlias = client.CurrentAlias
CurrentAlias = client.CurrentAlias,
CurrentAliasId = client.CurrentAlias.AliasId
};
}
}