migrating to .NET Core 2.0

This commit is contained in:
RaidMax
2018-04-08 01:44:42 -05:00
parent 57fd5fae22
commit fdde7dfdba
121 changed files with 534 additions and 1157 deletions

View File

@ -0,0 +1,57 @@
using Microsoft.EntityFrameworkCore;
using SharedLibraryCore.Database.Models;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace SharedLibraryCore.Database
{
public class ContextSeed
{
private DatabaseContext context;
public ContextSeed(DatabaseContext ctx)
{
context = ctx;
}
public async Task Seed()
{
if (context.AliasLinks.Count() == 0)
{
context.AliasLinks.Add(new EFAliasLink()
{
AliasLinkId = 1
});
var currentAlias = new EFAlias()
{
AliasId = 1,
Active = true,
DateAdded = DateTime.UtcNow,
IPAddress = 0,
Name = "IW4MAdmin",
LinkId = 1
};
context.Aliases.Add(currentAlias);
context.Clients.Add(new EFClient()
{
ClientId = 1,
Active = false,
Connections = 0,
FirstConnection = DateTime.UtcNow,
LastConnection = DateTime.UtcNow,
Level = Objects.Player.Permission.Console,
Masked = true,
NetworkId = 0,
AliasLinkId = 1,
CurrentAliasId = 1,
});
await context.SaveChangesAsync();
}
}
}
}

View File

@ -0,0 +1,109 @@
using System;
using Microsoft.EntityFrameworkCore;
using SharedLibraryCore.Database.Models;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.Sqlite;
namespace SharedLibraryCore.Database
{
public class DatabaseContext : DbContext
{
public DbSet<EFClient> Clients { get; set; }
public DbSet<EFAlias> Aliases { get; set; }
public DbSet<EFAliasLink> AliasLinks { get; set; }
public DbSet<EFPenalty> Penalties { get; set; }
public DatabaseContext(DbContextOptions<DatabaseContext> opt) : base(opt) { }
public DatabaseContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = $"{currentPath}{Path.DirectorySeparatorChar}Database.db".Substring(6) };
var connectionString = connectionStringBuilder.ToString();
var connection = new SqliteConnection(connectionString);
optionsBuilder.UseSqlite(connection);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// make network id unique
modelBuilder.Entity<EFClient>(entity =>
{
entity.HasIndex(e => e.NetworkId).IsUnique();
});
modelBuilder.Entity<EFPenalty>(entity =>
{
entity.HasOne(p => p.Offender)
.WithMany(c => c.ReceivedPenalties)
.HasForeignKey(c => c.OffenderId)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne(p => p.Punisher)
.WithMany(p => p.AdministeredPenalties)
.HasForeignKey(c => c.PunisherId)
.OnDelete(DeleteBehavior.Restrict);
});
modelBuilder.Entity<EFAliasLink>(entity =>
{
entity.HasMany(e => e.Children)
.WithOne(a => a.Link)
.HasForeignKey(k => k.LinkId)
.OnDelete(DeleteBehavior.Restrict);
});
// https://aleemkhan.wordpress.com/2013/02/28/dynamically-adding-dbset-properties-in-dbcontext-for-entity-framework-code-first/
#if !DEBUG
foreach (string dllPath in Directory.GetFiles($"{Utilities.OperatingDirectory}Plugins"))
#else
IEnumerable<string> directoryFiles;
try
{
directoryFiles = Directory.GetFiles($@"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}Debug{Path.DirectorySeparatorChar}netcoreapp2.0{Path.DirectorySeparatorChar}Plugins").Where(f => f.Contains(".dll"));
}
catch (Exception)
{
directoryFiles = Directory.GetFiles($@"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}Plugins").Where(f => f.Contains(".dll"));
}
foreach (string dllPath in directoryFiles)
#endif
{
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

@ -0,0 +1,212 @@
using Microsoft.EntityFrameworkCore;
using SharedLibraryCore.Database.Models;
using SharedLibraryCore.Objects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharedLibraryCore.Database
{
//https://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework
public static class Importer
{
public static void ImportClients(IList<Player> clients)
{
DatabaseContext context = null;
try
{
context = new DatabaseContext();
int count = 0;
foreach (var entityToInsert in clients)
{
++count;
var link = new EFAliasLink() { Active = true };
var alias = new EFAlias()
{
Active = true,
DateAdded = entityToInsert.LastConnection,
IPAddress = entityToInsert.IPAddress,
Link = link,
Name = entityToInsert.Name,
};
var client = new EFClient()
{
Active = true,
AliasLink = link,
Connections = entityToInsert.Connections,
CurrentAlias = alias,
FirstConnection = entityToInsert.LastConnection,
Level = entityToInsert.Level,
LastConnection = entityToInsert.LastConnection,
TotalConnectionTime = entityToInsert.TotalConnectionTime,
Masked = entityToInsert.Masked,
NetworkId = entityToInsert.NetworkId
};
context = AddClient(context, client, count, 1000, true);
}
context.SaveChanges();
}
finally
{
if (context != null)
context.Dispose();
}
}
private static DatabaseContext AddClient(DatabaseContext context, EFClient client, int count, int commitCount, bool recreateContext)
{
context.Clients.Add(client);
if (count % commitCount == 0)
{
try
{
context.SaveChanges();
}
catch (Exception)
{
}
if (recreateContext)
{
context.Dispose();
context = new DatabaseContext();
}
}
return context;
}
public static void ImportPenalties(IList<Penalty> penalties)
{
DatabaseContext context = null;
try
{
context = new DatabaseContext();
int count = 0;
foreach (var entityToInsert in penalties)
{
++count;
var punisher = entityToInsert.Offender.NetworkId == entityToInsert.Punisher.NetworkId ?
context.Clients.SingleOrDefault(c => c.ClientId == 1) :
context.Clients.SingleOrDefault(c => c.NetworkId == entityToInsert.Punisher.NetworkId);
if (punisher == null)
continue;
var offender = context.Clients.Include("AliasLink").SingleOrDefault(c => c.NetworkId == entityToInsert.Offender.NetworkId);
if (offender == null)
continue;
var penalty = new EFPenalty()
{
Active = true,
Expires = entityToInsert.Expires.Year == 9999 ? DateTime.Parse(System.Data.SqlTypes.SqlDateTime.MaxValue.ToString()) : entityToInsert.Expires,
Offender = offender,
Punisher = punisher,
Offense = entityToInsert.Offense,
Type = entityToInsert.Type,
When = entityToInsert.When == DateTime.MinValue ? DateTime.UtcNow : entityToInsert.When,
Link = offender.AliasLink
};
context = AddPenalty(context, penalty, count, 1000, true);
}
context.SaveChanges();
}
finally
{
if (context != null)
context.Dispose();
}
}
private static DatabaseContext AddPenalty(DatabaseContext context, EFPenalty penalty, int count, int commitCount, bool recreateContext)
{
context.Penalties.Add(penalty);
if (count % commitCount == 0)
{
try
{
context.SaveChanges();
}
catch (Exception)
{
}
if (recreateContext)
{
context.Dispose();
context = new DatabaseContext();
}
}
return context;
}
public static void ImportSQLite<T>(IList<T> SQLiteData) where T : class
{
DatabaseContext context = null;
try
{
context = new DatabaseContext();
int count = 0;
foreach (var entityToInsert in SQLiteData)
{
++count;
context = AddSQLite(context, entityToInsert, count, 1000, true);
}
context.SaveChanges();
}
finally
{
if (context != null)
context.Dispose();
}
}
private static DatabaseContext AddSQLite<T>(DatabaseContext context, T entity, int count, int commitCount, bool recreateContext) where T : class
{
context.Set<T>().Add(entity);
if (count % commitCount == 0)
{
try
{
context.SaveChanges();
}
catch (Exception)
{
}
if (recreateContext)
{
context.Dispose();
context = new DatabaseContext();
}
}
return context;
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SharedLibraryCore.Database.Models
{
public class EFAlias : SharedEntity
{
[Key]
public int AliasId { get; set; }
[Required]
public int LinkId { get; set; }
[ForeignKey("LinkId")]
public virtual EFAliasLink Link { get; set; }
// [Index("IX_IPandName", 0, IsUnique = true)]
//[MaxLength(24)]
[Required]
public string Name { get; set; }
// [Index("IX_IPandName", 1, IsUnique = true)]
// [MaxLength(24)]
[Required]
public int IPAddress { get; set; }
[Required]
public DateTime DateAdded { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace SharedLibraryCore.Database.Models
{
public class EFAliasLink : SharedEntity
{
[Key]
public int AliasLinkId { get; set; }
public virtual ICollection<EFAlias> Children { get; set; }
public virtual ICollection<EFPenalty> ReceivedPenalties { get; set; }
public EFAliasLink()
{
Children = new List<EFAlias>();
ReceivedPenalties = new List<EFPenalty>();
}
}
}

View File

@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace SharedLibraryCore.Database.Models
{
public class EFClient : SharedEntity
{
[Key]
public int ClientId { get; set; }
public long NetworkId { get; set; }
[Required]
public int Connections { get; set; }
[Required]
// in seconds
public int TotalConnectionTime { get; set; }
[Required]
public DateTime FirstConnection { get; set; }
[Required]
public DateTime LastConnection { get; set; }
public bool Masked { get; set; }
[Required]
public int AliasLinkId { get; set; }
[ForeignKey("AliasLinkId")]
public virtual EFAliasLink AliasLink { get; set; }
[Required]
public Objects.Player.Permission Level { get; set; }
[Required]
public int CurrentAliasId { get; set; }
[ForeignKey("CurrentAliasId")]
public virtual EFAlias CurrentAlias { get; set; }
public string Password { get; set; }
public string PasswordSalt { get; set; }
[NotMapped]
public virtual string Name
{
get { return CurrentAlias.Name; }
set { }
}
[NotMapped]
public virtual int IPAddress
{
get { return CurrentAlias.IPAddress; }
set { }
}
[NotMapped]
public string IPAddressString => new System.Net.IPAddress(BitConverter.GetBytes(IPAddress)).ToString();
public virtual ICollection<EFPenalty> ReceivedPenalties { get; set; }
public virtual ICollection<EFPenalty> AdministeredPenalties { get; set; }
public EFClient()
{
ReceivedPenalties = new List<EFPenalty>();
AdministeredPenalties = new List<EFPenalty>();
}
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharedLibraryCore.Database.Models
{
public class EFPenalty : SharedEntity
{
[Key]
public int PenaltyId { get; set; }
[Required]
public int LinkId { get; set; }
[ForeignKey("LinkId")]
public virtual EFAliasLink Link { get; set; }
[Required]
public int OffenderId { get; set; }
[ForeignKey("OffenderId")]
public virtual EFClient Offender { get; set; }
[Required]
public int PunisherId { get; set; }
[ForeignKey("PunisherId")]
public virtual EFClient Punisher { get; set; }
[Required]
public DateTime When { get; set; }
[Required]
public DateTime Expires { get; set; }
[Required]
public string Offense { get; set; }
public Objects.Penalty.PenaltyType Type { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharedLibraryCore.Database.Models
{
public class SharedEntity
{
public bool Active { get; set; }
}
}