From 304437b834e8c87687f68333ae67a13ee1377a73 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Wed, 12 Jun 2019 21:47:51 +0200 Subject: Adjust Codestyle --- DSACore/Controllers/CommandsController.cs | 19 +-- DSACore/Controllers/LobbyController.cs | 19 +-- DSACore/Controllers/TokensController.cs | 11 +- DSACore/Hubs/Login.cs | 88 +++++--------- DSACore/Models/Network/Group.cs | 21 ++-- DSACore/Models/Network/Token.cs | 12 +- DSACore/Models/Network/User.cs | 6 +- DSACore/Program.cs | 12 +- DSACore/Startup.cs | 16 +-- dsa/DSALib/Auxiliary/Calculator/Argument.cs | 15 +-- dsa/DSALib/Auxiliary/Calculator/ISolvable.cs | 6 +- dsa/DSALib/Auxiliary/Calculator/Operator.cs | 18 +-- dsa/DSALib/Auxiliary/Calculator/Ops.cs | 6 +- dsa/DSALib/Auxiliary/Calculator/StringSolver.cs | 60 ++++------ dsa/DSALib/Auxiliary/CommandInfo.cs | 12 +- dsa/DSALib/Auxiliary/Dice.cs | 20 ++-- dsa/DSALib/Auxiliary/Extensions.cs | 12 +- .../Auxiliary/IDataObjectEnumerableExtension.cs | 22 ++-- dsa/DSALib/Auxiliary/RandomMisc.cs | 21 ++-- dsa/DSALib/Auxiliary/SpellCorrect.cs | 48 ++++---- dsa/DSALib/Auxiliary/TalentEnumerableExtension.cs | 22 ++-- dsa/DSALib/Auxiliary/WeaponImporter.cs | 48 +++----- dsa/DSALib/Characters/Being.cs | 6 +- dsa/DSALib/Characters/Critter.cs | 36 ++---- dsa/DSALib/Characters/Entity.cs | 9 +- dsa/DSALib/Characters/ICharacter.cs | 6 +- dsa/DSALib/Characters/ICombatant.cs | 6 +- dsa/DSALib/Commands/CommandHandler.cs | 25 ++-- dsa/DSALib/Commands/CommandTypes.cs | 6 +- dsa/DSALib/Commands/FileHandler.cs | 13 +-- dsa/DSALib/Commands/Gm.cs | 3 +- dsa/DSALib/Commands/HeldList.cs | 24 ++-- dsa/DSALib/Commands/Help.cs | 18 +-- dsa/DSALib/Commands/LebenUndAstral.cs | 77 +++++------- dsa/DSALib/Commands/List.cs | 15 +-- dsa/DSALib/Commands/MiscCommands.cs | 6 +- dsa/DSALib/Commands/NpcCommands.cs | 17 +-- dsa/DSALib/Commands/ProbenTest.cs | 6 +- dsa/DSALib/DSA_Game/Characters/Character.cs | 58 ++++----- dsa/DSALib/DSA_Game/Characters/NPC.cs | 31 ++--- dsa/DSALib/DSA_Game/Characters/SaveChar.cs | 18 +-- dsa/DSALib/DSA_Game/Dsa.cs | 30 ++--- dsa/DSALib/DSA_Game/Save/Properties.cs | 33 ++---- dsa/DSALib/DSA_Game/Save/SaveCommand.cs | 27 ++--- dsa/DSALib/DSA_Game/Save/Session.cs | 24 ++-- dsa/DSALib/FireBase/Database.cs | 98 ++++++---------- dsa/DSALib/Models/Database/DataObject.cs | 14 +-- dsa/DSALib/Models/Database/Dsa/Advantage.cs | 9 +- dsa/DSALib/Models/Database/Dsa/CharSpell.cs | 9 +- dsa/DSALib/Models/Database/Dsa/DatabaseChar.cs | 15 +-- dsa/DSALib/Models/Database/Dsa/Field.cs | 9 +- dsa/DSALib/Models/Database/Dsa/GeneralSpell.cs | 15 +-- dsa/DSALib/Models/Database/Dsa/GroupChar.cs | 6 +- dsa/DSALib/Models/Database/Dsa/Inventory.cs | 6 +- dsa/DSALib/Models/Database/Dsa/Talent.cs | 15 +-- dsa/DSALib/Models/Database/Dsa/Weapon.cs | 24 ++-- dsa/DSALib/Models/Database/Dsa/WeaponTalent.cs | 9 +- dsa/DSALib/Models/Database/Groups/DSAGroup.cs | 6 +- dsa/DSALib/Models/Database/Groups/Group.cs | 6 +- dsa/DSALib/Models/Database/IDataObject.cs | 6 +- dsa/DSALib/Models/Dsa/CritterAttack.cs | 11 +- dsa/DSALib/Models/Dsa/KampfTalent.cs | 11 +- dsa/DSALib/Models/Dsa/Talent.cs | 16 ++- dsa/DSALib/Models/Dsa/Vorteil.cs | 10 +- dsa/DSALib/Models/Dsa/Zauber.cs | 9 +- dsa/DSALib/Models/Network/Command.cs | 6 +- dsa/DSALib/Models/Network/CommandResponse.cs | 15 +-- dsa/FireBase/ExceptionEventArgs.cs | 15 +-- dsa/FireBase/Extensions/ObservableExtensions.cs | 12 +- dsa/FireBase/Extensions/TaskExtensions.cs | 15 +-- dsa/FireBase/FirebaseClient.cs | 15 +-- dsa/FireBase/FirebaseException.cs | 15 +-- dsa/FireBase/FirebaseKeyGenerator.cs | 21 ++-- dsa/FireBase/FirebaseObject.cs | 9 +- dsa/FireBase/FirebaseOptions.cs | 9 +- dsa/FireBase/Http/HttpClientExtensions.cs | 24 ++-- dsa/FireBase/Http/PostResult.cs | 6 +- dsa/FireBase/ObservableExtensions.cs | 18 +-- dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs | 51 +++----- dsa/FireBase/Offline/DatabaseExtensions.cs | 39 +++---- dsa/FireBase/Offline/ISetHandler.cs | 6 +- dsa/FireBase/Offline/InitialPullStrategy.cs | 6 +- .../Offline/Internals/MemberAccessVisitor.cs | 24 ++-- dsa/FireBase/Offline/OfflineCacheAdapter.cs | 72 ++++-------- dsa/FireBase/Offline/OfflineDatabase.cs | 51 +++----- dsa/FireBase/Offline/OfflineEntry.cs | 18 +-- dsa/FireBase/Offline/RealtimeDatabase.cs | 129 +++++++-------------- dsa/FireBase/Offline/SetHandler.cs | 12 +- dsa/FireBase/Offline/StreamingOptions.cs | 6 +- dsa/FireBase/Offline/SyncOptions.cs | 6 +- dsa/FireBase/Query/AuthQuery.cs | 12 +- dsa/FireBase/Query/ChildQuery.cs | 15 +-- dsa/FireBase/Query/FilterQuery.cs | 21 ++-- dsa/FireBase/Query/FirebaseQuery.cs | 99 ++++++---------- dsa/FireBase/Query/IFirebaseQuery.cs | 6 +- dsa/FireBase/Query/OrderQuery.cs | 12 +- dsa/FireBase/Query/ParameterQuery.cs | 12 +- dsa/FireBase/Query/QueryExtensions.cs | 60 ++++------ dsa/FireBase/Query/QueryFactoryExtensions.cs | 51 +++----- dsa/FireBase/Query/SilentQuery.cs | 12 +- dsa/FireBase/Streaming/FirebaseCache.cs | 60 ++++------ dsa/FireBase/Streaming/FirebaseEvent.cs | 12 +- dsa/FireBase/Streaming/FirebaseEventSource.cs | 6 +- dsa/FireBase/Streaming/FirebaseEventType.cs | 6 +- dsa/FireBase/Streaming/FirebaseServerEventType.cs | 6 +- dsa/FireBase/Streaming/FirebaseSubscription.cs | 66 ++++------- dsa/FireBase/Streaming/NonBlockingStreamReader.cs | 21 ++-- .../Auxiliary/Calculator/ArgumentTests.cs | 39 +++---- .../Auxiliary/Calculator/StringSolverTests.cs | 79 ++++++------- dsa/NUnitTestProject1/Auxiliary/DiceTests.cs | 53 ++++----- 110 files changed, 882 insertions(+), 1678 deletions(-) diff --git a/DSACore/Controllers/CommandsController.cs b/DSACore/Controllers/CommandsController.cs index b6e0be2..2edbbaf 100644 --- a/DSACore/Controllers/CommandsController.cs +++ b/DSACore/Controllers/CommandsController.cs @@ -1,20 +1,16 @@ using System; -using DSACore.Models.Network; using DSALib.Commands; using DSALib.Models.Network; using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 -namespace DSACore.Controllers -{ +namespace DSACore.Controllers { [Route("dsa/[controller]")] - public class CommandsController : Controller - { + public class CommandsController : Controller { // GET: api/ [HttpGet] - public string Get() - { + public string Get() { return "Usage: post the command to execute"; } @@ -27,14 +23,11 @@ namespace DSACore.Controllers // POST api//Felis [HttpPost] - public string Post([FromBody] Command cmd) - { - try - { + public string Post([FromBody] Command cmd) { + try { return CommandHandler.ExecuteCommand(cmd).message; } - catch (Exception e) - { + catch (Exception e) { return $"Ein Fehler ist aufgetreten: \n {e.Message}"; } } diff --git a/DSACore/Controllers/LobbyController.cs b/DSACore/Controllers/LobbyController.cs index 7890b4f..41ce436 100644 --- a/DSACore/Controllers/LobbyController.cs +++ b/DSACore/Controllers/LobbyController.cs @@ -1,30 +1,23 @@ using System; -using DSACore.Models.Network; using DSALib.Commands; using DSALib.Models.Network; using Microsoft.AspNetCore.Mvc; -namespace DSACore.Controllers -{ - public class ScribbleController : Controller - { +namespace DSACore.Controllers { + public class ScribbleController : Controller { [Route("[controller]")] // GET: api/ [HttpGet] - public string Get() - { + public string Get() { return "Usage: get /tokens/{Token}"; } [HttpPost] - public string Post([FromBody] Command cmd) - { - try - { + public string Post([FromBody] Command cmd) { + try { return CommandHandler.ExecuteCommand(cmd).message; } - catch (Exception e) - { + catch (Exception e) { return $"Ein Fehler ist aufgetreten: \n {e.Message}"; } } diff --git a/DSACore/Controllers/TokensController.cs b/DSACore/Controllers/TokensController.cs index a85cabe..f1ddb37 100644 --- a/DSACore/Controllers/TokensController.cs +++ b/DSACore/Controllers/TokensController.cs @@ -1,21 +1,18 @@ using DSACore.Hubs; using Microsoft.AspNetCore.Mvc; -namespace DSACore.Controllers -{ +namespace DSACore.Controllers { [Route("lobby/[controller]")] [ApiController] - public class TokensController : Controller - { + public class TokensController : Controller { // GET [HttpGet("{token}")] - public ActionResult Get(string token) - { + public ActionResult Get(string token) { if (!int.TryParse(token, out var intToken)) return BadRequest("The token has to be a 32 bit unsigned integer"); if (intToken == 42) return Ok("Scribble"); - + if (!Users.Tokens.Exists(x => x.GetHashCode() == intToken)) return NotFound(); var group = Users.Tokens.Find(x => x.GetHashCode() == intToken); diff --git a/DSACore/Hubs/Login.cs b/DSACore/Hubs/Login.cs index f08c24a..80ee29c 100644 --- a/DSACore/Hubs/Login.cs +++ b/DSACore/Hubs/Login.cs @@ -10,18 +10,15 @@ using DSALib.DSA_Game.Characters; using DSALib.FireBase; using DSALib.Models.Network; using Microsoft.AspNetCore.SignalR; -using Group = DSACore.Models.Network.Group; -namespace DSACore.Hubs -{ - public class Users : Hub - { +namespace DSACore.Hubs { + public class Users : Hub { //private static Dictionary UserGroup = new Dictionary(); private const string ReceiveMethod = "ReceiveMessage"; //receiveMethod; static Users() { - DsaGroups = Database.GetGroups().Result.Select(x=>new Group(x.Item1, x.Item2)).ToList(); + DsaGroups = Database.GetGroups().Result.Select(x => new Group(x.Item1, x.Item2)).ToList(); DsaGroups.Add(new Group("login", "")); DsaGroups.Add(new Group("online", "")); //AddGroups(); @@ -31,20 +28,16 @@ namespace DSACore.Hubs public static List Tokens { get; } = new List(); - public async Task SendMessage(string user, string message) - { - try - { + public async Task SendMessage(string user, string message) { + try { var group = getGroup(Context.ConnectionId).Name; } - catch (InvalidOperationException) - { - await Clients.Caller.SendCoreAsync(ReceiveMethod, - new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" }); + catch (InvalidOperationException) { + await Clients.Caller.SendCoreAsync(ReceiveMethod, + new object[] {"Nutzer ist in keiner Gruppe. Erst joinen!"}); } - if (message[0] == '/') - { + if (message[0] == '/') { var args = message.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList(); var Timon = args.Any(x => x == "hallo"); @@ -52,16 +45,14 @@ namespace DSACore.Hubs var ident = args.First().Replace("/", ""); if (args.Count > 0) args.RemoveAt(0); - var ret = CommandHandler.ExecuteCommand(new Command - { + var ret = CommandHandler.ExecuteCommand(new Command { CharId = 0, CmdIdentifier = ident, CmdTexts = args, Name = user }); - switch (ret.ResponseType) - { + switch (ret.ResponseType) { case ResponseType.Caller: case ResponseType.Error: await Clients.Caller.SendAsync(ReceiveMethod, ret.message); @@ -71,34 +62,28 @@ namespace DSACore.Hubs break; } } - else - { + else { await SendToGroup(message); } } - private Task SendToGroup(string message) - { - try - { + private Task SendToGroup(string message) { + try { var group = getGroup(Context.ConnectionId).Name; return Clients.Group(group).SendCoreAsync(ReceiveMethod, new object[] {getUser(Context.ConnectionId).Name, message}); } - catch (InvalidOperationException) - { + catch (InvalidOperationException) { return Clients.Caller.SendCoreAsync(ReceiveMethod, new object[] {"Nutzer ist in keiner Gruppe. Erst joinen!"}); } } - private Group getGroup(string id) - { + private Group getGroup(string id) { return DsaGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))); } - private User getUser(string id) - { + private User getUser(string id) { return DsaGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))).Users .First(z => z.ConnectionId.Equals(id)); } @@ -113,8 +98,7 @@ namespace DSACore.Hubs //throw new NotImplementedException("add database call to get groups"); } - public async Task AddGroup(string group, string password) - { + public async Task AddGroup(string group, string password) { DsaGroups.Add(new Group(group, password)); var Dgroup = new DSALib.Models.Database.Groups.Group {Name = group, Id = DsaGroups.Count - 1}; //Database.AddGroup(Dgroup); @@ -122,22 +106,18 @@ namespace DSACore.Hubs //throw new NotImplementedException("add database call to add groups"); } - public async Task UploadChar(string xml) - { + public async Task UploadChar(string xml) { var group = getGroup(Context.ConnectionId); await Database.AddChar(new Character(new MemoryStream(Encoding.UTF8.GetBytes(xml))), group.Name); //throw new NotImplementedException("add database call to add groups"); } - public async Task Login(string group, string user, string hash) - { + public async Task Login(string group, string user, string hash) { //string password = System.Text.Encoding.UTF8.GetString(hash); - if (hash == DsaGroups.First(x => x.Name == group).Password) - { + if (hash == DsaGroups.First(x => x.Name == group).Password) { var gGroup = DsaGroups.First(x => x.Name.Equals(group)); - if (!gGroup.Users.Exists(x => x.Name.Equals(user))) - { + if (!gGroup.Users.Exists(x => x.Name.Equals(user))) { await Groups.RemoveFromGroupAsync(Context.ConnectionId, "login"); await Groups.AddToGroupAsync(Context.ConnectionId, group); gGroup.Users.Add(new User {ConnectionId = Context.ConnectionId, Name = user}); @@ -149,42 +129,35 @@ namespace DSACore.Hubs await Clients.Caller.SendAsync("Token", Tokens.Last().GetHashCode()); purgeTokens(); } - else - { + else { await Clients.Caller.SendAsync("LoginResponse", 1); } } - else - { + else { await Clients.Caller.SendAsync("LoginResponse", 2); //await Clients.Caller.SendAsync(receiveMethod, "Falsches Passwort!"); } } - private void purgeTokens() - { + private void purgeTokens() { Tokens.RemoveAll(x => !x.IsValid()); } - public override Task OnDisconnectedAsync(Exception exception) - { + public override Task OnDisconnectedAsync(Exception exception) { Disconnect().Wait(); return base.OnDisconnectedAsync(exception); } - public override Task OnConnectedAsync() - { + public override Task OnConnectedAsync() { Groups.AddToGroupAsync(Context.ConnectionId, "login").Wait(); Groups.AddToGroupAsync(Context.ConnectionId, "online").Wait(); return base.OnConnectedAsync(); } - public async Task Disconnect() - { + public async Task Disconnect() { await Groups.RemoveFromGroupAsync(Context.ConnectionId, "online"); if (DsaGroups.Exists(x => x.Users.Exists(y => y.ConnectionId == Context.ConnectionId))) - try - { + try { var group = getGroup(Context.ConnectionId); @@ -195,8 +168,7 @@ namespace DSACore.Hubs group.Users.Remove(user); await Groups.RemoveFromGroupAsync(Context.ConnectionId, group.Name); } - catch (Exception e) - { + catch (Exception e) { Console.WriteLine(e); //throw; } diff --git a/DSACore/Models/Network/Group.cs b/DSACore/Models/Network/Group.cs index efe12ee..aee9d02 100644 --- a/DSACore/Models/Network/Group.cs +++ b/DSACore/Models/Network/Group.cs @@ -1,18 +1,14 @@ using System; using System.Collections.Generic; -namespace DSACore.Models.Network -{ - public class Group - { - public Group(string name, string password) - { +namespace DSACore.Models.Network { + public class Group { + public Group(string name, string password) { Name = name; Password = password; } - public Group(string name, int userOnline) - { + public Group(string name, int userOnline) { Name = name ?? throw new ArgumentNullException(nameof(name)); } @@ -22,16 +18,13 @@ namespace DSACore.Models.Network public int UserCount => Users.Count; - public SendGroup SendGroup() - { + public SendGroup SendGroup() { return new SendGroup(Name, UserCount); } } - public class SendGroup - { - public SendGroup(string name, int userCount) - { + public class SendGroup { + public SendGroup(string name, int userCount) { Name = name ?? throw new ArgumentNullException(nameof(name)); UserCount = userCount; } diff --git a/DSACore/Models/Network/Token.cs b/DSACore/Models/Network/Token.cs index 451cafc..67b1853 100644 --- a/DSACore/Models/Network/Token.cs +++ b/DSACore/Models/Network/Token.cs @@ -1,20 +1,16 @@ using System; -namespace DSACore.Models.Network -{ - public class Token - { +namespace DSACore.Models.Network { + public class Token { private readonly DateTime creation = DateTime.Now; - public Token(string group) - { + public Token(string group) { Group = group; } public string Group { get; set; } - public bool IsValid() - { + public bool IsValid() { return DateTime.Now - creation < TimeSpan.FromMinutes(1); } } diff --git a/DSACore/Models/Network/User.cs b/DSACore/Models/Network/User.cs index 8b8008c..95a12b2 100644 --- a/DSACore/Models/Network/User.cs +++ b/DSACore/Models/Network/User.cs @@ -1,7 +1,5 @@ -namespace DSACore.Models.Network -{ - public class User - { +namespace DSACore.Models.Network { + public class User { public string Name { get; set; } public string ConnectionId { get; set; } public int Char { get; set; } diff --git a/DSACore/Program.cs b/DSACore/Program.cs index 8af0a74..2889734 100644 --- a/DSACore/Program.cs +++ b/DSACore/Program.cs @@ -3,19 +3,15 @@ using DSALib.FireBase; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; -namespace DSACore -{ - public class Program - { - public static void Main(string[] args) - { +namespace DSACore { + public class Program { + public static void Main(string[] args) { Database.GetGroup(0).Wait(); Dsa.Startup(); CreateWebHostBuilder(args).Build().Run(); } - public static IWebHostBuilder CreateWebHostBuilder(string[] args) - { + public static IWebHostBuilder CreateWebHostBuilder(string[] args) { return WebHost.CreateDefaultBuilder(args) .UseStartup() .UseUrls("http://0.0.0.0:5000"); diff --git a/DSACore/Startup.cs b/DSACore/Startup.cs index ef22802..e325f79 100644 --- a/DSACore/Startup.cs +++ b/DSACore/Startup.cs @@ -5,29 +5,23 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -namespace DSACore -{ - public class Startup - { - public Startup(IConfiguration configuration) - { +namespace DSACore { + public class Startup { + public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. - public void ConfigureServices(IServiceCollection services) - { - + public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. - public void Configure(IApplicationBuilder app, IHostingEnvironment env) - { + public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); else diff --git a/dsa/DSALib/Auxiliary/Calculator/Argument.cs b/dsa/DSALib/Auxiliary/Calculator/Argument.cs index e681377..d6be0c8 100644 --- a/dsa/DSALib/Auxiliary/Calculator/Argument.cs +++ b/dsa/DSALib/Auxiliary/Calculator/Argument.cs @@ -1,16 +1,13 @@ using System; -namespace DSALib.Auxiliary.Calculator -{ +namespace DSALib.Auxiliary.Calculator { /// /// Provides an ISolvable class to save numbers. The class handles Argument checking and conversion from string to int. /// - public class Argument : ISolvable - { + public class Argument : ISolvable { private readonly int value; - public Argument(string value) - { + public Argument(string value) { // check whether the value given is an empty string if (string.IsNullOrEmpty(value)) throw new ArgumentException("Argument kann nicht mit einem leeren string instanziert werden. ", @@ -22,13 +19,11 @@ namespace DSALib.Auxiliary.Calculator this.value = result; } - public int Solve() - { + public int Solve() { return value; } - public override string ToString() - { + public override string ToString() { return value.ToString(); } } diff --git a/dsa/DSALib/Auxiliary/Calculator/ISolvable.cs b/dsa/DSALib/Auxiliary/Calculator/ISolvable.cs index 844e9b3..b2ea779 100644 --- a/dsa/DSALib/Auxiliary/Calculator/ISolvable.cs +++ b/dsa/DSALib/Auxiliary/Calculator/ISolvable.cs @@ -1,10 +1,8 @@ -namespace DSALib.Auxiliary.Calculator -{ +namespace DSALib.Auxiliary.Calculator { /// /// Object has to be able to return an integer as it's value /// - public interface ISolvable - { + public interface ISolvable { int Solve(); } } \ No newline at end of file diff --git a/dsa/DSALib/Auxiliary/Calculator/Operator.cs b/dsa/DSALib/Auxiliary/Calculator/Operator.cs index e6aeec6..f3d5c9f 100644 --- a/dsa/DSALib/Auxiliary/Calculator/Operator.cs +++ b/dsa/DSALib/Auxiliary/Calculator/Operator.cs @@ -1,17 +1,14 @@ using System; using DSALibv.Auxiliary.Calculator; -namespace DSALib.Auxiliary.Calculator -{ +namespace DSALib.Auxiliary.Calculator { /// /// The Operator Class represents a binary operator with tow Arguments and an Operation type /// - public class Operator : ISolvable - { + public class Operator : ISolvable { private readonly ISolvable arg1, arg2; - public Operator(ISolvable arg1, ISolvable arg2, Ops operatorType) - { + public Operator(ISolvable arg1, ISolvable arg2, Ops operatorType) { this.arg1 = arg1; this.arg2 = arg2; OperatorType = operatorType; @@ -19,11 +16,9 @@ namespace DSALib.Auxiliary.Calculator public Ops OperatorType { get; set; } - public int Solve() - { + public int Solve() { int result; - switch (OperatorType) - { + switch (OperatorType) { case Ops.Dice: result = Dice.Roll(arg1.Solve(), arg2.Solve()); break; @@ -43,8 +38,7 @@ namespace DSALib.Auxiliary.Calculator return result; } - public override string ToString() - { + public override string ToString() { return $"({arg1} {OperatorType} {arg2})"; } } diff --git a/dsa/DSALib/Auxiliary/Calculator/Ops.cs b/dsa/DSALib/Auxiliary/Calculator/Ops.cs index 93046d0..cf1a8e7 100644 --- a/dsa/DSALib/Auxiliary/Calculator/Ops.cs +++ b/dsa/DSALib/Auxiliary/Calculator/Ops.cs @@ -1,10 +1,8 @@ -namespace DSALibv.Auxiliary.Calculator -{ +namespace DSALibv.Auxiliary.Calculator { /// /// The Different Operations, witch can be performed in execution-order /// - public enum Ops - { + public enum Ops { Dice, Multiply, Subtract, diff --git a/dsa/DSALib/Auxiliary/Calculator/StringSolver.cs b/dsa/DSALib/Auxiliary/Calculator/StringSolver.cs index 45d6a54..d46f8bc 100644 --- a/dsa/DSALib/Auxiliary/Calculator/StringSolver.cs +++ b/dsa/DSALib/Auxiliary/Calculator/StringSolver.cs @@ -3,24 +3,20 @@ using System.Collections.Generic; using System.Linq; using DSALibv.Auxiliary.Calculator; -namespace DSALib.Auxiliary.Calculator -{ +namespace DSALib.Auxiliary.Calculator { /// /// The StringSolver divides the calculation string into operations and SubStringSolvers if the string contains /// parentheses /// - public class StringSolver : ISolvable - { + public class StringSolver : ISolvable { private readonly List arguments = new List(); private readonly string input; - public StringSolver(string input) - { + public StringSolver(string input) { this.input = input; } - public int Solve() - { + public int Solve() { var workInput = "0+" + input.Replace(" ", string.Empty).ToLower(); workInput = ExpandParentheses(workInput); @@ -34,8 +30,7 @@ namespace DSALib.Auxiliary.Calculator return ((ISolvable) arguments.First()).Solve(); } - public override string ToString() - { + public override string ToString() { return "(0+" + input.Replace(" ", string.Empty).ToLower() + ")"; } @@ -43,23 +38,19 @@ namespace DSALib.Auxiliary.Calculator GetInner(ref string input) // extract the inner bracket an remove the section from the input string { var depth = 0; - for (var index = 1; index < input.Length; index++) - { + for (var index = 1; index < input.Length; index++) { var c = input[index]; - switch (c) - { + switch (c) { case '(': depth++; break; case ')': - if (depth == 0) - { + if (depth == 0) { var split = input.Substring(1, index - 1); input = input.Substring(index + 1); return split.Equals(string.Empty) ? "0" : split; } - else - { + else { depth--; } @@ -70,10 +61,8 @@ namespace DSALib.Auxiliary.Calculator throw new ArgumentException("Invalid brace sequence"); } - private static Ops GetOps(char c) - { - switch (c) - { + private static Ops GetOps(char c) { + switch (c) { case 'd': case 'w': return Ops.Dice; @@ -101,14 +90,11 @@ namespace DSALib.Auxiliary.Calculator return input; } - private void AtomizeOperations(string workInput) - { - for (var index = 0; index < workInput.Length; index++) - { + private void AtomizeOperations(string workInput) { + for (var index = 0; index < workInput.Length; index++) { var c = workInput[index]; - if (char.IsNumber(c)) - { + if (char.IsNumber(c)) { // if char number, check if at end of string, else continue looping if (index == workInput.Length - 1) // if at end of string; add remaining number to arguments @@ -117,8 +103,7 @@ namespace DSALib.Auxiliary.Calculator continue; } - switch (c) - { + switch (c) { case ')': throw new ArgumentException("Invalid brace sequence"); case '(': @@ -136,12 +121,10 @@ namespace DSALib.Auxiliary.Calculator } } - private void NestOperations() - { + private void NestOperations() { foreach (Ops currentOp in Enum.GetValues(typeof(Ops))) // cycle through operators in operational order - for (var index = 0; index < arguments.Count; index++) - { + for (var index = 0; index < arguments.Count; index++) { var arg = arguments[index]; if (arg.GetType() != typeof(Ops)) continue; @@ -162,19 +145,16 @@ namespace DSALib.Auxiliary.Calculator } } - private void HandleSpecialFormatting(ref int index, Ops op) - { + private void HandleSpecialFormatting(ref int index, Ops op) { var arg1 = arguments[index - 1]; - if (arg1.GetType() == typeof(Ops)) - { + if (arg1.GetType() == typeof(Ops)) { if (op == Ops.Dice) arguments.Insert(index++, new Argument("1")); // w6 -> 1w6 if (op == Ops.Subtract) arguments.Insert(index++, new Argument("0")); // +-3 -> +0-3 } var arg2 = arguments[index + 1]; // 3+-5 -> 3+(0-5) - if (arg2.GetType() == typeof(Ops)) - { + if (arg2.GetType() == typeof(Ops)) { arguments[index + 1] = new Operator(new Argument("0"), (ISolvable) arguments[index + 2], (Ops) arg2); arguments.RemoveAt(index + 2); } diff --git a/dsa/DSALib/Auxiliary/CommandInfo.cs b/dsa/DSALib/Auxiliary/CommandInfo.cs index d8e2188..80cc854 100644 --- a/dsa/DSALib/Auxiliary/CommandInfo.cs +++ b/dsa/DSALib/Auxiliary/CommandInfo.cs @@ -1,11 +1,8 @@ using System.Linq; -namespace DSALib.Auxiliary -{ - public struct CommandInfo - { - public CommandInfo(string name, string brief, string[] description, string scope) - { +namespace DSALib.Auxiliary { + public struct CommandInfo { + public CommandInfo(string name, string brief, string[] description, string scope) { Name = name; Scope = scope; Brief = brief; @@ -20,8 +17,7 @@ namespace DSALib.Auxiliary public string[] Description { get; } - public string GetDescription() - { + public string GetDescription() { return Description.Aggregate((s, c) => s + c); } } diff --git a/dsa/DSALib/Auxiliary/Dice.cs b/dsa/DSALib/Auxiliary/Dice.cs index 0bfabeb..36a4748 100644 --- a/dsa/DSALib/Auxiliary/Dice.cs +++ b/dsa/DSALib/Auxiliary/Dice.cs @@ -1,24 +1,22 @@ using System; using System.Linq; -namespace DSALib.Auxiliary -{ +namespace DSALib.Auxiliary { public static class Dice // roll it! { private static readonly Random Rnd = new Random(); - public static int Roll(int d = 20) - { + public static int Roll(int d = 20) { return Rnd.Next(d) + 1; } - public static int Roll(string input) - { + public static int Roll(string input) { var strings = input.ToLower().Split(new[] {'w', 'd'}, 2, StringSplitOptions.RemoveEmptyEntries).ToList(); - + if (strings.Count != 2) - throw new ArgumentException($"{input}: does not satisfy the format requirements( dice count (d|w) die size)"); + throw new ArgumentException( + $"{input}: does not satisfy the format requirements( dice count (d|w) die size)"); var count = Convert.ToInt32(strings[0]); var d = Convert.ToInt32(strings[0]); @@ -26,13 +24,11 @@ namespace DSALib.Auxiliary return Roll(count, d); } - public static int Roll(int count, int d) - { + public static int Roll(int count, int d) { if (d <= 0 || count <= 0) return 0; var sum = 0; - for (var i = 0; i < Math.Abs(count); i++) - { + for (var i = 0; i < Math.Abs(count); i++) { var roll = Roll(d); sum += roll; } diff --git a/dsa/DSALib/Auxiliary/Extensions.cs b/dsa/DSALib/Auxiliary/Extensions.cs index 7d367a5..b4fde67 100644 --- a/dsa/DSALib/Auxiliary/Extensions.cs +++ b/dsa/DSALib/Auxiliary/Extensions.cs @@ -1,11 +1,8 @@ -namespace DSALib.Auxiliary -{ - public static class StringExtension - { +namespace DSALib.Auxiliary { + public static class StringExtension { //This mehod extends string. It adds spaces until a fixed length is reached. //If the original string is already longer, it is returner unmodified. - public static string AddSpaces(this string str, int length) - { + public static string AddSpaces(this string str, int length) { var temp = str; for (var i = str.Length; i < length; i++) temp += " "; return temp; @@ -15,8 +12,7 @@ //This mehod extends string. //It adds spaces at the HEAD of a string until a fixed length is reached. //If the original string is already longer, it is returner unmodified. - public static string AddSpacesAtHead(this string str, int length) - { + public static string AddSpacesAtHead(this string str, int length) { var temp = ""; for (var i = str.Length; i < length; i++) temp += " "; return temp + str; diff --git a/dsa/DSALib/Auxiliary/IDataObjectEnumerableExtension.cs b/dsa/DSALib/Auxiliary/IDataObjectEnumerableExtension.cs index b8a6067..d695baf 100644 --- a/dsa/DSALib/Auxiliary/IDataObjectEnumerableExtension.cs +++ b/dsa/DSALib/Auxiliary/IDataObjectEnumerableExtension.cs @@ -1,25 +1,21 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text.RegularExpressions; -using System.Threading.Tasks; using DSALib.Auxiliary; using DSALib.Models.Database; -namespace DSACore.Auxiliary -{ - public static class DataObjectEnumerableExtension - { - public static IDataObject Match(this IEnumerable dataObjects, string name) - { - return (dataObjects as IOrderedEnumerable ?? throw new InvalidOperationException()).OrderBy(x => SpellCorrect.Compare(name,x.Name)).Last(); +namespace DSACore.Auxiliary { + public static class DataObjectEnumerableExtension { + public static IDataObject Match(this IEnumerable dataObjects, string name) { + return (dataObjects as IOrderedEnumerable ?? throw new InvalidOperationException()) + .OrderBy(x => SpellCorrect.Compare(name, x.Name)).Last(); } - public static bool TryMatch(this IEnumerable dataObjects,out IDataObject data, string name) - { - data = (dataObjects as IOrderedEnumerable ?? throw new InvalidOperationException()).OrderBy(x => SpellCorrect.Compare(name,x.Name)).Last(); + public static bool TryMatch(this IEnumerable dataObjects, out IDataObject data, string name) { + data = (dataObjects as IOrderedEnumerable ?? throw new InvalidOperationException()) + .OrderBy(x => SpellCorrect.Compare(name, x.Name)).Last(); return SpellCorrect.IsMatch(name, data.Name); } } -} +} \ No newline at end of file diff --git a/dsa/DSALib/Auxiliary/RandomMisc.cs b/dsa/DSALib/Auxiliary/RandomMisc.cs index 2723930..f78a25d 100644 --- a/dsa/DSALib/Auxiliary/RandomMisc.cs +++ b/dsa/DSALib/Auxiliary/RandomMisc.cs @@ -2,35 +2,29 @@ using System.Linq; using System.Text; -namespace DSALib.Auxiliary -{ - public static class RandomMisc - { +namespace DSALib.Auxiliary { + public static class RandomMisc { private static readonly Random Rand = new Random(); // use: 4w6 +4 - public static string Roll(string input) - { + public static string Roll(string input) { var output = new StringBuilder(); var strings = input.Split('w', 'd').ToList(); var count = Convert.ToInt32(strings[0]); strings = strings[1].Split(' ').ToList(); var d = Convert.ToInt32(strings[0]); - if (strings.Count > 0) - { + if (strings.Count > 0) { } var sum = 0; - for (var i = 0; i < count; i++) - { + for (var i = 0; i < count; i++) { var roll = Dice.Roll(d); sum += roll; output.Append("[" + roll + "] "); } - if (strings.Count > 1) - { + if (strings.Count > 1) { sum += Convert.ToInt32(strings[1]); output.Append("sum: " + sum); } @@ -38,8 +32,7 @@ namespace DSALib.Auxiliary return output.ToString(); } - public static double Random(double stdDev = 1, double mean = 0) - { + public static double Random(double stdDev = 1, double mean = 0) { var u1 = Rand.NextDouble(); // uniform(0,1) random doubles var u2 = Rand.NextDouble(); var randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) * diff --git a/dsa/DSALib/Auxiliary/SpellCorrect.cs b/dsa/DSALib/Auxiliary/SpellCorrect.cs index 79908c4..3b98942 100644 --- a/dsa/DSALib/Auxiliary/SpellCorrect.cs +++ b/dsa/DSALib/Auxiliary/SpellCorrect.cs @@ -1,21 +1,16 @@ -using System; - -namespace DSALib.Auxiliary -{ - public class SpellCorrect - { - public const double ErrorThreshold = 1 / 3.0; +namespace DSALib.Auxiliary { + public class SpellCorrect { + public const double ErrorThreshold = 1 / 3.0; private const double Match = 3.0; private const double Gap = -1.5; private const double Mismatch = -2.0; - public static double Compare(string s, string q) - { + public static double Compare(string s, string q) { s = s.ToLower(); q = q.ToLower(); int i, j; - + var matrix = new double[s.Length + 1, q.Length + 1]; var max = 0.0; matrix[0, 0] = 0.0; @@ -27,33 +22,30 @@ namespace DSALib.Auxiliary for (i = 1; i <= s.Length; i++) - for (j = 1; j <= q.Length; j++) - { - double decay = j / (s.Length * 1000.0); - var add = s[i - 1] == q[j - 1] ? Match - decay : Mismatch; - var score = matrix[i - 1, j - 1] + add; + for (j = 1; j <= q.Length; j++) { + var decay = j / (s.Length * 1000.0); + var add = s[i - 1] == q[j - 1] ? Match - decay : Mismatch; + var score = matrix[i - 1, j - 1] + add; - if (score < matrix[i - 1, j] + Gap) score = matrix[i - 1, j] + Gap; + if (score < matrix[i - 1, j] + Gap) score = matrix[i - 1, j] + Gap; - if (score < matrix[i, j - 1] + Gap) score = matrix[i, j - 1] + Gap; + if (score < matrix[i, j - 1] + Gap) score = matrix[i, j - 1] + Gap; - if (i > 1 && j > 1) - if (s[i - 1] == q[j - 2] && s[i - 2] == q[j - 1]) - { - add = 3 / 2.0 * Match - decay; - if (score < matrix[i - 2, j - 2] + add) score = matrix[i - 2, j - 2] + add; - } + if (i > 1 && j > 1) + if (s[i - 1] == q[j - 2] && s[i - 2] == q[j - 1]) { + add = 3 / 2.0 * Match - decay; + if (score < matrix[i - 2, j - 2] + add) score = matrix[i - 2, j - 2] + add; + } - if (max < score && i == s.Length) max = score; + if (max < score && i == s.Length) max = score; - matrix[i, j] = score; - } + matrix[i, j] = score; + } return max; } - public static bool IsMatch(string s1, string s2) - { + public static bool IsMatch(string s1, string s2) { var score = Compare(s1, s2); return score > ErrorThreshold * s1.Length; } diff --git a/dsa/DSALib/Auxiliary/TalentEnumerableExtension.cs b/dsa/DSALib/Auxiliary/TalentEnumerableExtension.cs index 6ec7fcc..fd2895b 100644 --- a/dsa/DSALib/Auxiliary/TalentEnumerableExtension.cs +++ b/dsa/DSALib/Auxiliary/TalentEnumerableExtension.cs @@ -5,12 +5,10 @@ using DSACore.Auxiliary; using DSALib.DSA_Game.Characters; using DSALib.Models.Dsa; -namespace DSALib.Auxiliary -{ - public static class TalentEnumerableExtension - { - public static string ProbenTest(this IEnumerable List, Character c, string talentName, int erschwernis = 0) - { +namespace DSALib.Auxiliary { + public static class TalentEnumerableExtension { + public static string ProbenTest(this IEnumerable List, Character c, string talentName, + int erschwernis = 0) { var output = new StringBuilder(); var sc = new SpellCorrect(); @@ -34,11 +32,9 @@ namespace DSALib.Auxiliary output.Append(" "); tap -= erschwernis; var gesamtErschwernis = tap; - if (gesamtErschwernis < 0) - { + if (gesamtErschwernis < 0) { tap = 0; - for (var i = 0; i <= 2; i++) - { + for (var i = 0; i <= 2; i++) { // foreach property, dice and tap var temp = Dice.Roll(); var eigenschaft = c.Eigenschaften[c.PropTable[props[i]]]; @@ -50,10 +46,8 @@ namespace DSALib.Auxiliary if (tap >= 0) tap = 1; } - else - { - for (var i = 0; i <= 2; i++) - { + else { + for (var i = 0; i <= 2; i++) { // foreach property, dice and tap var temp = Dice.Roll(); var eigenschaft = c.Eigenschaften[c.PropTable[props[i]]]; diff --git a/dsa/DSALib/Auxiliary/WeaponImporter.cs b/dsa/DSALib/Auxiliary/WeaponImporter.cs index 61eb33e..a3e7582 100644 --- a/dsa/DSALib/Auxiliary/WeaponImporter.cs +++ b/dsa/DSALib/Auxiliary/WeaponImporter.cs @@ -7,20 +7,16 @@ using System.Threading.Tasks; using DSALib.FireBase; using DSALib.Models.Database.Dsa; -namespace DSALib.Auxiliary -{ - public class WeaponImporter - { +namespace DSALib.Auxiliary { + public class WeaponImporter { private readonly List Range = new List(); private readonly List Weapons = new List(); - public async Task DownloadWeapons() - { + public async Task DownloadWeapons() { var client = new HttpClient(); - for (var i = 1; i <= 25; i++) - { + for (var i = 1; i <= 25; i++) { var responseString = await client.GetStringAsync("http://diarium.eu/dsa4-forge/ajax/categoryChanged/" + i); @@ -35,15 +31,13 @@ namespace DSALib.Auxiliary var ids = new List(); foreach (var matchGroup in talentMatch.ToList()) - if (matchGroup.Success) - { + if (matchGroup.Success) { lines.Add(matchGroup.Groups[3].Value); ids.Add(int.Parse(matchGroup.Groups[1].Value)); } - for (var j = 0; j < lines.Count; j++) - { + for (var j = 0; j < lines.Count; j++) { var talent = lines[j]; var values = await client.GetStringAsync("http://diarium.eu/dsa4-forge/ajax/calculate/" + i + "/" + @@ -71,18 +65,15 @@ namespace DSALib.Auxiliary Console.ReadLine(); } - private async Task AddMelee(int i, string talent, List matches) - { + private async Task AddMelee(int i, string talent, List matches) { var name = talent.Replace(' ', '_').Replace(".", ""); - if (!matches[1].Equals(string.Empty)) - { + if (!matches[1].Equals(string.Empty)) { var temp = new MeleeWeapon( name, matches[1], int.TryParse(matches[10], out var weight) ? weight : 0, matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(), - matches[11]) - { + matches[11]) { INI = int.TryParse(matches[3], out var ini) ? ini : 0, MW = matches[4], TpKK = matches[2] @@ -111,15 +102,13 @@ namespace DSALib.Auxiliary await Database.AddWeapon(range); return; }*/ - if (i > 18) - { + if (i > 18) { var range = new RangedWeapon( name, matches[13].Replace(' ', '+'), int.TryParse(matches[10], out var weight) ? weight : 0, matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(), - matches[11]) - { + matches[11]) { AtMod = int.TryParse(matches[18], out var atMod) ? atMod : 0, KKMod = int.TryParse(matches[17], out var kkMod) ? kkMod : 0, AtReach = matches[14], @@ -131,18 +120,15 @@ namespace DSALib.Auxiliary } } - private async Task AddRanged(int i, string talent, List matches) - { + private async Task AddRanged(int i, string talent, List matches) { var name = talent.Replace(' ', '_').Replace(".", ""); - if (!matches[1].Equals(string.Empty)) - { + if (!matches[1].Equals(string.Empty)) { var temp = new MeleeWeapon( name, matches[1], int.TryParse(matches[10], out var weight) ? weight : 0, matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(), - matches[11]) - { + matches[11]) { INI = int.TryParse(matches[3], out var ini) ? ini : 0, MW = matches[4], TpKK = matches[2] @@ -152,15 +138,13 @@ namespace DSALib.Auxiliary await Database.AddWeapon(temp); } - if (i > 18) - { + if (i > 18) { var range = new RangedWeapon( name, matches[13].Replace(' ', '+'), int.TryParse(matches[10], out var weight) ? weight : 0, matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(), - matches[11]) - { + matches[11]) { AtMod = int.TryParse(matches[18], out var atMod) ? atMod : 0, KKMod = int.TryParse(matches[17], out var kkMod) ? kkMod : 0, AtReach = matches[14], diff --git a/dsa/DSALib/Characters/Being.cs b/dsa/DSALib/Characters/Being.cs index 27879a1..147bc54 100644 --- a/dsa/DSALib/Characters/Being.cs +++ b/dsa/DSALib/Characters/Being.cs @@ -1,7 +1,5 @@ -namespace DSALib.Characters -{ - public class Being : Entity - { +namespace DSALib.Characters { + public class Being : Entity { public int Lebenspunkte_Basis { get; set; } = 30; public int Lebenspunkte_Aktuell { get; set; } = 30; diff --git a/dsa/DSALib/Characters/Critter.cs b/dsa/DSALib/Characters/Critter.cs index dcedccb..e3a39a6 100644 --- a/dsa/DSALib/Characters/Critter.cs +++ b/dsa/DSALib/Characters/Critter.cs @@ -5,14 +5,11 @@ using DiscoBot.DSA_Game.Characters; using DSALib.Models.Dsa; using Newtonsoft.Json; -namespace DSALib.Characters -{ - public class Critter : Being, ICombatant - { +namespace DSALib.Characters { + public class Critter : Being, ICombatant { public CritterAttack lastAttack; - public Critter(int gw, int gs, int rs, int mr, int ko, int pa, string ini, List critterAttacks) - { + public Critter(int gw, int gs, int rs, int mr, int ko, int pa, string ini, List critterAttacks) { Gw = gw; Gs = gs; Rs = rs; @@ -24,8 +21,7 @@ namespace DSALib.Characters lastAttack = CritterAttacks[new Random().Next(critterAttacks.Count)]; } - public Critter() - { + public Critter() { } public int Rs { get; set; } @@ -46,41 +42,33 @@ namespace DSALib.Characters public List CritterAttacks { get; set; } - public string Angriff(string talent, int erschwernis = 0) - { + public string Angriff(string talent, int erschwernis = 0) { throw new NotImplementedException(); } - public string Parade(string talent, int erschwernis = 0) - { + public string Parade(string talent, int erschwernis = 0) { throw new NotImplementedException(); } - public static Critter Load(string path) - { - try - { + public static Critter Load(string path) { + try { return JsonConvert.DeserializeObject( File.ReadAllText(path)); // Deserialize Data and create Session Object } - catch (Exception e) - { + catch (Exception e) { Console.WriteLine($"Laden von Save-File {path} fehlgeschlagen." + e); return null; } } - public void Save(string path = @"..\..\Critters\") - { - try - { + public void Save(string path = @"..\..\Critters\") { + try { File.WriteAllText(path + Name + ".json", JsonConvert.SerializeObject(this, Formatting.Indented)); // Deserialize Data and create CommandInfo Struct } - catch (Exception e) - { + catch (Exception e) { Console.WriteLine($"Speichern von Save-File {path} fehlgeschlagen." + e); } } diff --git a/dsa/DSALib/Characters/Entity.cs b/dsa/DSALib/Characters/Entity.cs index a8a5e81..cd65b27 100644 --- a/dsa/DSALib/Characters/Entity.cs +++ b/dsa/DSALib/Characters/Entity.cs @@ -1,11 +1,8 @@ -namespace DSALib.Characters -{ - public class Entity - { +namespace DSALib.Characters { + public class Entity { public string Name { get; set; } - public override string ToString() - { + public override string ToString() { return Name; } } diff --git a/dsa/DSALib/Characters/ICharacter.cs b/dsa/DSALib/Characters/ICharacter.cs index 256fecd..72a3b30 100644 --- a/dsa/DSALib/Characters/ICharacter.cs +++ b/dsa/DSALib/Characters/ICharacter.cs @@ -1,9 +1,7 @@ using DiscoBot.DSA_Game.Characters; -namespace DSALib.Characters -{ - public interface ICharacter : ICombatant - { +namespace DSALib.Characters { + public interface ICharacter : ICombatant { string TestTalent(string talent, int erschwernis = 0); string TestEigenschaft(string eigenschaft, int erschwernis = 0); diff --git a/dsa/DSALib/Characters/ICombatant.cs b/dsa/DSALib/Characters/ICombatant.cs index a4ce601..ec0b8b5 100644 --- a/dsa/DSALib/Characters/ICombatant.cs +++ b/dsa/DSALib/Characters/ICombatant.cs @@ -1,7 +1,5 @@ -namespace DiscoBot.DSA_Game.Characters -{ - public interface ICombatant - { +namespace DiscoBot.DSA_Game.Characters { + public interface ICombatant { string Name { get; set; } int Lebenspunkte_Basis { get; set; } diff --git a/dsa/DSALib/Commands/CommandHandler.cs b/dsa/DSALib/Commands/CommandHandler.cs index e63d7b8..ebe2039 100644 --- a/dsa/DSALib/Commands/CommandHandler.cs +++ b/dsa/DSALib/Commands/CommandHandler.cs @@ -1,20 +1,15 @@ using System; using DSALib.Auxiliary; using DSALib.Auxiliary.Calculator; -using DSALib.Commands; using DSALib.DSA_Game; using DSALib.Models.Network; -namespace DSALib.Commands -{ - public class CommandHandler - { - public static CommandResponse ExecuteCommand(Command cmd) - { +namespace DSALib.Commands { + public class CommandHandler { + public static CommandResponse ExecuteCommand(Command cmd) { var res = string.Empty; var type = ResponseType.Broadcast; - switch (cmd.CmdIdentifier.ToLower()) - { + switch (cmd.CmdIdentifier.ToLower()) { case "addChar": res = FileHandler.AddChar(cmd.CharId, cmd.CmdText); break; @@ -62,11 +57,9 @@ namespace DSALib.Commands return new CommandResponse($"Kommando {cmd.CmdIdentifier} nicht gefunden", ResponseType.Error); } - private static string Proben(string name, string command, string waffe, int erschwernis = 0) - { + private static string Proben(string name, string command, string waffe, int erschwernis = 0) { var res = string.Empty; - switch (command.ToLower()) - { + switch (command.ToLower()) { case "f": case "fern": case "fernkampf": @@ -107,12 +100,10 @@ namespace DSALib.Commands return res; } - private static string CheckCommand(string name, CommandTypes command, string waffe, int erschwernis = 0) - { + private static string CheckCommand(string name, CommandTypes command, string waffe, int erschwernis = 0) { var chr = Dsa.GetCharacter(0); - switch (command) - { + switch (command) { case CommandTypes.Talent: return chr.TestTalent(waffe, erschwernis); case CommandTypes.Eigenschaft: diff --git a/dsa/DSALib/Commands/CommandTypes.cs b/dsa/DSALib/Commands/CommandTypes.cs index 62b8b0f..ac69bfc 100644 --- a/dsa/DSALib/Commands/CommandTypes.cs +++ b/dsa/DSALib/Commands/CommandTypes.cs @@ -1,7 +1,5 @@ -namespace DSALib.Commands -{ - public enum CommandTypes - { +namespace DSALib.Commands { + public enum CommandTypes { Talent, Eigenschaft, Angriff, diff --git a/dsa/DSALib/Commands/FileHandler.cs b/dsa/DSALib/Commands/FileHandler.cs index d117040..bd38fa9 100644 --- a/dsa/DSALib/Commands/FileHandler.cs +++ b/dsa/DSALib/Commands/FileHandler.cs @@ -3,22 +3,17 @@ using System.Linq; using System.Net; using DSALib.DSA_Game; using DSALib.DSA_Game.Characters; -using DSALib; using DSALib.Models.Dsa; -namespace DSALib.Commands -{ - public class FileHandler - { - public static string AddChar(ulong id, string url) - { +namespace DSALib.Commands { + public class FileHandler { + public static string AddChar(ulong id, string url) { if (url == string.Empty) throw new ArgumentException("Es wurde keine Datei angehängt"); if (!url.EndsWith(".xml")) throw new ArgumentException("Es wurde kein xml Held mitgeschickt"); - using (var client = new WebClient()) - { + using (var client = new WebClient()) { client.DownloadFile(url, "helden\\" + url.Split("/").Last()); } diff --git a/dsa/DSALib/Commands/Gm.cs b/dsa/DSALib/Commands/Gm.cs index 74fd673..e4b37a5 100644 --- a/dsa/DSALib/Commands/Gm.cs +++ b/dsa/DSALib/Commands/Gm.cs @@ -1,5 +1,4 @@ -namespace DSALib.Commands -{ +namespace DSALib.Commands { /*public class Iam { diff --git a/dsa/DSALib/Commands/HeldList.cs b/dsa/DSALib/Commands/HeldList.cs index ef29a14..6943f21 100644 --- a/dsa/DSALib/Commands/HeldList.cs +++ b/dsa/DSALib/Commands/HeldList.cs @@ -5,12 +5,9 @@ using DSALib.Auxiliary; using DSALib.DSA_Game; using DSALib.DSA_Game.Characters; -namespace DSALib.Commands -{ - public class HeldList - { - public static string ListAsync(ulong id, params string[] prop_list) - { +namespace DSALib.Commands { + public class HeldList { + public static string ListAsync(ulong id, params string[] prop_list) { var res = new List(); var character = Dsa.GetCharacter(id) as Character; @@ -19,8 +16,7 @@ namespace DSALib.Commands if (prop_list.Length == 0 || prop_list[0].ToLower().StartsWith("all") || - prop_list[0].ToLower().StartsWith("brief") || prop_list[0].ToLower().StartsWith("zettel")) - { + prop_list[0].ToLower().StartsWith("brief") || prop_list[0].ToLower().StartsWith("zettel")) { res.Add(character.Name + ":\n"); //Eigenschaften res.AddRange( @@ -64,18 +60,14 @@ namespace DSALib.Commands " " + s.Probe)); } else if (prop_list[0].ToLower().StartsWith("man") || prop_list[0].ToLower().StartsWith("help") || - prop_list[0].ToLower().StartsWith("hilf")) - { + prop_list[0].ToLower().StartsWith("hilf")) { return "```xl\n" + Help.Get_Specific_Help("Held") + "\n```"; } - else - { + else { res.Add(character.Name + ":\n"); - foreach (var prop in prop_list) - { - switch (prop.ToLower()) - { + foreach (var prop in prop_list) { + switch (prop.ToLower()) { case "e": case "eig": case "eigenschaft": diff --git a/dsa/DSALib/Commands/Help.cs b/dsa/DSALib/Commands/Help.cs index 4506821..b81a9ba 100644 --- a/dsa/DSALib/Commands/Help.cs +++ b/dsa/DSALib/Commands/Help.cs @@ -2,26 +2,21 @@ using DSALib.Auxiliary; using DSALib.DSA_Game.Save; -namespace DSALib.Commands -{ - public class Help - { +namespace DSALib.Commands { + public class Help { //public static List Commands { get; } = new List(); - public static string Get_Specific_Help(string command) - { + public static string Get_Specific_Help(string command) { // return command specific help var com = Properties.CommandInfos .OrderBy(x => SpellCorrect.Compare(x.Name, command.ToLower())).Last(); // get best fit command return com.GetDescription(); } - public static string Get_Generic_Help() - { + public static string Get_Generic_Help() { var res = ""; - foreach (var com in Properties.CommandInfos) - { + foreach (var com in Properties.CommandInfos) { var first_column_width = 8; res += ("!" + com.Name + ": ").AddSpaces(first_column_width) + com.Brief; @@ -35,8 +30,7 @@ namespace DSALib.Commands return res; } - public static string ShowHelp(params string[] commandList) - { + public static string ShowHelp(params string[] commandList) { var command = ""; if (commandList.Length > 0) command = commandList.Aggregate((s, c) => s + " " + c); diff --git a/dsa/DSALib/Commands/LebenUndAstral.cs b/dsa/DSALib/Commands/LebenUndAstral.cs index ac11c91..20f05cb 100644 --- a/dsa/DSALib/Commands/LebenUndAstral.cs +++ b/dsa/DSALib/Commands/LebenUndAstral.cs @@ -1,14 +1,11 @@ using System; using DSALib.Auxiliary; -using DSALib.DSA_Game; using DSALib.Characters; +using DSALib.DSA_Game; -namespace DSALib.Commands -{ - public class LE - { - public static string LEAsync(ulong id, string modifier) - { +namespace DSALib.Commands { + public class LE { + public static string LEAsync(ulong id, string modifier) { //This is the string that will be printed var res = ""; @@ -21,10 +18,8 @@ namespace DSALib.Commands } } - public class AE - { - public static string AEAsync(ulong id, string modifier) - { + public class AE { + public static string AEAsync(ulong id, string modifier) { //This is the string that will be printed var res = ""; @@ -36,10 +31,8 @@ namespace DSALib.Commands } } - public static class StatExtension - { - public static string get_LE_Text(this ICharacter c, string prop) - { + public static class StatExtension { + public static string get_LE_Text(this ICharacter c, string prop) { var res = ""; var comp = new SpellCorrect(); var character = c; @@ -47,27 +40,22 @@ namespace DSALib.Commands res += character.Name + ":\n"; //If there is actual input we process it - if (prop.Length > 0) - { + if (prop.Length > 0) { res += "LE: "; res += character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis + " -> "; // Apply a change to current value - if (prop.StartsWith("+") || prop.StartsWith("-")) - { + if (prop.StartsWith("+") || prop.StartsWith("-")) { //Allow overflowing the max - if (prop.StartsWith("++")) - { + if (prop.StartsWith("++")) { character.Lebenspunkte_Aktuell = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop.Substring(1, prop.Length - 1)); } - else - { + else { var temp = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop) - character.Lebenspunkte_Basis; //Stop from overflow overflow - if (temp > 0 && prop.StartsWith("+")) - { + if (temp > 0 && prop.StartsWith("+")) { character.Lebenspunkte_Aktuell = character.Lebenspunkte_Basis > character.Lebenspunkte_Aktuell ? character.Lebenspunkte_Basis @@ -75,16 +63,14 @@ namespace DSALib.Commands res += " Maximale Lebenspunkte sind erreicht "; } //Simply apply change - else - { + else { character.Lebenspunkte_Aktuell = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop); } } res += character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis; } - else - { + else { // Set to new value regardless of original character.Lebenspunkte_Aktuell = Convert.ToInt32(prop); @@ -92,16 +78,14 @@ namespace DSALib.Commands } } //If no value is passed, the curent value is displayed - else - { + else { res += "LE: " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis; } return res; } - public static string get_AE_Text(this ICharacter c, string prop) - { + public static string get_AE_Text(this ICharacter c, string prop) { var res = ""; var comp = new SpellCorrect(); var character = c; @@ -109,27 +93,22 @@ namespace DSALib.Commands res += character.Name + ":\n"; //If there is actual input we process it - if (prop.Length > 0) - { + if (prop.Length > 0) { res += "AE: "; res += character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis + " -> "; // Apply a change to current value - if (prop.StartsWith("+") || prop.StartsWith("-")) - { + if (prop.StartsWith("+") || prop.StartsWith("-")) { //Allow overflowing the max - if (prop.StartsWith("++")) - { + if (prop.StartsWith("++")) { character.Astralpunkte_Aktuell = character.Astralpunkte_Aktuell + Convert.ToInt32(prop.Substring(1, prop.Length - 1)); } - else - { + else { var temp = character.Astralpunkte_Aktuell + Convert.ToInt32(prop) - character.Astralpunkte_Basis; //Stop from overflow overflow - if (temp > 0 && prop.StartsWith("+")) - { + if (temp > 0 && prop.StartsWith("+")) { character.Astralpunkte_Aktuell = character.Astralpunkte_Basis > character.Astralpunkte_Aktuell ? character.Astralpunkte_Basis @@ -137,14 +116,12 @@ namespace DSALib.Commands res += " Maximale Astralpunkte sind erreicht "; } //Simply apply change - else - { + else { character.Astralpunkte_Aktuell = character.Astralpunkte_Aktuell + Convert.ToInt32(prop); } } - if (character.Astralpunkte_Aktuell < 0) - { + if (character.Astralpunkte_Aktuell < 0) { res += "Nicht genügend Astralpunkte! "; character.Astralpunkte_Aktuell = 0; } @@ -152,16 +129,14 @@ namespace DSALib.Commands res += character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis; } //Set to new value regardless of original - else - { + else { character.Astralpunkte_Aktuell = Convert.ToInt32(prop); res += character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis; } } //If no value is passed, the curent value is displayed - else - { + else { res += "AE: " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis; } diff --git a/dsa/DSALib/Commands/List.cs b/dsa/DSALib/Commands/List.cs index 1213f85..8106c89 100644 --- a/dsa/DSALib/Commands/List.cs +++ b/dsa/DSALib/Commands/List.cs @@ -1,20 +1,15 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Linq; using DSALib.DSA_Game; -namespace DSALib.Commands -{ - public class List - { - public static string ListAsync(string prop) - { +namespace DSALib.Commands { + public class List { + public static string ListAsync(string prop) { var res = new List(); //int persist = 0; - switch (prop.ToLower()) - { + switch (prop.ToLower()) { case "man": case "help": return Help.Get_Specific_Help("List"); diff --git a/dsa/DSALib/Commands/MiscCommands.cs b/dsa/DSALib/Commands/MiscCommands.cs index 69b2ffe..e5afd3d 100644 --- a/dsa/DSALib/Commands/MiscCommands.cs +++ b/dsa/DSALib/Commands/MiscCommands.cs @@ -1,7 +1,5 @@ -namespace DSALib.Commands -{ - public class MiscCommands - { +namespace DSALib.Commands { + public class MiscCommands { /*[Command("r"), Summary("Würfelt ")] [Alias("R", "Roll", "roll", "Würfle")] public Task RollAsync([Remainder, Summary("Weapon")] string roll) diff --git a/dsa/DSALib/Commands/NpcCommands.cs b/dsa/DSALib/Commands/NpcCommands.cs index 510b78b..5e20d65 100644 --- a/dsa/DSALib/Commands/NpcCommands.cs +++ b/dsa/DSALib/Commands/NpcCommands.cs @@ -1,30 +1,23 @@ using System; using System.Collections.Generic; using System.Linq; -using DSALib.Characters; using DSALib.DSA_Game; -using DSALib.DSA_Game.Characters; -namespace DSALib.Commands -{ - public class NpcCommands - { - public static string CreateNpc(ulong id, IEnumerable props, int modifier) - { +namespace DSALib.Commands { + public class NpcCommands { + public static string CreateNpc(ulong id, IEnumerable props, int modifier) { if (int.TryParse(props.Last(), out var mean)) return Random(id, props.First(), mean, modifier); return Copy(id, props.First(), props.Last(), modifier); } - private static string Random(ulong id, string npcName, int mean = 9, int stDv = 1) - { + private static string Random(ulong id, string npcName, int mean = 9, int stDv = 1) { throw new NotImplementedException(); //Dsa.Chars.Add(new Npc(npcName, mean, stDv)); //return $"{npcName} wurde zufällig generiert"; } - private static string Copy(ulong id, string npcName, string source, int stDv = 1) - { + private static string Copy(ulong id, string npcName, string source, int stDv = 1) { if (Dsa.Chars.Exists(x => x.Name.Equals(npcName))) throw new Exception("Char gibt es schon"); throw new NotImplementedException(); //var chr = Dsa.GetCharacter(id); diff --git a/dsa/DSALib/Commands/ProbenTest.cs b/dsa/DSALib/Commands/ProbenTest.cs index 7c88480..6896e15 100644 --- a/dsa/DSALib/Commands/ProbenTest.cs +++ b/dsa/DSALib/Commands/ProbenTest.cs @@ -1,7 +1,5 @@ -namespace DSALib.Commands -{ - public class ProbenTest - { +namespace DSALib.Commands { + public class ProbenTest { /*[Command("t"), Summary("Würfelt ein Talent-/Zauberprobe")] [Alias("T", "Talent", "talent", "versuche")] public Task TalentAsync([Summary("Talent oder Zaubername")] string talent, int erschwernis = 0) diff --git a/dsa/DSALib/DSA_Game/Characters/Character.cs b/dsa/DSALib/DSA_Game/Characters/Character.cs index aea5671..3e4022e 100644 --- a/dsa/DSALib/DSA_Game/Characters/Character.cs +++ b/dsa/DSALib/DSA_Game/Characters/Character.cs @@ -9,12 +9,9 @@ using DSALib.Auxiliary; using DSALib.Characters; using DSALib.Models.Dsa; -namespace DSALib.DSA_Game.Characters -{ - public class Character : Being, ICharacter - { - public Character() - { +namespace DSALib.DSA_Game.Characters { + public class Character : Being, ICharacter { + public Character() { PropTable.Add("MU", "Mut"); // routing PropTable.Add("KL", "Klugheit"); PropTable.Add("IN", "Intuition"); @@ -25,20 +22,17 @@ namespace DSALib.DSA_Game.Characters PropTable.Add("KK", "Körperkraft"); } - public Character(string path) : this() - { + public Character(string path) : this() { Load(new MemoryStream(File.ReadAllBytes(path))); // load Post_process(); // calculate derived values } - public Character(MemoryStream stream) : this() - { + public Character(MemoryStream stream) : this() { Load(stream); // load Post_process(); // calculate derived values } - public Character(Character c, string name, int stDv = 2) : this() - { + public Character(Character c, string name, int stDv = 2) : this() { Name = name; foreach (var i in c.Eigenschaften) Eigenschaften.Add(i.Key, i.Value + (int) Math.Round(RandomMisc.Random(stDv))); @@ -82,8 +76,7 @@ namespace DSALib.DSA_Game.Characters return Zauber.ProbenTest(this, zauber, erschwernis); } - public string TestEigenschaft(string eigenschaft, int erschwernis = 0) - { + public string TestEigenschaft(string eigenschaft, int erschwernis = 0) { var output = new StringBuilder(); var prop = PropTable[eigenschaft.ToUpper()]; var tap = Eigenschaften[prop]; @@ -115,11 +108,10 @@ namespace DSALib.DSA_Game.Characters return output.ToString(); } - public string Parade(string talent, int erschwernis = 0) - { + public string Parade(string talent, int erschwernis = 0) { var output = new StringBuilder(); - if (Kampftalente.TryMatch(out var iAttack , talent)) + if (Kampftalente.TryMatch(out var iAttack, talent)) return $"{Name} kann nicht mit der Waffenart {talent} umgehen..."; @@ -136,11 +128,10 @@ namespace DSALib.DSA_Game.Characters return output.ToString(); } - public string Fernkampf(string talent, int erschwernis = 0) - { + public string Fernkampf(string talent, int erschwernis = 0) { var output = new StringBuilder(); var fk = Eigenschaften["fk"]; - if (! Talente.TryMatch(out var iAttack, talent)) + if (!Talente.TryMatch(out var iAttack, talent)) return $"{Name} kann nicht mit der Waffenart {talent} umgehen..."; var attack = (Talent) iAttack; @@ -157,8 +148,7 @@ namespace DSALib.DSA_Game.Characters return output.ToString(); } - private void Post_process() - { + private void Post_process() { var LE_Wert = Eigenschaften["Lebensenergie"]; var AE_Wert = Eigenschaften.First(s => s.Key.Contains("Astralenergie")).Value; @@ -184,16 +174,13 @@ namespace DSALib.DSA_Game.Characters } - private void Load(MemoryStream stream) - { + private void Load(MemoryStream stream) { var reader = new XmlTextReader(stream); - while (reader.Read()) - { + while (reader.Read()) { // read until he hits keywords if (reader.NodeType != XmlNodeType.Element) continue; - switch (reader.Name) - { + switch (reader.Name) { case "Wesen": reader.Skip(); break; @@ -208,17 +195,14 @@ namespace DSALib.DSA_Game.Characters break; case "vt": reader.Read(); - while (reader.Name.Equals("vorteil")) - { - try - { + while (reader.Name.Equals("vorteil")) { + try { Vorteile.Add(new Vorteil( reader.GetAttribute("name"), // Convert.ToInt32(reader.GetAttribute("value")))); reader.GetAttribute("value"))); } - catch - { + catch { Vorteile.Add(new Vorteil(reader.GetAttribute("name"))); } @@ -228,8 +212,7 @@ namespace DSALib.DSA_Game.Characters break; case "talentliste": reader.Read(); - while (reader.Name.Equals("talent")) - { + while (reader.Name.Equals("talent")) { Talente.Add( new Talent( reader.GetAttribute("name"), @@ -241,8 +224,7 @@ namespace DSALib.DSA_Game.Characters break; case "zauberliste": reader.Read(); - while (reader.Name.Equals("zauber")) - { + while (reader.Name.Equals("zauber")) { Zauber.Add( new Zauber( reader.GetAttribute("name"), diff --git a/dsa/DSALib/DSA_Game/Characters/NPC.cs b/dsa/DSALib/DSA_Game/Characters/NPC.cs index 105adda..6bcde0c 100644 --- a/dsa/DSALib/DSA_Game/Characters/NPC.cs +++ b/dsa/DSALib/DSA_Game/Characters/NPC.cs @@ -1,24 +1,18 @@ using System; using DSALib.Auxiliary; -using DSALib.Characters; -namespace DSALib.Characters -{ - public class Npc : Being, ICharacter - { +namespace DSALib.Characters { + public class Npc : Being, ICharacter { private readonly int mean, stDv; - public Npc(string name, int mean, int stDv) - { + public Npc(string name, int mean, int stDv) { this.mean = mean; this.stDv = stDv; Name = name; } - public string TestTalent(string talent, int tap = 3) - { - for (var i = 0; i <= 2; i++) - { + public string TestTalent(string talent, int tap = 3) { + for (var i = 0; i <= 2; i++) { // foreach property, dice and tap var temp = Dice.Roll(); var eigenschaft = (int) Math.Round(RandomMisc.Random(stDv, mean)); @@ -32,8 +26,7 @@ namespace DSALib.Characters return $"{Name} scheitert an {talent}"; } - public string TestEigenschaft(string eigenschaft, int erschwernis = 0) - { + public string TestEigenschaft(string eigenschaft, int erschwernis = 0) { var temp = Dice.Roll(); var prop = (int) Math.Round(RandomMisc.Random(stDv, stDv)); @@ -42,8 +35,7 @@ namespace DSALib.Characters return $"{Name} scheitert an {eigenschaft}"; } - public string Angriff(string waffe, int erschwernis = 0) - { + public string Angriff(string waffe, int erschwernis = 0) { var temp = Dice.Roll(); if (temp == 1) return $"{Name} greift kritisch mit {waffe} an"; @@ -53,8 +45,7 @@ namespace DSALib.Characters return $"{Name} haut mit {waffe} daneben"; } - public string Parade(string waffe, int erschwernis = 0) - { + public string Parade(string waffe, int erschwernis = 0) { var temp = Dice.Roll(); if (temp == 1) return $"{Name} pariert mit {waffe} meisterlich"; @@ -64,8 +55,7 @@ namespace DSALib.Characters return $"{Name} schafft es nicht mit {waffe} zu parieren"; } - public string Fernkampf(string waffe, int erschwernis = 0) - { + public string Fernkampf(string waffe, int erschwernis = 0) { var temp = Dice.Roll(); if (temp == 1) return $"{Name} trifft kritisch mit {waffe}"; @@ -75,8 +65,7 @@ namespace DSALib.Characters return $"{Name} schießt mit {waffe} daneben"; } - public string TestZauber(string zauber, int erschwernis) - { + public string TestZauber(string zauber, int erschwernis) { return TestTalent(zauber, erschwernis); } } diff --git a/dsa/DSALib/DSA_Game/Characters/SaveChar.cs b/dsa/DSALib/DSA_Game/Characters/SaveChar.cs index 00e2f86..b3c4fcd 100644 --- a/dsa/DSALib/DSA_Game/Characters/SaveChar.cs +++ b/dsa/DSALib/DSA_Game/Characters/SaveChar.cs @@ -1,9 +1,7 @@ using DSALib.Characters; -namespace DSALib.DSA_Game.Characters -{ - public class SaveChar - { +namespace DSALib.DSA_Game.Characters { + public class SaveChar { public string Name { get; set; } public int Lebenspunkte_Aktuell { get; set; } @@ -12,10 +10,8 @@ namespace DSALib.DSA_Game.Characters public int Astralpunkte_Aktuell { get; set; } - public static SaveChar FromICharacter(ICharacter c) - { - return new SaveChar - { + public static SaveChar FromICharacter(ICharacter c) { + return new SaveChar { Astralpunkte_Aktuell = c.Astralpunkte_Aktuell, Ausdauer_Aktuell = c.Ausdauer_Aktuell, Lebenspunkte_Aktuell = c.Lebenspunkte_Aktuell, @@ -25,10 +21,8 @@ namespace DSALib.DSA_Game.Characters } - public static class ICharExtension - { - public static void Update(this ICharacter c, SaveChar s) - { + public static class ICharExtension { + public static void Update(this ICharacter c, SaveChar s) { c.Astralpunkte_Aktuell = s.Astralpunkte_Aktuell; c.Ausdauer_Aktuell = s.Ausdauer_Aktuell; c.Lebenspunkte_Aktuell = s.Lebenspunkte_Aktuell; diff --git a/dsa/DSALib/DSA_Game/Dsa.cs b/dsa/DSALib/DSA_Game/Dsa.cs index bcd8951..42be212 100644 --- a/dsa/DSALib/DSA_Game/Dsa.cs +++ b/dsa/DSALib/DSA_Game/Dsa.cs @@ -1,16 +1,13 @@ using System; using System.Collections.Generic; using System.Linq; +using DSALib.Characters; using DSALib.DSA_Game.Characters; using DSALib.DSA_Game.Save; -using DSALib; -using DSALib.Characters; using DSALib.Models.Dsa; -namespace DSALib.DSA_Game -{ - public static class Dsa - { +namespace DSALib.DSA_Game { + public static class Dsa { #if DEBUG public const string rootPath = ""; //"C:\\Users\\Dennis\\Source\\Repos\\DiscoBot\\DSALib\\";//"DiscoBot\\DSALib\\"; @@ -25,23 +22,19 @@ namespace DSALib.DSA_Game public static List Zauber { get; set; } = new List(); - public static Session Session - { - get - { + public static Session Session { + get { s_session.Chars = Chars.Select(x => SaveChar.FromICharacter(x)).ToList(); return s_session; } - set - { + set { s_session = value; foreach (var x in value.Chars) Chars.Find(c => c.Name.Equals(x.Name)).Update(x); } } - public static void Startup() - { + public static void Startup() { //new .Auxiliary.Calculator.StringSolver("1d100 - (1d200 + 1) * -50000").Solve(); /*Session = new Session();*/ // relation.Add("Papo", "Pump aus der Gosse"); @@ -75,20 +68,17 @@ namespace DSALib.DSA_Game //new WeaponImporter().DownloadWeapons().Wait(); - Session = new Session - { + Session = new Session { Chars = Chars.Select(SaveChar.FromICharacter).ToList() }; //Session.Save(); } - public static ICharacter GetCharacter(ulong id) - { + public static ICharacter GetCharacter(ulong id) { throw new NotImplementedException(); } - public static ICharacter GetCharacter(string name, ulong groupId) - { + public static ICharacter GetCharacter(string name, ulong groupId) { throw new NotImplementedException(); } } diff --git a/dsa/DSALib/DSA_Game/Save/Properties.cs b/dsa/DSALib/DSA_Game/Save/Properties.cs index 2312af0..06628ed 100644 --- a/dsa/DSALib/DSA_Game/Save/Properties.cs +++ b/dsa/DSALib/DSA_Game/Save/Properties.cs @@ -6,33 +6,27 @@ using System.Linq; using DSALib.Auxiliary; using Newtonsoft.Json; -namespace DSALib.DSA_Game.Save -{ - public static class Properties - { +namespace DSALib.DSA_Game.Save { + public static class Properties { public static Dictionary objects; - static Properties() - { + static Properties() { objects = new Dictionary(); /*this.objects.Add("Sounds", new List()); this.objects.Add("CommandInfos", new List());*/ } - public static List CommandInfos - { + public static List CommandInfos { get => objects["CommandInfo"] as List; set => objects["CommandInfo"] = value; } // use Properties.Commandinfos to access the abstract Object array - public static void Deserialize(string path = @"Properties") - { + public static void Deserialize(string path = @"Properties") { var files = Directory.GetFiles(path, "*.json"); foreach (var file in files) - try - { + try { var name = file.Split('\\').Last().Split('.')[0].Replace('-', '.'); var data = File.ReadAllText(file); var type = Type.GetType(name); @@ -41,19 +35,15 @@ namespace DSALib.DSA_Game.Save var o = JsonConvert.DeserializeObject(data, type); objects.Add(name.Split('.').Last(), o); } - catch (Exception e) - { + catch (Exception e) { // ignored Console.WriteLine($"Laden von Save-File {file} fehlgeschlagen." + e); } } - public static void Serialize(string path = @"..\..\Properties\") - { - try - { - foreach (var o in objects) - { + public static void Serialize(string path = @"..\..\Properties\") { + try { + foreach (var o in objects) { var assembly = o.Value is IList list ? list[0]?.GetType().FullName : o.Value.GetType().FullName; @@ -64,8 +54,7 @@ namespace DSALib.DSA_Game.Save Formatting.Indented)); // Deserialize Data and create CommandInfo Struct } } - catch (Exception e) - { + catch (Exception e) { // ignored Console.WriteLine("Speichern von Save-File fehlgeschlagen." + e); } diff --git a/dsa/DSALib/DSA_Game/Save/SaveCommand.cs b/dsa/DSALib/DSA_Game/Save/SaveCommand.cs index c5a1bb4..0153779 100644 --- a/dsa/DSALib/DSA_Game/Save/SaveCommand.cs +++ b/dsa/DSALib/DSA_Game/Save/SaveCommand.cs @@ -2,14 +2,10 @@ using System.IO; using System.Linq; -namespace DSALib.DSA_Game.Save -{ - public class SaveCommand - { - public void LoadSession(string name = "") - { - if (name.Equals("?") || name.Equals(string.Empty)) - { +namespace DSALib.DSA_Game.Save { + public class SaveCommand { + public void LoadSession(string name = "") { + if (name.Equals("?") || name.Equals(string.Empty)) { Console.WriteLine("Gespeicherte Sessions:"); Console.WriteLine(ListSessions()); return; @@ -24,27 +20,23 @@ namespace DSALib.DSA_Game.Save Console.WriteLine($"{name} wurde geladen"); } - public void SessionSave(string name = "") - { + public void SessionSave(string name = "") { //var sendFile = this.Context.Channel.SendWebFile("https://cdn.discordapp.com/attachments/377123019673567232/465615882048110603/giphy.gif"); - if (name.Equals("?") || name.Equals(string.Empty)) - { + if (name.Equals("?") || name.Equals(string.Empty)) { Console.WriteLine("Gespeicherte Sessions:"); Console.WriteLine(ListSessions()); return; } var path = Session.DirectoryPath + @"\" + name; - if (Directory.Exists(path)) - { + if (Directory.Exists(path)) { var files = Directory.GetFiles(path); var current = files.Max(x => Convert.ToInt32(x.Split('-').Last().Split('.').First())); Dsa.Session.SessionName = name; Dsa.Session.Save(path + "\\" + name + $"-{++current}.json"); } - else - { + else { Directory.CreateDirectory(path); Dsa.Session.SessionName = name; Dsa.Session.Save(path + "\\" + name + "-0.json"); @@ -54,8 +46,7 @@ namespace DSALib.DSA_Game.Save //await sendFile; } - private string[] ListSessions() - { + private string[] ListSessions() { var dirs = Directory.GetDirectories(Session.DirectoryPath) .OrderByDescending(x => new DirectoryInfo(x).LastAccessTime.Ticks).ToArray(); for (var i = 0; i < dirs.Length; i++) dirs[i] += "; " + new DirectoryInfo(dirs[i]).LastAccessTime; diff --git a/dsa/DSALib/DSA_Game/Save/Session.cs b/dsa/DSALib/DSA_Game/Save/Session.cs index 62aa8f6..bd36bf8 100644 --- a/dsa/DSALib/DSA_Game/Save/Session.cs +++ b/dsa/DSALib/DSA_Game/Save/Session.cs @@ -4,10 +4,8 @@ using System.IO; using DSALib.DSA_Game.Characters; using Newtonsoft.Json; -namespace DSALib.DSA_Game.Save -{ - public class Session - { +namespace DSALib.DSA_Game.Save { + public class Session { public static string DirectoryPath { get; set; } = Dsa.rootPath + @"sessions"; public Dictionary Relation { get; set; } = @@ -17,32 +15,26 @@ namespace DSALib.DSA_Game.Save public string SessionName { get; set; } - public static Session Load(string path) - { - try - { + public static Session Load(string path) { + try { return JsonConvert.DeserializeObject( File.ReadAllText(path)); // Deserialize Data and create Session Object } - catch (Exception e) - { + catch (Exception e) { // ignored Console.WriteLine($"Laden von Save-File {path} fehlgeschlagen." + e); return null; } } - public void Save(string path) - { - try - { + public void Save(string path) { + try { File.WriteAllText(path, JsonConvert.SerializeObject(this, Formatting.Indented)); // Deserialize Data and create CommandInfo Struct } - catch (Exception e) - { + catch (Exception e) { Console.WriteLine($"Speichern von Save-File {path} fehlgeschlagen.\n" + e); // ignored } diff --git a/dsa/DSALib/FireBase/Database.cs b/dsa/DSALib/FireBase/Database.cs index 1edd699..585b6d0 100644 --- a/dsa/DSALib/FireBase/Database.cs +++ b/dsa/DSALib/FireBase/Database.cs @@ -2,56 +2,51 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text.RegularExpressions; using System.Threading.Tasks; using DSALib.DSA_Game; using DSALib.DSA_Game.Characters; using DSALib.Models.Database.Dsa; +using DSALib.Models.Database.Groups; using Firebase.Database; using Firebase.Database.Query; -namespace DSALib.FireBase -{ - public static class Database - { - public static FirebaseClient Firebase; +namespace DSALib.FireBase { + public static class Database { + private static readonly FirebaseClient Firebase; - public static Dictionary Chars = new Dictionary(); + private static readonly Dictionary Chars = new Dictionary(); - public static Dictionary MeleeList = new Dictionary(); + private static readonly Dictionary MeleeList = new Dictionary(); - public static Dictionary RangedWeapons = new Dictionary(); + private static readonly Dictionary RangedWeapons = new Dictionary(); - public static Dictionary Talents = new Dictionary(); + private static readonly Dictionary Talents = new Dictionary(); - public static Dictionary Spells = new Dictionary(); + private static readonly Dictionary Spells = new Dictionary(); - static Database() - { + static Database() { var auth = File.ReadAllText(Dsa.rootPath + "Token"); // your app secret Firebase = new FirebaseClient( "https://heldenonline-4d828.firebaseio.com/", - new FirebaseOptions - { + new FirebaseOptions { AuthTokenAsyncFactory = () => Task.FromResult(auth) }); - Task.Run(Initialize); + Task.Run((Action) Initialize); } - private static void Initialize() { + private static void Initialize() { var waiting = new[] { // ToDo IntializeCollection("Chars", Chars), IntializeCollection("MeleeWeapons", MeleeList), IntializeCollection("RangedWeapons", RangedWeapons), IntializeCollection("Talents", Talents), - IntializeCollection("Spells", Spells), + IntializeCollection("Spells", Spells) }; Task.WaitAll(waiting); } - private static async Task IntializeCollection(string path, Dictionary list) - { + private static async Task IntializeCollection(string path, Dictionary list) { var temp = await Firebase .Child(path) .OrderByKey() @@ -60,8 +55,7 @@ namespace DSALib.FireBase foreach (var firebaseObject in temp) list.Add(firebaseObject.Key, firebaseObject.Object); } - public static async Task AddChar(Character file, string group) - { + public static async Task AddChar(Character file, string group) { DatabaseChar.LoadChar(file, out var groupChar, out var data); var lastChar = await Firebase @@ -91,8 +85,7 @@ namespace DSALib.FireBase return id + 1; } - public static async Task RemoveChar(int id) - { + public static async Task RemoveChar(int id) { await Firebase .Child("Groups") .Child("Char" + id) @@ -111,8 +104,7 @@ namespace DSALib.FireBase .DeleteAsync(); } - public static DatabaseChar GetChar(int id) - { + public static DatabaseChar GetChar(int id) { /*var chr = await firebase .Child("Chars") .Child("Char" + id) @@ -121,8 +113,7 @@ namespace DSALib.FireBase return Chars["Char" + id]; } - public static async Task GetInventory(int id) - { + public static async Task GetInventory(int id) { var inv = await Firebase .Child("Inventories") .Child("Inventory" + id) @@ -130,32 +121,28 @@ namespace DSALib.FireBase return inv; } - public static async Task SetInventory(int id, Inventory inv) - { + public static async Task SetInventory(int id, Inventory inv) { await Firebase .Child("Inventories") .Child("Inventory" + id) .PutAsync(inv); } - public static async Task AddTalent(DSALib.Models.Database.Dsa.Talent tal) - { + public static async Task AddTalent(Talent tal) { await Firebase .Child("Talents") .Child(tal.Name) .PutAsync(tal); } - public static async Task RemoveTalent(string talent) - { + public static async Task RemoveTalent(string talent) { await Firebase .Child("Talents") .Child(talent) .DeleteAsync(); } - public static DSALib.Models.Database.Dsa.Talent GetTalent(string talent) - { + public static Talent GetTalent(string talent) { /* return await firebase .Child("Talents") @@ -164,30 +151,26 @@ namespace DSALib.FireBase return Talents[talent]; } - public static async Task AddSpell(GeneralSpell tal) - { + public static async Task AddSpell(GeneralSpell tal) { await Firebase .Child("Spells") .Child(tal.Name) .PutAsync(tal); } - public static async Task RemoveSpell(string spell) - { + public static async Task RemoveSpell(string spell) { await Firebase .Child("Spells") .Child(spell) .DeleteAsync(); } - public static GeneralSpell GetSpell(string spell) - { + public static GeneralSpell GetSpell(string spell) { return Spells[spell]; } - public static async Task AddWeapon(Weapon wep) - { + public static async Task AddWeapon(Weapon wep) { var collection = wep.GetType() == typeof(MeleeWeapon) ? "MeleeWeapons" : "RangedWeapons"; await Firebase .Child(collection) @@ -195,8 +178,7 @@ namespace DSALib.FireBase .PutAsync(wep); } - public static async Task RemoveWeapon(string weapon, bool ranged = false) - { + public static async Task RemoveWeapon(string weapon, bool ranged = false) { var collection = ranged ? "RangedWeapons" : "MeleeWeapons"; await Firebase .Child(collection) @@ -204,8 +186,7 @@ namespace DSALib.FireBase .DeleteAsync(); } - public static async Task GetWeapon(string weapon, bool ranged = false) - { + public static async Task GetWeapon(string weapon, bool ranged = false) { var collection = ranged ? "RangedWeapons" : "MeleeWeapons"; return await Firebase .Child(collection) @@ -213,12 +194,11 @@ namespace DSALib.FireBase .OnceSingleAsync(); } - public static async Task>> GetGroups() - { + public static async Task>> GetGroups() { var groups = await Firebase .Child("Groups") .OrderByKey() - .OnceAsync(); + .OnceAsync(); var ret = new List>(); foreach (var firebaseObject in groups) @@ -227,22 +207,20 @@ namespace DSALib.FireBase return ret; } - public static async Task GetGroup(int id) - { + public static async Task GetGroup(int id) { var group = await Firebase .Child("Groups") .Child("Group" + id) - .OnceSingleAsync(); + .OnceSingleAsync(); return group; } - public static async Task AddGroup(DSALib.Models.Database.Groups.Group group) - { + public static async Task AddGroup(Group group) { var lastChar = await Firebase .Child("Groups") .OrderByKey() .LimitToLast(1) - .OnceAsync(); + .OnceAsync(); var id = group.Id = lastChar.First().Object.Id + 1; await Firebase @@ -251,16 +229,14 @@ namespace DSALib.FireBase .PutAsync(group); } - public static async void SetGroup(DSALib.Models.Database.Groups.Group group) - { + public static async void SetGroup(Group group) { await Firebase .Child("Groups") .Child("Group" + group.Id) .PutAsync(group); } - public static async void DeleteGroup(int id) - { + public static async void DeleteGroup(int id) { await Firebase .Child("Groups") .Child("Group" + id) diff --git a/dsa/DSALib/Models/Database/DataObject.cs b/dsa/DSALib/Models/Database/DataObject.cs index 59cfdf2..ca6d6b2 100644 --- a/dsa/DSALib/Models/Database/DataObject.cs +++ b/dsa/DSALib/Models/Database/DataObject.cs @@ -1,13 +1,9 @@ -namespace DSALib.Models.Database -{ - public class DataObject : IDataObject - { +namespace DSALib.Models.Database { + public class DataObject : IDataObject { + public string Name { get; set; } - public override string ToString() - { + public override string ToString() { return Name; } - - public string Name { get; set; } } -} +} \ No newline at end of file diff --git a/dsa/DSALib/Models/Database/Dsa/Advantage.cs b/dsa/DSALib/Models/Database/Dsa/Advantage.cs index 2ed0bf9..1a3d40b 100644 --- a/dsa/DSALib/Models/Database/Dsa/Advantage.cs +++ b/dsa/DSALib/Models/Database/Dsa/Advantage.cs @@ -1,11 +1,8 @@ using System; -namespace DSALib.Models.Database.Dsa -{ - public class Advantage - { - public Advantage(string name, string value = "") - { +namespace DSALib.Models.Database.Dsa { + public class Advantage { + public Advantage(string name, string value = "") { Name = name ?? throw new ArgumentNullException(nameof(name)); Value = value ?? throw new ArgumentNullException(nameof(value)); } diff --git a/dsa/DSALib/Models/Database/Dsa/CharSpell.cs b/dsa/DSALib/Models/Database/Dsa/CharSpell.cs index d08bc74..4486004 100644 --- a/dsa/DSALib/Models/Database/Dsa/CharSpell.cs +++ b/dsa/DSALib/Models/Database/Dsa/CharSpell.cs @@ -1,11 +1,8 @@ using System; -namespace DSALib.Models.Database.Dsa -{ - public class CharSpell - { - public CharSpell(string representation, int value) - { +namespace DSALib.Models.Database.Dsa { + public class CharSpell { + public CharSpell(string representation, int value) { this.representation = representation ?? throw new ArgumentNullException(nameof(representation)); this.value = value; } diff --git a/dsa/DSALib/Models/Database/Dsa/DatabaseChar.cs b/dsa/DSALib/Models/Database/Dsa/DatabaseChar.cs index 1312f95..2b163a4 100644 --- a/dsa/DSALib/Models/Database/Dsa/DatabaseChar.cs +++ b/dsa/DSALib/Models/Database/Dsa/DatabaseChar.cs @@ -3,17 +3,13 @@ using System.Collections.Generic; using System.Linq; using DSALib.DSA_Game.Characters; -namespace DSALib.Models.Database.Dsa -{ - public class DatabaseChar - { - public DatabaseChar() - { +namespace DSALib.Models.Database.Dsa { + public class DatabaseChar { + public DatabaseChar() { } public DatabaseChar(int id, string name, string rasse, List skills, List talents, - List advantages, List spells, List weaponTalents) - { + List advantages, List spells, List weaponTalents) { Id = id; Name = name ?? throw new ArgumentNullException(nameof(name)); Race = rasse ?? throw new ArgumentNullException(nameof(rasse)); @@ -41,8 +37,7 @@ namespace DSALib.Models.Database.Dsa public List WeaponTalents { get; set; } = new List(); - public static void LoadChar(Character file, out GroupChar group, out DatabaseChar data) - { + public static void LoadChar(Character file, out GroupChar group, out DatabaseChar data) { group = new GroupChar(); data = new DatabaseChar(); diff --git a/dsa/DSALib/Models/Database/Dsa/Field.cs b/dsa/DSALib/Models/Database/Dsa/Field.cs index 6d1b82e..f720318 100644 --- a/dsa/DSALib/Models/Database/Dsa/Field.cs +++ b/dsa/DSALib/Models/Database/Dsa/Field.cs @@ -1,11 +1,8 @@ using System; -namespace DSALib.Models.Database.Dsa -{ - public class Field - { - public Field(string name, int value = 0) - { +namespace DSALib.Models.Database.Dsa { + public class Field { + public Field(string name, int value = 0) { Name = name ?? throw new ArgumentNullException(nameof(name)); Value = value; } diff --git a/dsa/DSALib/Models/Database/Dsa/GeneralSpell.cs b/dsa/DSALib/Models/Database/Dsa/GeneralSpell.cs index 964c38e..6e1ecf1 100644 --- a/dsa/DSALib/Models/Database/Dsa/GeneralSpell.cs +++ b/dsa/DSALib/Models/Database/Dsa/GeneralSpell.cs @@ -1,20 +1,15 @@ -namespace DSALib.Models.Database.Dsa -{ - public class GeneralSpell : Talent - { +namespace DSALib.Models.Database.Dsa { + public class GeneralSpell : Talent { public char Comlexity = 'A'; - public GeneralSpell(string name, string roll, char comlexity = 'A') : base(name, roll) - { + public GeneralSpell(string name, string roll, char comlexity = 'A') : base(name, roll) { Comlexity = comlexity; } - public GeneralSpell(string name, string roll) : base(name, roll) - { + public GeneralSpell(string name, string roll) : base(name, roll) { } - public GeneralSpell() - { + public GeneralSpell() { } } } \ No newline at end of file diff --git a/dsa/DSALib/Models/Database/Dsa/GroupChar.cs b/dsa/DSALib/Models/Database/Dsa/GroupChar.cs index a0115cd..446bfcc 100644 --- a/dsa/DSALib/Models/Database/Dsa/GroupChar.cs +++ b/dsa/DSALib/Models/Database/Dsa/GroupChar.cs @@ -1,7 +1,5 @@ -namespace DSALib.Models.Database.Dsa -{ - public class GroupChar - { +namespace DSALib.Models.Database.Dsa { + public class GroupChar { public string Name { get; set; } public int Id { get; set; } public int Lp { get; set; } diff --git a/dsa/DSALib/Models/Database/Dsa/Inventory.cs b/dsa/DSALib/Models/Database/Dsa/Inventory.cs index f3f5d7a..5dc5c62 100644 --- a/dsa/DSALib/Models/Database/Dsa/Inventory.cs +++ b/dsa/DSALib/Models/Database/Dsa/Inventory.cs @@ -1,9 +1,7 @@ using System.Collections.Generic; -namespace DSALib.Models.Database.Dsa -{ - public class Inventory - { +namespace DSALib.Models.Database.Dsa { + public class Inventory { public int Id { get; set; } public Dictionary Items { get; set; } = new Dictionary(); public Dictionary Food { get; set; } = new Dictionary(); diff --git a/dsa/DSALib/Models/Database/Dsa/Talent.cs b/dsa/DSALib/Models/Database/Dsa/Talent.cs index 214aecc..18f18ff 100644 --- a/dsa/DSALib/Models/Database/Dsa/Talent.cs +++ b/dsa/DSALib/Models/Database/Dsa/Talent.cs @@ -1,20 +1,15 @@ using System; -namespace DSALib.Models.Database.Dsa -{ - public class Talent : DSALib.Models.Database.DataObject - { - public Talent() - { +namespace DSALib.Models.Database.Dsa { + public class Talent : DataObject { + public Talent() { } - public Talent(string name) - { + public Talent(string name) { Name = name ?? throw new ArgumentNullException(nameof(name)); } - public Talent(string name, string roll) - { + public Talent(string name, string roll) { Name = name ?? throw new ArgumentNullException(nameof(name)); Roll = roll.Split('/'); } diff --git a/dsa/DSALib/Models/Database/Dsa/Weapon.cs b/dsa/DSALib/Models/Database/Dsa/Weapon.cs index 308c6c5..7f9b36e 100644 --- a/dsa/DSALib/Models/Database/Dsa/Weapon.cs +++ b/dsa/DSALib/Models/Database/Dsa/Weapon.cs @@ -1,15 +1,11 @@ using System; -namespace DSALib.Models.Database.Dsa -{ - public class Weapon - { - public Weapon() - { +namespace DSALib.Models.Database.Dsa { + public class Weapon { + public Weapon() { } - public Weapon(string name, string damage, int weight, string weaponTalent, string price) - { + public Weapon(string name, string damage, int weight, string weaponTalent, string price) { Name = name ?? throw new ArgumentNullException(nameof(name)); Damage = damage ?? throw new ArgumentNullException(nameof(damage)); Weight = weight; @@ -24,11 +20,9 @@ namespace DSALib.Models.Database.Dsa public string Price { get; set; } } - public class MeleeWeapon : Weapon - { + public class MeleeWeapon : Weapon { public MeleeWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, - damage, weight, weaponTalent, price) - { + damage, weight, weaponTalent, price) { } public string TpKK { get; set; } @@ -36,11 +30,9 @@ namespace DSALib.Models.Database.Dsa public string MW { get; set; } } - public class RangedWeapon : Weapon - { + public class RangedWeapon : Weapon { public RangedWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, - damage, weight, weaponTalent, price) - { + damage, weight, weaponTalent, price) { } public int AtMod { get; set; } diff --git a/dsa/DSALib/Models/Database/Dsa/WeaponTalent.cs b/dsa/DSALib/Models/Database/Dsa/WeaponTalent.cs index 2ab921b..2deecce 100644 --- a/dsa/DSALib/Models/Database/Dsa/WeaponTalent.cs +++ b/dsa/DSALib/Models/Database/Dsa/WeaponTalent.cs @@ -1,11 +1,8 @@ using System; -namespace DSALib.Models.Database.Dsa -{ - public class WeaponTalent - { - public WeaponTalent(string name, int at, int pa) - { +namespace DSALib.Models.Database.Dsa { + public class WeaponTalent { + public WeaponTalent(string name, int at, int pa) { Name = name ?? throw new ArgumentNullException(nameof(name)); At = at; Pa = pa; diff --git a/dsa/DSALib/Models/Database/Groups/DSAGroup.cs b/dsa/DSALib/Models/Database/Groups/DSAGroup.cs index adbd0ac..574d6a5 100644 --- a/dsa/DSALib/Models/Database/Groups/DSAGroup.cs +++ b/dsa/DSALib/Models/Database/Groups/DSAGroup.cs @@ -1,10 +1,8 @@ using System.Collections.Generic; using DSALib.Models.Database.Dsa; -namespace DSALib.Models.Database.Groups -{ - public class DsaGroup : Group - { +namespace DSALib.Models.Database.Groups { + public class DsaGroup : Group { public List Chars { get; set; } = new List(); } } \ No newline at end of file diff --git a/dsa/DSALib/Models/Database/Groups/Group.cs b/dsa/DSALib/Models/Database/Groups/Group.cs index 096f2be..eaf10c5 100644 --- a/dsa/DSALib/Models/Database/Groups/Group.cs +++ b/dsa/DSALib/Models/Database/Groups/Group.cs @@ -1,7 +1,5 @@ -namespace DSALib.Models.Database.Groups -{ - public class Group - { +namespace DSALib.Models.Database.Groups { + public class Group { public string Name { get; set; } public string Password { get; set; } public int Id { get; set; } diff --git a/dsa/DSALib/Models/Database/IDataObject.cs b/dsa/DSALib/Models/Database/IDataObject.cs index bdc88b7..41a0882 100644 --- a/dsa/DSALib/Models/Database/IDataObject.cs +++ b/dsa/DSALib/Models/Database/IDataObject.cs @@ -1,7 +1,5 @@ -namespace DSALib.Models.Database -{ - public interface IDataObject - { +namespace DSALib.Models.Database { + public interface IDataObject { string Name { get; set; } } } \ No newline at end of file diff --git a/dsa/DSALib/Models/Dsa/CritterAttack.cs b/dsa/DSALib/Models/Dsa/CritterAttack.cs index 8cd8b09..bad3bda 100644 --- a/dsa/DSALib/Models/Dsa/CritterAttack.cs +++ b/dsa/DSALib/Models/Dsa/CritterAttack.cs @@ -1,9 +1,8 @@ -namespace DSALib.Models.Dsa -{ - public class CritterAttack : Database.DataObject - { - public CritterAttack(string name, int at, string tp, string comment = "") - { +using DSALib.Models.Database; + +namespace DSALib.Models.Dsa { + public class CritterAttack : DataObject { + public CritterAttack(string name, int at, string tp, string comment = "") { Name = name; At = at; Tp = tp; diff --git a/dsa/DSALib/Models/Dsa/KampfTalent.cs b/dsa/DSALib/Models/Dsa/KampfTalent.cs index 51ad255..2c82fbb 100644 --- a/dsa/DSALib/Models/Dsa/KampfTalent.cs +++ b/dsa/DSALib/Models/Dsa/KampfTalent.cs @@ -1,9 +1,8 @@ -namespace DSALib.Models.Dsa -{ - public class KampfTalent : Database.DataObject - { - public KampfTalent(string name, int at, int pa) - { +using DSALib.Models.Database; + +namespace DSALib.Models.Dsa { + public class KampfTalent : DataObject { + public KampfTalent(string name, int at, int pa) { Name = name; At = at; Pa = pa; diff --git a/dsa/DSALib/Models/Dsa/Talent.cs b/dsa/DSALib/Models/Dsa/Talent.cs index 5771a74..74fc844 100644 --- a/dsa/DSALib/Models/Dsa/Talent.cs +++ b/dsa/DSALib/Models/Dsa/Talent.cs @@ -1,9 +1,9 @@ -namespace DSALib.Models.Dsa -{ - public class Talent : Database.DataObject // talent objekt +using DSALib.Models.Database; + +namespace DSALib.Models.Dsa { + public class Talent : DataObject // talent objekt { - public Talent(string name, string probe, int value) - { + public Talent(string name, string probe, int value) { Name = name; Probe = probe; Value = value; @@ -21,10 +21,8 @@ return temp; } - public bool IstFernkampftalent() - { - switch (Name) - { + public bool IstFernkampftalent() { + switch (Name) { case "Armbrust": case "Belagerungswaffen": case "Blasrohr": diff --git a/dsa/DSALib/Models/Dsa/Vorteil.cs b/dsa/DSALib/Models/Dsa/Vorteil.cs index e37af20..c07d6f8 100644 --- a/dsa/DSALib/Models/Dsa/Vorteil.cs +++ b/dsa/DSALib/Models/Dsa/Vorteil.cs @@ -1,9 +1,9 @@ -namespace DSALib.Models.Dsa -{ - public class Vorteil : Database.DataObject // talent objekt +using DSALib.Models.Database; + +namespace DSALib.Models.Dsa { + public class Vorteil : DataObject // talent objekt { - public Vorteil(string name, string value = "") - { + public Vorteil(string name, string value = "") { Name = name; Value = value; // this.Choice = choice; diff --git a/dsa/DSALib/Models/Dsa/Zauber.cs b/dsa/DSALib/Models/Dsa/Zauber.cs index e4387bf..b0a8feb 100644 --- a/dsa/DSALib/Models/Dsa/Zauber.cs +++ b/dsa/DSALib/Models/Dsa/Zauber.cs @@ -1,10 +1,7 @@ -namespace DSALib.Models.Dsa -{ - public class Zauber : Talent - { +namespace DSALib.Models.Dsa { + public class Zauber : Talent { public Zauber(string name, string probe, int value, char complexity = 'A', string representation = "Magier") - : base(name, probe, value) - { + : base(name, probe, value) { Complexity = complexity; Representation = Representation; } diff --git a/dsa/DSALib/Models/Network/Command.cs b/dsa/DSALib/Models/Network/Command.cs index 5a97e88..1b54e84 100644 --- a/dsa/DSALib/Models/Network/Command.cs +++ b/dsa/DSALib/Models/Network/Command.cs @@ -1,10 +1,8 @@ using System.Collections.Generic; using System.Linq; -namespace DSALib.Models.Network -{ - public class Command - { +namespace DSALib.Models.Network { + public class Command { public ulong GroupId { get; set; } = 0; public ulong CharId { get; set; } public string Name { get; set; } diff --git a/dsa/DSALib/Models/Network/CommandResponse.cs b/dsa/DSALib/Models/Network/CommandResponse.cs index 0816e4a..02ae99b 100644 --- a/dsa/DSALib/Models/Network/CommandResponse.cs +++ b/dsa/DSALib/Models/Network/CommandResponse.cs @@ -1,11 +1,8 @@ using System; -namespace DSALib.Models.Network -{ - public class CommandResponse - { - public CommandResponse(string message, ResponseType responseType = ResponseType.Broadcast) - { +namespace DSALib.Models.Network { + public class CommandResponse { + public CommandResponse(string message, ResponseType responseType = ResponseType.Broadcast) { this.message = message ?? throw new ArgumentNullException(nameof(message)); ResponseType = responseType; } @@ -13,14 +10,12 @@ namespace DSALib.Models.Network public string message { get; } public ResponseType ResponseType { get; } - public override string ToString() - { + public override string ToString() { return message; } } - public enum ResponseType - { + public enum ResponseType { Broadcast, Caller, Error diff --git a/dsa/FireBase/ExceptionEventArgs.cs b/dsa/FireBase/ExceptionEventArgs.cs index 09c205a..a7ac506 100644 --- a/dsa/FireBase/ExceptionEventArgs.cs +++ b/dsa/FireBase/ExceptionEventArgs.cs @@ -1,28 +1,23 @@ using System; -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Event args holding the object. /// - public class ExceptionEventArgs : EventArgs where T : Exception - { + public class ExceptionEventArgs : EventArgs where T : Exception { public readonly T Exception; /// /// Initializes a new instance of the class. /// /// The exception. - public ExceptionEventArgs(T exception) - { + public ExceptionEventArgs(T exception) { Exception = exception; } } - public class ExceptionEventArgs : ExceptionEventArgs - { - public ExceptionEventArgs(Exception exception) : base(exception) - { + public class ExceptionEventArgs : ExceptionEventArgs { + public ExceptionEventArgs(Exception exception) : base(exception) { } } } \ No newline at end of file diff --git a/dsa/FireBase/Extensions/ObservableExtensions.cs b/dsa/FireBase/Extensions/ObservableExtensions.cs index 0a672d7..1dae7e9 100644 --- a/dsa/FireBase/Extensions/ObservableExtensions.cs +++ b/dsa/FireBase/Extensions/ObservableExtensions.cs @@ -1,10 +1,8 @@ using System; using System.Reactive.Linq; -namespace Firebase.Database.Extensions -{ - public static class ObservableExtensions - { +namespace Firebase.Database.Extensions { + public static class ObservableExtensions { /// /// Returns a cold observable which retries (re-subscribes to) the source observable on error until it successfully /// terminates. @@ -20,12 +18,10 @@ namespace Firebase.Database.Extensions this IObservable source, TimeSpan dueTime, Func retryOnError) - where TException : Exception - { + where TException : Exception { var attempt = 0; - return Observable.Defer(() => - { + return Observable.Defer(() => { return (++attempt == 1 ? source : source.DelaySubscription(dueTime)) .Select(item => new Tuple(true, item, null)) .Catch, TException>(e => retryOnError(e) diff --git a/dsa/FireBase/Extensions/TaskExtensions.cs b/dsa/FireBase/Extensions/TaskExtensions.cs index c955b3a..68d4538 100644 --- a/dsa/FireBase/Extensions/TaskExtensions.cs +++ b/dsa/FireBase/Extensions/TaskExtensions.cs @@ -1,21 +1,16 @@ using System; using System.Threading.Tasks; -namespace Firebase.Database.Extensions -{ - public static class TaskExtensions - { +namespace Firebase.Database.Extensions { + public static class TaskExtensions { /// /// Instead of unwrapping it throws it as it is. /// - public static async Task WithAggregateException(this Task source) - { - try - { + public static async Task WithAggregateException(this Task source) { + try { await source.ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw source.Exception ?? ex; } } diff --git a/dsa/FireBase/FirebaseClient.cs b/dsa/FireBase/FirebaseClient.cs index 3079f3b..e0e96d2 100644 --- a/dsa/FireBase/FirebaseClient.cs +++ b/dsa/FireBase/FirebaseClient.cs @@ -5,13 +5,11 @@ using Firebase.Database.Query; [assembly: InternalsVisibleTo("Firebase.Database.Tests")] -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Firebase client which acts as an entry point to the online database. /// - public class FirebaseClient : IDisposable - { + public class FirebaseClient : IDisposable { private readonly string baseUrl; internal readonly HttpClient HttpClient; internal readonly FirebaseOptions Options; @@ -21,8 +19,7 @@ namespace Firebase.Database /// /// The base url. /// Offline database. - public FirebaseClient(string baseUrl, FirebaseOptions options = null) - { + public FirebaseClient(string baseUrl, FirebaseOptions options = null) { HttpClient = new HttpClient(); Options = options ?? new FirebaseOptions(); @@ -31,8 +28,7 @@ namespace Firebase.Database if (!this.baseUrl.EndsWith("/")) this.baseUrl += "/"; } - public void Dispose() - { + public void Dispose() { HttpClient?.Dispose(); } @@ -41,8 +37,7 @@ namespace Firebase.Database /// /// Name of the child. /// . - public ChildQuery Child(string resourceName) - { + public ChildQuery Child(string resourceName) { return new ChildQuery(this, () => baseUrl + resourceName); } } diff --git a/dsa/FireBase/FirebaseException.cs b/dsa/FireBase/FirebaseException.cs index cfc09d3..f74c54e 100644 --- a/dsa/FireBase/FirebaseException.cs +++ b/dsa/FireBase/FirebaseException.cs @@ -1,13 +1,10 @@ using System; using System.Net; -namespace Firebase.Database -{ - public class FirebaseException : Exception - { +namespace Firebase.Database { + public class FirebaseException : Exception { public FirebaseException(string requestUrl, string requestData, string responseData, HttpStatusCode statusCode) - : base(GenerateExceptionMessage(requestUrl, requestData, responseData)) - { + : base(GenerateExceptionMessage(requestUrl, requestData, responseData)) { RequestUrl = requestUrl; RequestData = requestData; ResponseData = responseData; @@ -16,8 +13,7 @@ namespace Firebase.Database public FirebaseException(string requestUrl, string requestData, string responseData, HttpStatusCode statusCode, Exception innerException) - : base(GenerateExceptionMessage(requestUrl, requestData, responseData), innerException) - { + : base(GenerateExceptionMessage(requestUrl, requestData, responseData), innerException) { RequestUrl = requestUrl; RequestData = requestData; ResponseData = responseData; @@ -44,8 +40,7 @@ namespace Firebase.Database /// public HttpStatusCode StatusCode { get; } - private static string GenerateExceptionMessage(string requestUrl, string requestData, string responseData) - { + private static string GenerateExceptionMessage(string requestUrl, string requestData, string responseData) { return $"Exception occured while processing the request.\nUrl: {requestUrl}\nRequest Data: {requestData}\nResponse: {responseData}"; } diff --git a/dsa/FireBase/FirebaseKeyGenerator.cs b/dsa/FireBase/FirebaseKeyGenerator.cs index 37beed5..2139b7a 100644 --- a/dsa/FireBase/FirebaseKeyGenerator.cs +++ b/dsa/FireBase/FirebaseKeyGenerator.cs @@ -1,14 +1,12 @@ using System; using System.Text; -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Offline key generator which mimics the official Firebase generators. /// Credit: https://github.com/bubbafat/FirebaseSharp/blob/master/src/FirebaseSharp.Portable/FireBasePushIdGenerator.cs /// - public class FirebaseKeyGenerator - { + public class FirebaseKeyGenerator { // Modeled after base64 web-safe chars, but ordered by ASCII. private const string PushCharsString = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; private static readonly char[] PushChars; @@ -20,8 +18,7 @@ namespace Firebase.Database // Timestamp of last push, used to prevent local collisions if you push twice in one ms. private static long lastPushTime; - static FirebaseKeyGenerator() - { + static FirebaseKeyGenerator() { PushChars = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(PushCharsString)); } @@ -31,8 +28,7 @@ namespace Firebase.Database /// /// The . /// - public static string Next() - { + public static string Next() { // We generate 72-bits of randomness which get turned into 12 characters and // appended to the timestamp to prevent collisions with other clients. We store the last // characters we generated because in the event of a collision, we'll use those same @@ -43,8 +39,7 @@ namespace Firebase.Database lastPushTime = now; var timeStampChars = new char[8]; - for (var i = 7; i >= 0; i--) - { + for (var i = 7; i >= 0; i--) { var index = (int) (now % PushChars.Length); timeStampChars[i] = PushChars[index]; now = (long) Math.Floor((double) now / PushChars.Length); @@ -54,12 +49,10 @@ namespace Firebase.Database id.Append(timeStampChars); - if (!duplicateTime) - { + if (!duplicateTime) { for (var i = 0; i < 12; i++) lastRandChars[i] = (byte) random.Next(0, PushChars.Length); } - else - { + else { // If the timestamp hasn't changed since last push, use the same random number, // except incremented by 1. var lastIndex = 11; diff --git a/dsa/FireBase/FirebaseObject.cs b/dsa/FireBase/FirebaseObject.cs index 2e0fd20..f53b2d4 100644 --- a/dsa/FireBase/FirebaseObject.cs +++ b/dsa/FireBase/FirebaseObject.cs @@ -1,15 +1,12 @@ -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Holds the object of type /// /// along with its key. /// /// Type of the underlying object. - public class FirebaseObject - { - internal FirebaseObject(string key, T obj) - { + public class FirebaseObject { + internal FirebaseObject(string key, T obj) { Key = key; Object = obj; } diff --git a/dsa/FireBase/FirebaseOptions.cs b/dsa/FireBase/FirebaseOptions.cs index b4a5e51..08f1935 100644 --- a/dsa/FireBase/FirebaseOptions.cs +++ b/dsa/FireBase/FirebaseOptions.cs @@ -5,12 +5,9 @@ using System.Threading.Tasks; using Firebase.Database.Offline; using Newtonsoft.Json; -namespace Firebase.Database -{ - public class FirebaseOptions - { - public FirebaseOptions() - { +namespace Firebase.Database { + public class FirebaseOptions { + public FirebaseOptions() { OfflineDatabaseFactory = (t, s) => new Dictionary(); SubscriptionStreamReaderFactory = s => new StreamReader(s); JsonSerializerSettings = new JsonSerializerSettings(); diff --git a/dsa/FireBase/Http/HttpClientExtensions.cs b/dsa/FireBase/Http/HttpClientExtensions.cs index 6582769..a4f1c11 100644 --- a/dsa/FireBase/Http/HttpClientExtensions.cs +++ b/dsa/FireBase/Http/HttpClientExtensions.cs @@ -7,13 +7,11 @@ using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; -namespace Firebase.Database.Http -{ +namespace Firebase.Database.Http { /// /// The http client extensions for object deserializations. /// - internal static class HttpClientExtensions - { + internal static class HttpClientExtensions { /// /// The get object collection async. /// @@ -24,13 +22,11 @@ namespace Firebase.Database.Http /// The . public static async Task>> GetObjectCollectionAsync( this HttpClient client, string requestUri, - JsonSerializerSettings jsonSerializerSettings) - { + JsonSerializerSettings jsonSerializerSettings) { var responseData = string.Empty; var statusCode = HttpStatusCode.OK; - try - { + try { var response = await client.GetAsync(requestUri).ConfigureAwait(false); statusCode = response.StatusCode; responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -44,8 +40,7 @@ namespace Firebase.Database.Http return dictionary.Select(item => new FirebaseObject(item.Key, item.Value)).ToList(); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(requestUri, string.Empty, responseData, statusCode, ex); } } @@ -96,21 +91,18 @@ namespace Firebase.Database.Http /// The json data. /// The type of entities the collection should contain. /// The . - public static IEnumerable> GetObjectCollection(this string data, Type elementType) - { + public static IEnumerable> GetObjectCollection(this string data, Type elementType) { var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), elementType); IDictionary dictionary = null; - if (data.StartsWith("[")) - { + if (data.StartsWith("[")) { var listType = typeof(List<>).MakeGenericType(elementType); var list = JsonConvert.DeserializeObject(data, listType) as IList; dictionary = Activator.CreateInstance(dictionaryType) as IDictionary; var index = 0; foreach (var item in list) dictionary.Add(index++.ToString(), item); } - else - { + else { dictionary = JsonConvert.DeserializeObject(data, dictionaryType) as IDictionary; } diff --git a/dsa/FireBase/Http/PostResult.cs b/dsa/FireBase/Http/PostResult.cs index 15a4894..b6b8f09 100644 --- a/dsa/FireBase/Http/PostResult.cs +++ b/dsa/FireBase/Http/PostResult.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Http -{ +namespace Firebase.Database.Http { /// /// Represents data returned after a successful POST to firebase server. /// - public class PostResult - { + public class PostResult { /// /// Gets or sets the generated key after a successful post. /// diff --git a/dsa/FireBase/ObservableExtensions.cs b/dsa/FireBase/ObservableExtensions.cs index bc46261..69730df 100644 --- a/dsa/FireBase/ObservableExtensions.cs +++ b/dsa/FireBase/ObservableExtensions.cs @@ -2,34 +2,28 @@ using System.Collections.ObjectModel; using Firebase.Database.Streaming; -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Extensions for . /// - public static class ObservableExtensions - { + public static class ObservableExtensions { /// /// Starts observing on given firebase observable and propagates event into an . /// /// The observable. /// Type of entity. /// The . - public static ObservableCollection AsObservableCollection(this IObservable> observable) - { + public static ObservableCollection AsObservableCollection(this IObservable> observable) { var collection = new ObservableCollection(); - observable.Subscribe(f => - { - if (f.EventType == FirebaseEventType.InsertOrUpdate) - { + observable.Subscribe(f => { + if (f.EventType == FirebaseEventType.InsertOrUpdate) { var i = collection.IndexOf(f.Object); if (i >= 0) collection.RemoveAt(i); collection.Add(f.Object); } - else - { + else { collection.Remove(f.Object); } }); diff --git a/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs b/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs index 1a9e607..724115f 100644 --- a/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs +++ b/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs @@ -6,13 +6,11 @@ using System.IO; using System.Linq; using LiteDB; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// The offline database. /// - public class ConcurrentOfflineDatabase : IDictionary - { + public class ConcurrentOfflineDatabase : IDictionary { private readonly ConcurrentDictionary ccache; private readonly LiteRepository db; @@ -21,8 +19,7 @@ namespace Firebase.Database.Offline /// /// The item type which is used to determine the database file name. /// Custom string which will get appended to the file name. - public ConcurrentOfflineDatabase(Type itemType, string filenameModifier) - { + public ConcurrentOfflineDatabase(Type itemType, string filenameModifier) { var fullName = GetFileName(itemType.ToString()); if (fullName.Length > 100) fullName = fullName.Substring(0, 100); @@ -78,12 +75,10 @@ namespace Firebase.Database.Offline /// /// The key of the element to get or set. /// The element with the specified key. - public OfflineEntry this[string key] - { + public OfflineEntry this[string key] { get => ccache[key]; - set - { + set { ccache.AddOrUpdate(key, value, (k, existing) => value); db.Upsert(value); } @@ -93,13 +88,11 @@ namespace Firebase.Database.Offline /// Returns an enumerator that iterates through the collection. /// /// An enumerator that can be used to iterate through the collection. - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return ccache.GetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } @@ -107,16 +100,14 @@ namespace Firebase.Database.Offline /// Adds an item to the . /// /// The object to add to the . - public void Add(KeyValuePair item) - { + public void Add(KeyValuePair item) { Add(item.Key, item.Value); } /// /// Removes all items from the . /// - public void Clear() - { + public void Clear() { ccache.Clear(); db.Delete(LiteDB.Query.All()); } @@ -129,8 +120,7 @@ namespace Firebase.Database.Offline /// True if is found in the ; /// otherwise, false. /// - public bool Contains(KeyValuePair item) - { + public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } @@ -144,8 +134,7 @@ namespace Firebase.Database.Offline /// zero-based indexing. /// /// The zero-based index in at which copying begins. - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { + public void CopyTo(KeyValuePair[] array, int arrayIndex) { ccache.ToList().CopyTo(array, arrayIndex); } @@ -159,8 +148,7 @@ namespace Firebase.Database.Offline /// ; otherwise, false. This method also returns false if /// is not found in the original . /// - public bool Remove(KeyValuePair item) - { + public bool Remove(KeyValuePair item) { return Remove(item.Key); } @@ -173,8 +161,7 @@ namespace Firebase.Database.Offline /// True if the contains an element with the key; /// otherwise, false. /// - public bool ContainsKey(string key) - { + public bool ContainsKey(string key) { return ccache.ContainsKey(key); } @@ -183,8 +170,7 @@ namespace Firebase.Database.Offline /// /// The object to use as the key of the element to add. /// The object to use as the value of the element to add. - public void Add(string key, OfflineEntry value) - { + public void Add(string key, OfflineEntry value) { ccache.AddOrUpdate(key, value, (k, existing) => value); db.Upsert(value); } @@ -197,8 +183,7 @@ namespace Firebase.Database.Offline /// True if the element is successfully removed; otherwise, false. This method also returns false if /// was not found in the original . /// - public bool Remove(string key) - { + public bool Remove(string key) { ccache.TryRemove(key, out _); return db.Delete(key); } @@ -216,13 +201,11 @@ namespace Firebase.Database.Offline /// True if the object that implements contains an /// element with the specified key; otherwise, false. /// - public bool TryGetValue(string key, out OfflineEntry value) - { + public bool TryGetValue(string key, out OfflineEntry value) { return ccache.TryGetValue(key, out value); } - private string GetFileName(string fileName) - { + private string GetFileName(string fileName) { var invalidChars = new[] {'`', '[', ',', '='}; foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct()) fileName = fileName.Replace(c, '_'); diff --git a/dsa/FireBase/Offline/DatabaseExtensions.cs b/dsa/FireBase/Offline/DatabaseExtensions.cs index e7c4074..75624f1 100644 --- a/dsa/FireBase/Offline/DatabaseExtensions.cs +++ b/dsa/FireBase/Offline/DatabaseExtensions.cs @@ -4,10 +4,8 @@ using System.Linq.Expressions; using System.Reflection; using Firebase.Database.Query; -namespace Firebase.Database.Offline -{ - public static class DatabaseExtensions - { +namespace Firebase.Database.Offline { + public static class DatabaseExtensions { /// /// Create new instances of the . /// @@ -24,8 +22,7 @@ namespace Firebase.Database.Offline public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) - where T : class - { + where T : class { return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges); } @@ -49,8 +46,7 @@ namespace Firebase.Database.Offline StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class - where TSetHandler : ISetHandler, new() - { + where TSetHandler : ISetHandler, new() { return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges, Activator.CreateInstance()); @@ -68,8 +64,7 @@ namespace Firebase.Database.Offline /// public static void Patch(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -85,8 +80,7 @@ namespace Firebase.Database.Offline /// public static void Put(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -101,8 +95,7 @@ namespace Firebase.Database.Offline /// /// The generated key for this object. public static string Post(this RealtimeDatabase db, T obj, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { var key = FirebaseKeyGenerator.Next(); db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); @@ -120,8 +113,7 @@ namespace Firebase.Database.Offline /// priority. /// public static void Delete(this RealtimeDatabase db, string key, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -143,8 +135,7 @@ namespace Firebase.Database.Offline public static void Put(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -166,8 +157,7 @@ namespace Firebase.Database.Offline public static void Patch(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -189,8 +179,7 @@ namespace Firebase.Database.Offline public static void Delete(this RealtimeDatabase db, string key, Expression> propertyExpression, bool syncOnline = true, int priority = 1) where T : class - where TProperty : class - { + where TProperty : class { db.Set(key, propertyExpression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -215,8 +204,7 @@ namespace Firebase.Database.Offline Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) where T : class - where TSelector : IDictionary - { + where TSelector : IDictionary { var nextKey = FirebaseKeyGenerator.Next(); var expression = Expression.Lambda>( Expression.Call(propertyExpression.Body, @@ -245,8 +233,7 @@ namespace Firebase.Database.Offline public static void Delete(this RealtimeDatabase db, string key, Expression>> propertyExpression, string dictionaryKey, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { var expression = Expression.Lambda>( Expression.Call(propertyExpression.Body, typeof(IDictionary).GetRuntimeMethod("get_Item", new[] {typeof(string)}), diff --git a/dsa/FireBase/Offline/ISetHandler.cs b/dsa/FireBase/Offline/ISetHandler.cs index c04bd41..699d33a 100644 --- a/dsa/FireBase/Offline/ISetHandler.cs +++ b/dsa/FireBase/Offline/ISetHandler.cs @@ -1,10 +1,8 @@ using System.Threading.Tasks; using Firebase.Database.Query; -namespace Firebase.Database.Offline -{ - public interface ISetHandler - { +namespace Firebase.Database.Offline { + public interface ISetHandler { Task SetAsync(ChildQuery query, string key, OfflineEntry entry); } } \ No newline at end of file diff --git a/dsa/FireBase/Offline/InitialPullStrategy.cs b/dsa/FireBase/Offline/InitialPullStrategy.cs index ca2bebf..292c716 100644 --- a/dsa/FireBase/Offline/InitialPullStrategy.cs +++ b/dsa/FireBase/Offline/InitialPullStrategy.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// Specifies the strategy for initial pull of server data. /// - public enum InitialPullStrategy - { + public enum InitialPullStrategy { /// /// Don't pull anything. /// diff --git a/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs b/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs index 89a77da..fe888ac 100644 --- a/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs +++ b/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs @@ -3,37 +3,29 @@ using System.Linq.Expressions; using System.Reflection; using Newtonsoft.Json; -namespace Firebase.Database.Offline.Internals -{ - public class MemberAccessVisitor : ExpressionVisitor - { +namespace Firebase.Database.Offline.Internals { + public class MemberAccessVisitor : ExpressionVisitor { private readonly IList propertyNames = new List(); private bool wasDictionaryAccess; public IEnumerable PropertyNames => propertyNames; - public override Expression Visit(Expression expr) - { - if (expr?.NodeType == ExpressionType.MemberAccess) - { - if (wasDictionaryAccess) - { + public override Expression Visit(Expression expr) { + if (expr?.NodeType == ExpressionType.MemberAccess) { + if (wasDictionaryAccess) { wasDictionaryAccess = false; } - else - { + else { var memberExpr = (MemberExpression) expr; var jsonAttr = memberExpr.Member.GetCustomAttribute(); propertyNames.Add(jsonAttr?.PropertyName ?? memberExpr.Member.Name); } } - else if (expr?.NodeType == ExpressionType.Call) - { + else if (expr?.NodeType == ExpressionType.Call) { var callExpr = (MethodCallExpression) expr; - if (callExpr.Method.Name == "get_Item" && callExpr.Arguments.Count == 1) - { + if (callExpr.Method.Name == "get_Item" && callExpr.Arguments.Count == 1) { var e = Expression.Lambda(callExpr.Arguments[0]).Compile(); propertyNames.Add(e.DynamicInvoke().ToString()); wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess; diff --git a/dsa/FireBase/Offline/OfflineCacheAdapter.cs b/dsa/FireBase/Offline/OfflineCacheAdapter.cs index 3153d1b..9881c78 100644 --- a/dsa/FireBase/Offline/OfflineCacheAdapter.cs +++ b/dsa/FireBase/Offline/OfflineCacheAdapter.cs @@ -3,19 +3,15 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -namespace Firebase.Database.Offline -{ - internal class OfflineCacheAdapter : IDictionary, IDictionary - { +namespace Firebase.Database.Offline { + internal class OfflineCacheAdapter : IDictionary, IDictionary { private readonly IDictionary database; - public OfflineCacheAdapter(IDictionary database) - { + public OfflineCacheAdapter(IDictionary database) { this.database = database; } - public void CopyTo(Array array, int index) - { + public void CopyTo(Array array, int index) { throw new NotImplementedException(); } @@ -23,12 +19,10 @@ namespace Firebase.Database.Offline public object SyncRoot { get; } - object IDictionary.this[object key] - { + object IDictionary.this[object key] { get => database[key.ToString()].Deserialize(); - set - { + set { var keyString = key.ToString(); if (database.ContainsKey(keyString)) database[keyString] = new OfflineEntry(keyString, value, database[keyString].Priority, @@ -42,25 +36,21 @@ namespace Firebase.Database.Offline ICollection IDictionary.Keys { get; } - public bool Contains(object key) - { + public bool Contains(object key) { return ContainsKey(key.ToString()); } - IDictionaryEnumerator IDictionary.GetEnumerator() - { + IDictionaryEnumerator IDictionary.GetEnumerator() { throw new NotImplementedException(); } - public void Remove(object key) - { + public void Remove(object key) { Remove(key.ToString()); } public bool IsFixedSize => false; - public void Add(object key, object value) - { + public void Add(object key, object value) { Add(key.ToString(), (T) value); } @@ -72,12 +62,10 @@ namespace Firebase.Database.Offline public ICollection Values => database.Values.Select(o => o.Deserialize()).ToList(); - public T this[string key] - { + public T this[string key] { get => database[key].Deserialize(); - set - { + set { if (database.ContainsKey(key)) database[key] = new OfflineEntry(key, value, database[key].Priority, database[key].SyncOptions); else @@ -85,62 +73,50 @@ namespace Firebase.Database.Offline } } - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return database.Select(d => new KeyValuePair(d.Key, d.Value.Deserialize())).GetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } - public void Add(KeyValuePair item) - { + public void Add(KeyValuePair item) { Add(item.Key, item.Value); } - public void Clear() - { + public void Clear() { database.Clear(); } - public bool Contains(KeyValuePair item) - { + public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { + public void CopyTo(KeyValuePair[] array, int arrayIndex) { throw new NotImplementedException(); } - public bool Remove(KeyValuePair item) - { + public bool Remove(KeyValuePair item) { return database.Remove(item.Key); } - public void Add(string key, T value) - { + public void Add(string key, T value) { database.Add(key, new OfflineEntry(key, value, 1, SyncOptions.None)); } - public bool ContainsKey(string key) - { + public bool ContainsKey(string key) { return database.ContainsKey(key); } - public bool Remove(string key) - { + public bool Remove(string key) { return database.Remove(key); } - public bool TryGetValue(string key, out T value) - { + public bool TryGetValue(string key, out T value) { OfflineEntry val; - if (database.TryGetValue(key, out val)) - { + if (database.TryGetValue(key, out val)) { value = val.Deserialize(); return true; } diff --git a/dsa/FireBase/Offline/OfflineDatabase.cs b/dsa/FireBase/Offline/OfflineDatabase.cs index be0380b..5820dc6 100644 --- a/dsa/FireBase/Offline/OfflineDatabase.cs +++ b/dsa/FireBase/Offline/OfflineDatabase.cs @@ -5,13 +5,11 @@ using System.IO; using System.Linq; using LiteDB; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// The offline database. /// - public class OfflineDatabase : IDictionary - { + public class OfflineDatabase : IDictionary { private readonly IDictionary cache; private readonly LiteRepository db; @@ -20,8 +18,7 @@ namespace Firebase.Database.Offline /// /// The item type which is used to determine the database file name. /// Custom string which will get appended to the file name. - public OfflineDatabase(Type itemType, string filenameModifier) - { + public OfflineDatabase(Type itemType, string filenameModifier) { var fullName = GetFileName(itemType.ToString()); if (fullName.Length > 100) fullName = fullName.Substring(0, 100); @@ -73,12 +70,10 @@ namespace Firebase.Database.Offline /// /// The key of the element to get or set. /// The element with the specified key. - public OfflineEntry this[string key] - { + public OfflineEntry this[string key] { get => cache[key]; - set - { + set { cache[key] = value; db.Upsert(value); } @@ -88,13 +83,11 @@ namespace Firebase.Database.Offline /// Returns an enumerator that iterates through the collection. /// /// An enumerator that can be used to iterate through the collection. - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return cache.GetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } @@ -102,16 +95,14 @@ namespace Firebase.Database.Offline /// Adds an item to the . /// /// The object to add to the . - public void Add(KeyValuePair item) - { + public void Add(KeyValuePair item) { Add(item.Key, item.Value); } /// /// Removes all items from the . /// - public void Clear() - { + public void Clear() { cache.Clear(); db.Delete(LiteDB.Query.All()); } @@ -124,8 +115,7 @@ namespace Firebase.Database.Offline /// True if is found in the ; /// otherwise, false. /// - public bool Contains(KeyValuePair item) - { + public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } @@ -139,8 +129,7 @@ namespace Firebase.Database.Offline /// zero-based indexing. /// /// The zero-based index in at which copying begins. - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { + public void CopyTo(KeyValuePair[] array, int arrayIndex) { cache.CopyTo(array, arrayIndex); } @@ -154,8 +143,7 @@ namespace Firebase.Database.Offline /// ; otherwise, false. This method also returns false if /// is not found in the original . /// - public bool Remove(KeyValuePair item) - { + public bool Remove(KeyValuePair item) { return Remove(item.Key); } @@ -168,8 +156,7 @@ namespace Firebase.Database.Offline /// True if the contains an element with the key; /// otherwise, false. /// - public bool ContainsKey(string key) - { + public bool ContainsKey(string key) { return cache.ContainsKey(key); } @@ -178,8 +165,7 @@ namespace Firebase.Database.Offline /// /// The object to use as the key of the element to add. /// The object to use as the value of the element to add. - public void Add(string key, OfflineEntry value) - { + public void Add(string key, OfflineEntry value) { cache.Add(key, value); db.Insert(value); } @@ -192,8 +178,7 @@ namespace Firebase.Database.Offline /// True if the element is successfully removed; otherwise, false. This method also returns false if /// was not found in the original . /// - public bool Remove(string key) - { + public bool Remove(string key) { cache.Remove(key); return db.Delete(key); } @@ -211,13 +196,11 @@ namespace Firebase.Database.Offline /// True if the object that implements contains an /// element with the specified key; otherwise, false. /// - public bool TryGetValue(string key, out OfflineEntry value) - { + public bool TryGetValue(string key, out OfflineEntry value) { return cache.TryGetValue(key, out value); } - private string GetFileName(string fileName) - { + private string GetFileName(string fileName) { var invalidChars = new[] {'`', '[', ',', '='}; foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct()) fileName = fileName.Replace(c, '_'); diff --git a/dsa/FireBase/Offline/OfflineEntry.cs b/dsa/FireBase/Offline/OfflineEntry.cs index 9feffa3..c959510 100644 --- a/dsa/FireBase/Offline/OfflineEntry.cs +++ b/dsa/FireBase/Offline/OfflineEntry.cs @@ -1,13 +1,11 @@ using System; using Newtonsoft.Json; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// Represents an object stored in offline storage. /// - public class OfflineEntry - { + public class OfflineEntry { private object dataInstance; /// @@ -21,8 +19,7 @@ namespace Firebase.Database.Offline /// /// The sync options. public OfflineEntry(string key, object obj, string data, int priority, SyncOptions syncOptions, - bool isPartial = false) - { + bool isPartial = false) { Key = key; Priority = priority; Data = data; @@ -44,15 +41,13 @@ namespace Firebase.Database.Offline /// /// The sync options. public OfflineEntry(string key, object obj, int priority, SyncOptions syncOptions, bool isPartial = false) - : this(key, obj, JsonConvert.SerializeObject(obj), priority, syncOptions, isPartial) - { + : this(key, obj, JsonConvert.SerializeObject(obj), priority, syncOptions, isPartial) { } /// /// Initializes a new instance of the class. /// - public OfflineEntry() - { + public OfflineEntry() { } /// @@ -91,8 +86,7 @@ namespace Firebase.Database.Offline /// /// Type of object to deserialize into. /// Instance of . - public T Deserialize() - { + public T Deserialize() { return (T) (dataInstance ?? (dataInstance = JsonConvert.DeserializeObject(Data))); } } diff --git a/dsa/FireBase/Offline/RealtimeDatabase.cs b/dsa/FireBase/Offline/RealtimeDatabase.cs index 973db46..e66a1f1 100644 --- a/dsa/FireBase/Offline/RealtimeDatabase.cs +++ b/dsa/FireBase/Offline/RealtimeDatabase.cs @@ -16,14 +16,12 @@ using Firebase.Database.Query; using Firebase.Database.Streaming; using Newtonsoft.Json; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// The real-time Database which synchronizes online and offline data. /// /// Type of entities. - public class RealtimeDatabase : IDisposable where T : class - { + public class RealtimeDatabase : IDisposable where T : class { private readonly ChildQuery childQuery; private readonly string elementRoot; private readonly FirebaseCache firebaseCache; @@ -55,8 +53,7 @@ namespace Firebase.Database.Offline public RealtimeDatabase(ChildQuery childQuery, string elementRoot, Func> offlineDatabaseFactory, string filenameModifier, StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, - ISetHandler setHandler = null) - { + ISetHandler setHandler = null) { this.childQuery = childQuery; this.elementRoot = elementRoot; this.streamingOptions = streamingOptions; @@ -80,8 +77,7 @@ namespace Firebase.Database.Offline public ISetHandler PutHandler { private get; set; } - public void Dispose() - { + public void Dispose() { subject.OnCompleted(); firebaseSubscription?.Dispose(); } @@ -102,19 +98,16 @@ namespace Firebase.Database.Offline /// The priority. Objects with higher priority will be synced first. Higher number indicates higher /// priority. /// - public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1) - { + public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1) { SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions)); } public void Set(string key, Expression> propertyExpression, object value, - SyncOptions syncOptions, int priority = 1) - { + SyncOptions syncOptions, int priority = 1) { var fullKey = GenerateFullKey(key, propertyExpression, syncOptions); var serializedObject = JsonConvert.SerializeObject(value).Trim('"', '\\'); - if (fullKey.Item3) - { + if (fullKey.Item3) { if (typeof(TProperty) != typeof(string) || value == null) // don't escape non-string primitives and null; serializedObject = $"{{ \"{fullKey.Item2}\" : {serializedObject} }}"; @@ -142,8 +135,7 @@ namespace Firebase.Database.Offline /// The priority. Objects with higher priority will be synced first. Higher number indicates higher /// priority. /// - public void Pull(string key, int priority = 1) - { + public void Pull(string key, int priority = 1) { if (!Database.ContainsKey(key)) Database[key] = new OfflineEntry(key, null, priority, SyncOptions.Pull); else if (Database[key].SyncOptions == SyncOptions.None) @@ -154,8 +146,7 @@ namespace Firebase.Database.Offline /// /// Fetches everything from the remote database. /// - public async Task PullAsync() - { + public async Task PullAsync() { var existingEntries = await childQuery .OnceAsync() .ToObservable() @@ -166,8 +157,7 @@ namespace Firebase.Database.Offline .OK) // OK implies the request couldn't complete due to network error. .Select(e => ResetDatabaseFromInitial(e, false)) .SelectMany(e => e) - .Do(e => - { + .Do(e => { Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None); subject.OnNext(new FirebaseEvent(e.Key, e.Object, FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePull)); @@ -175,8 +165,7 @@ namespace Firebase.Database.Offline .ToList(); // Remove items not stored online - foreach (var item in Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList()) - { + foreach (var item in Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList()) { Database.Remove(item); subject.OnNext(new FirebaseEvent(item, null, FirebaseEventType.Delete, FirebaseEventSource.OnlinePull)); @@ -186,8 +175,7 @@ namespace Firebase.Database.Offline /// /// Retrieves all offline items currently stored in local database. /// - public IEnumerable> Once() - { + public IEnumerable> Once() { return Database .Where(kvp => !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial) .Select(kvp => new FirebaseObject(kvp.Key, kvp.Value.Deserialize())) @@ -198,17 +186,14 @@ namespace Firebase.Database.Offline /// Starts observing the real-time Database. Events will be fired both when change is done locally and remotely. /// /// Stream of . - public IObservable> AsObservable() - { - if (!isSyncRunning) - { + public IObservable> AsObservable() { + if (!isSyncRunning) { isSyncRunning = true; Task.Factory.StartNew(SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } - if (observable == null) - { + if (observable == null) { var initialData = Observable.Return(FirebaseEvent.Empty(FirebaseEventSource.Offline)); if (Database.TryGetValue(elementRoot, out var oe)) initialData = Observable.Return(oe) @@ -251,8 +236,7 @@ namespace Firebase.Database.Offline } private IReadOnlyCollection> ResetDatabaseFromInitial( - IReadOnlyCollection> collection, bool onlyWhenInitialEverything = true) - { + IReadOnlyCollection> collection, bool onlyWhenInitialEverything = true) { if (onlyWhenInitialEverything && initialPullStrategy != InitialPullStrategy.Everything) return collection; // items which are in local db, but not in the online collection @@ -264,8 +248,7 @@ namespace Firebase.Database.Offline return collection.Concat(extra).ToList(); } - private void SetObjectFromInitialPull(FirebaseObject e) - { + private void SetObjectFromInitialPull(FirebaseObject e) { // set object with no sync only if it doesn't exist yet // and the InitialPullStrategy != Everything // this attempts to deal with scenario when you are offline, have local changes and go online @@ -276,11 +259,9 @@ namespace Firebase.Database.Offline Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None); } - private IObservable>> GetInitialPullObservable() - { + private IObservable>> GetInitialPullObservable() { FirebaseQuery query; - switch (initialPullStrategy) - { + switch (initialPullStrategy) { case InitialPullStrategy.MissingOnly: query = childQuery.OrderByKey().StartAt(() => GetLatestKey()); break; @@ -301,12 +282,10 @@ namespace Firebase.Database.Offline .Select(e => new[] {new FirebaseObject(elementRoot, e)})); } - private IDisposable InitializeStreamingSubscription(IObserver> observer) - { + private IDisposable InitializeStreamingSubscription(IObserver> observer) { var completeDisposable = Disposable.Create(() => isSyncRunning = false); - switch (streamingOptions) - { + switch (streamingOptions) { case StreamingOptions.LatestOnly: // stream since the latest key var queryLatest = childQuery.OrderByKey().StartAt(() => GetLatestKey()); @@ -328,8 +307,7 @@ namespace Firebase.Database.Offline } private void SetAndRaise(string key, OfflineEntry obj, - FirebaseEventSource eventSource = FirebaseEventSource.Offline) - { + FirebaseEventSource eventSource = FirebaseEventSource.Offline) { Database[key] = obj; subject.OnNext(new FirebaseEvent(key, obj?.Deserialize(), string.IsNullOrEmpty(obj?.Data) || obj?.Data == "null" @@ -337,12 +315,9 @@ namespace Firebase.Database.Offline : FirebaseEventType.InsertOrUpdate, eventSource)); } - private async void SynchronizeThread() - { - while (isSyncRunning) - { - try - { + private async void SynchronizeThread() { + while (isSyncRunning) { + try { var validEntries = Database.Where(e => e.Value != null); await PullEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Pull)); @@ -350,8 +325,7 @@ namespace Firebase.Database.Offline await PushEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Put || kvp.Value.SyncOptions == SyncOptions.Patch)); } - catch (Exception ex) - { + catch (Exception ex) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } @@ -359,8 +333,7 @@ namespace Firebase.Database.Offline } } - private string GetLatestKey() - { + private string GetLatestKey() { var key = Database.OrderBy(o => o.Key, StringComparer.Ordinal).LastOrDefault().Key ?? string.Empty; if (!string.IsNullOrWhiteSpace(key)) @@ -369,60 +342,50 @@ namespace Firebase.Database.Offline return key; } - private async Task PushEntriesAsync(IEnumerable> pushEntries) - { + private async Task PushEntriesAsync(IEnumerable> pushEntries) { var groups = pushEntries.GroupBy(pair => pair.Value.Priority).OrderByDescending(kvp => kvp.Key).ToList(); - foreach (var group in groups) - { + foreach (var group in groups) { var tasks = group.OrderBy(kvp => kvp.Value.IsPartial).Select(kvp => kvp.Value.IsPartial ? ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key) : ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key, kvp.Value.Deserialize())); - try - { + try { await Task.WhenAll(tasks).WithAggregateException(); } - catch (Exception ex) - { + catch (Exception ex) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } } } - private async Task PullEntriesAsync(IEnumerable> pullEntries) - { + private async Task PullEntriesAsync(IEnumerable> pullEntries) { var taskGroups = pullEntries.GroupBy(pair => pair.Value.Priority).OrderByDescending(kvp => kvp.Key); - foreach (var group in taskGroups) - { + foreach (var group in taskGroups) { var tasks = group.Select(pair => ResetAfterPull( childQuery.Child(pair.Key == elementRoot ? string.Empty : pair.Key).OnceSingleAsync(), pair.Key, pair.Value)); - try - { + try { await Task.WhenAll(tasks).WithAggregateException(); } - catch (Exception ex) - { + catch (Exception ex) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } } } - private async Task ResetAfterPull(Task task, string key, OfflineEntry entry) - { + private async Task ResetAfterPull(Task task, string key, OfflineEntry entry) { await task; SetAndRaise(key, new OfflineEntry(key, task.Result, entry.Priority, SyncOptions.None), FirebaseEventSource.OnlinePull); } - private async Task ResetSyncAfterPush(Task task, string key, T obj) - { + private async Task ResetSyncAfterPush(Task task, string key, T obj) { await ResetSyncAfterPush(task, key); if (streamingOptions == StreamingOptions.None) @@ -431,35 +394,29 @@ namespace Firebase.Database.Offline FirebaseEventSource.OnlinePush)); } - private async Task ResetSyncAfterPush(Task task, string key) - { + private async Task ResetSyncAfterPush(Task task, string key) { await task; ResetSyncOptions(key); } - private void ResetSyncOptions(string key) - { + private void ResetSyncOptions(string key) { var item = Database[key]; - if (item.IsPartial) - { + if (item.IsPartial) { Database.Remove(key); } - else - { + else { item.SyncOptions = SyncOptions.None; Database[key] = item; } } - private void StreamingExceptionThrown(object sender, ExceptionEventArgs e) - { + private void StreamingExceptionThrown(object sender, ExceptionEventArgs e) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception)); } private Tuple GenerateFullKey(string key, - Expression> propertyGetter, SyncOptions syncOptions) - { + Expression> propertyGetter, SyncOptions syncOptions) { var visitor = new MemberAccessVisitor(); visitor.Visit(propertyGetter); var propertyType = typeof(TProperty).GetTypeInfo(); diff --git a/dsa/FireBase/Offline/SetHandler.cs b/dsa/FireBase/Offline/SetHandler.cs index 6314c3c..c683fdd 100644 --- a/dsa/FireBase/Offline/SetHandler.cs +++ b/dsa/FireBase/Offline/SetHandler.cs @@ -1,14 +1,10 @@ using System.Threading.Tasks; using Firebase.Database.Query; -namespace Firebase.Database.Offline -{ - public class SetHandler : ISetHandler - { - public virtual async Task SetAsync(ChildQuery query, string key, OfflineEntry entry) - { - using (var child = query.Child(key)) - { +namespace Firebase.Database.Offline { + public class SetHandler : ISetHandler { + public virtual async Task SetAsync(ChildQuery query, string key, OfflineEntry entry) { + using (var child = query.Child(key)) { if (entry.SyncOptions == SyncOptions.Put) await child.PutAsync(entry.Data); else diff --git a/dsa/FireBase/Offline/StreamingOptions.cs b/dsa/FireBase/Offline/StreamingOptions.cs index a420cbb..205118d 100644 --- a/dsa/FireBase/Offline/StreamingOptions.cs +++ b/dsa/FireBase/Offline/StreamingOptions.cs @@ -1,7 +1,5 @@ -namespace Firebase.Database.Offline -{ - public enum StreamingOptions - { +namespace Firebase.Database.Offline { + public enum StreamingOptions { /// /// No realtime streaming. /// diff --git a/dsa/FireBase/Offline/SyncOptions.cs b/dsa/FireBase/Offline/SyncOptions.cs index ca68d0a..3b6e9c8 100644 --- a/dsa/FireBase/Offline/SyncOptions.cs +++ b/dsa/FireBase/Offline/SyncOptions.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// Specifies type of sync requested for given data. /// - public enum SyncOptions - { + public enum SyncOptions { /// /// No sync needed for given data. /// diff --git a/dsa/FireBase/Query/AuthQuery.cs b/dsa/FireBase/Query/AuthQuery.cs index 2cfda3c..a3b06bd 100644 --- a/dsa/FireBase/Query/AuthQuery.cs +++ b/dsa/FireBase/Query/AuthQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents an auth parameter in firebase query, e.g. "?auth=xyz". /// - public class AuthQuery : ParameterQuery - { + public class AuthQuery : ParameterQuery { private readonly Func tokenFactory; /// @@ -16,8 +14,7 @@ namespace Firebase.Database.Query /// The authentication token factory. /// The owner. public AuthQuery(FirebaseQuery parent, Func tokenFactory, FirebaseClient client) : base(parent, - () => client.Options.AsAccessToken ? "access_token" : "auth", client) - { + () => client.Options.AsAccessToken ? "access_token" : "auth", client) { this.tokenFactory = tokenFactory; } @@ -26,8 +23,7 @@ namespace Firebase.Database.Query /// /// The child of this child. /// The . - protected override string BuildUrlParameter(FirebaseQuery child) - { + protected override string BuildUrlParameter(FirebaseQuery child) { return tokenFactory(); } } diff --git a/dsa/FireBase/Query/ChildQuery.cs b/dsa/FireBase/Query/ChildQuery.cs index 014fe09..579bd0a 100644 --- a/dsa/FireBase/Query/ChildQuery.cs +++ b/dsa/FireBase/Query/ChildQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Firebase query which references the child of current node. /// - public class ChildQuery : FirebaseQuery - { + public class ChildQuery : FirebaseQuery { private readonly Func pathFactory; /// @@ -16,8 +14,7 @@ namespace Firebase.Database.Query /// The path to the child node. /// The owner. public ChildQuery(FirebaseQuery parent, Func pathFactory, FirebaseClient client) - : base(parent, client) - { + : base(parent, client) { this.pathFactory = pathFactory; } @@ -27,8 +24,7 @@ namespace Firebase.Database.Query /// The client. /// The path to the child node. public ChildQuery(FirebaseClient client, Func pathFactory) - : this(null, pathFactory, client) - { + : this(null, pathFactory, client) { } /// @@ -36,8 +32,7 @@ namespace Firebase.Database.Query /// /// The child of this child. /// The . - protected override string BuildUrlSegment(FirebaseQuery child) - { + protected override string BuildUrlSegment(FirebaseQuery child) { var s = pathFactory(); if (s != string.Empty && !s.EndsWith("/")) s += '/'; diff --git a/dsa/FireBase/Query/FilterQuery.cs b/dsa/FireBase/Query/FilterQuery.cs index 3434d1d..c0c4dc2 100644 --- a/dsa/FireBase/Query/FilterQuery.cs +++ b/dsa/FireBase/Query/FilterQuery.cs @@ -1,13 +1,11 @@ using System; using System.Globalization; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a firebase filtering query, e.g. "?LimitToLast=10". /// - public class FilterQuery : ParameterQuery - { + public class FilterQuery : ParameterQuery { private readonly Func boolValueFactory; private readonly Func doubleValueFactory; private readonly Func valueFactory; @@ -21,8 +19,7 @@ namespace Firebase.Database.Query /// The owning client. public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) - : base(parent, filterFactory, client) - { + : base(parent, filterFactory, client) { this.valueFactory = valueFactory; } @@ -35,8 +32,7 @@ namespace Firebase.Database.Query /// The owning client. public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) - : base(parent, filterFactory, client) - { + : base(parent, filterFactory, client) { doubleValueFactory = valueFactory; } @@ -49,8 +45,7 @@ namespace Firebase.Database.Query /// The owning client. public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) - : base(parent, filterFactory, client) - { + : base(parent, filterFactory, client) { boolValueFactory = valueFactory; } @@ -59,10 +54,8 @@ namespace Firebase.Database.Query /// /// The child. /// Url parameter part of the resulting path. - protected override string BuildUrlParameter(FirebaseQuery child) - { - if (valueFactory != null) - { + protected override string BuildUrlParameter(FirebaseQuery child) { + if (valueFactory != null) { if (valueFactory() == null) return "null"; return $"\"{valueFactory()}\""; } diff --git a/dsa/FireBase/Query/FirebaseQuery.cs b/dsa/FireBase/Query/FirebaseQuery.cs index 60d0289..91e7afa 100644 --- a/dsa/FireBase/Query/FirebaseQuery.cs +++ b/dsa/FireBase/Query/FirebaseQuery.cs @@ -8,13 +8,11 @@ using Firebase.Database.Http; using Firebase.Database.Streaming; using Newtonsoft.Json; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a firebase query. /// - public abstract class FirebaseQuery : IFirebaseQuery, IDisposable - { + public abstract class FirebaseQuery : IFirebaseQuery, IDisposable { protected readonly FirebaseQuery Parent; private HttpClient client; @@ -25,8 +23,7 @@ namespace Firebase.Database.Query /// /// The parent of this query. /// The owning client. - protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client) - { + protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client) { Client = client; Parent = parent; } @@ -34,8 +31,7 @@ namespace Firebase.Database.Query /// /// Disposes this instance. /// - public void Dispose() - { + public void Dispose() { client?.Dispose(); } @@ -50,16 +46,13 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of elements. /// Collection of holding the entities returned by server. - public async Task>> OnceAsync(TimeSpan? timeout = null) - { + public async Task>> OnceAsync(TimeSpan? timeout = null) { var url = string.Empty; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", string.Empty, string.Empty, HttpStatusCode.OK, ex); } @@ -75,10 +68,8 @@ namespace Firebase.Database.Query /// Optional custom root element of received json items. /// Observable stream of . public IObservable> AsObservable( - EventHandler> exceptionHandler = null, string elementRoot = "") - { - return Observable.Create>(observer => - { + EventHandler> exceptionHandler = null, string elementRoot = "") { + return Observable.Create>(observer => { var sub = new FirebaseSubscription(observer, this, elementRoot, new FirebaseCache()); sub.ExceptionThrown += exceptionHandler; return sub.Run(); @@ -89,11 +80,9 @@ namespace Firebase.Database.Query /// Builds the actual URL of this query. /// /// The . - public async Task BuildUrlAsync() - { + public async Task BuildUrlAsync() { // if token factory is present on the parent then use it to generate auth token - if (Client.Options.AuthTokenAsyncFactory != null) - { + if (Client.Options.AuthTokenAsyncFactory != null) { var token = await Client.Options.AuthTokenAsyncFactory().ConfigureAwait(false); return this.WithAuth(token).BuildUrl(null); } @@ -124,23 +113,19 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of elements. /// Single object of type . - public async Task OnceSingleAsync(TimeSpan? timeout = null) - { + public async Task OnceSingleAsync(TimeSpan? timeout = null) { var responseData = string.Empty; var statusCode = HttpStatusCode.OK; var url = string.Empty; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", string.Empty, responseData, statusCode, ex); } - try - { + try { var response = await GetClient(timeout).GetAsync(url).ConfigureAwait(false); statusCode = response.StatusCode; responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -150,8 +135,7 @@ namespace Firebase.Database.Query return JsonConvert.DeserializeObject(responseData, Client.Options.JsonSerializerSettings); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(url, string.Empty, responseData, statusCode, ex); } } @@ -165,11 +149,9 @@ namespace Firebase.Database.Query /// Type of /// Resulting firebase object with populated key. public async Task> PostAsync(string data, bool generateKeyOffline = true, - TimeSpan? timeout = null) - { + TimeSpan? timeout = null) { // post generates a new key server-side, while put can be used with an already generated local key - if (generateKeyOffline) - { + if (generateKeyOffline) { var key = FirebaseKeyGenerator.Next(); await new ChildQuery(this, () => key, Client).PutAsync(data).ConfigureAwait(false); @@ -190,8 +172,7 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of /// The . - public async Task PatchAsync(string data, TimeSpan? timeout = null) - { + public async Task PatchAsync(string data, TimeSpan? timeout = null) { var c = GetClient(timeout); await this.Silent().SendAsync(c, data, new HttpMethod("PATCH")).ConfigureAwait(false); @@ -204,8 +185,7 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of /// The . - public async Task PutAsync(string data, TimeSpan? timeout = null) - { + public async Task PutAsync(string data, TimeSpan? timeout = null) { var c = GetClient(timeout); await this.Silent().SendAsync(c, data, HttpMethod.Put).ConfigureAwait(false); @@ -216,32 +196,27 @@ namespace Firebase.Database.Query /// /// Optional timeout value. /// The . - public async Task DeleteAsync(TimeSpan? timeout = null) - { + public async Task DeleteAsync(TimeSpan? timeout = null) { var c = GetClient(timeout); var url = string.Empty; var responseData = string.Empty; var statusCode = HttpStatusCode.OK; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", string.Empty, responseData, statusCode, ex); } - try - { + try { var result = await c.DeleteAsync(url).ConfigureAwait(false); statusCode = result.StatusCode; responseData = await result.Content.ReadAsStringAsync().ConfigureAwait(false); result.EnsureSuccessStatusCode(); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(url, string.Empty, responseData, statusCode, ex); } } @@ -253,8 +228,7 @@ namespace Firebase.Database.Query /// The . protected abstract string BuildUrlSegment(FirebaseQuery child); - private string BuildUrl(FirebaseQuery child) - { + private string BuildUrl(FirebaseQuery child) { var url = BuildUrlSegment(child); if (Parent != null) url = Parent.BuildUrl(this) + url; @@ -262,8 +236,7 @@ namespace Firebase.Database.Query return url; } - private HttpClient GetClient(TimeSpan? timeout = null) - { + private HttpClient GetClient(TimeSpan? timeout = null) { if (client == null) client = new HttpClient(); if (!timeout.HasValue) @@ -274,29 +247,24 @@ namespace Firebase.Database.Query return client; } - private async Task SendAsync(HttpClient client, string data, HttpMethod method) - { + private async Task SendAsync(HttpClient client, string data, HttpMethod method) { var responseData = string.Empty; var statusCode = HttpStatusCode.OK; var requestData = data; var url = string.Empty; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", requestData, responseData, statusCode, ex); } - var message = new HttpRequestMessage(method, url) - { + var message = new HttpRequestMessage(method, url) { Content = new StringContent(requestData) }; - try - { + try { var result = await client.SendAsync(message).ConfigureAwait(false); statusCode = result.StatusCode; responseData = await result.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -305,8 +273,7 @@ namespace Firebase.Database.Query return responseData; } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(url, requestData, responseData, statusCode, ex); } } diff --git a/dsa/FireBase/Query/IFirebaseQuery.cs b/dsa/FireBase/Query/IFirebaseQuery.cs index 0da4b15..f31e39e 100644 --- a/dsa/FireBase/Query/IFirebaseQuery.cs +++ b/dsa/FireBase/Query/IFirebaseQuery.cs @@ -3,13 +3,11 @@ using System.Collections.Generic; using System.Threading.Tasks; using Firebase.Database.Streaming; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// The FirebaseQuery interface. /// - public interface IFirebaseQuery - { + public interface IFirebaseQuery { /// /// Gets the owning client of this query. /// diff --git a/dsa/FireBase/Query/OrderQuery.cs b/dsa/FireBase/Query/OrderQuery.cs index 302d1a3..bb5a536 100644 --- a/dsa/FireBase/Query/OrderQuery.cs +++ b/dsa/FireBase/Query/OrderQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a firebase ordering query, e.g. "?OrderBy=Foo". /// - public class OrderQuery : ParameterQuery - { + public class OrderQuery : ParameterQuery { private readonly Func propertyNameFactory; /// @@ -16,8 +14,7 @@ namespace Firebase.Database.Query /// The property name. /// The owning client. public OrderQuery(ChildQuery parent, Func propertyNameFactory, FirebaseClient client) - : base(parent, () => "orderBy", client) - { + : base(parent, () => "orderBy", client) { this.propertyNameFactory = propertyNameFactory; } @@ -26,8 +23,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - protected override string BuildUrlParameter(FirebaseQuery child) - { + protected override string BuildUrlParameter(FirebaseQuery child) { return $"\"{propertyNameFactory()}\""; } } diff --git a/dsa/FireBase/Query/ParameterQuery.cs b/dsa/FireBase/Query/ParameterQuery.cs index 572224c..84adc17 100644 --- a/dsa/FireBase/Query/ParameterQuery.cs +++ b/dsa/FireBase/Query/ParameterQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a parameter in firebase query, e.g. "?data=foo". /// - public abstract class ParameterQuery : FirebaseQuery - { + public abstract class ParameterQuery : FirebaseQuery { private readonly Func parameterFactory; private readonly string separator; @@ -17,8 +15,7 @@ namespace Firebase.Database.Query /// The parameter. /// The owning client. protected ParameterQuery(FirebaseQuery parent, Func parameterFactory, FirebaseClient client) - : base(parent, client) - { + : base(parent, client) { this.parameterFactory = parameterFactory; separator = Parent is ChildQuery ? "?" : "&"; } @@ -28,8 +25,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - protected override string BuildUrlSegment(FirebaseQuery child) - { + protected override string BuildUrlSegment(FirebaseQuery child) { return $"{separator}{parameterFactory()}={BuildUrlParameter(child)}"; } diff --git a/dsa/FireBase/Query/QueryExtensions.cs b/dsa/FireBase/Query/QueryExtensions.cs index df2edfc..b86a877 100644 --- a/dsa/FireBase/Query/QueryExtensions.cs +++ b/dsa/FireBase/Query/QueryExtensions.cs @@ -3,21 +3,18 @@ using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Query extensions providing linq like syntax for firebase server methods. /// - public static class QueryExtensions - { + public static class QueryExtensions { /// /// Adds an auth parameter to the query. /// /// The child. /// The auth token. /// The . - internal static AuthQuery WithAuth(this FirebaseQuery node, string token) - { + internal static AuthQuery WithAuth(this FirebaseQuery node, string token) { return node.WithAuth(() => token); } @@ -26,8 +23,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - internal static SilentQuery Silent(this FirebaseQuery node) - { + internal static SilentQuery Silent(this FirebaseQuery node) { return new SilentQuery(node, node.Client); } @@ -37,8 +33,7 @@ namespace Firebase.Database.Query /// The child. /// The path of sub child. /// The . - public static ChildQuery Child(this ChildQuery node, string path) - { + public static ChildQuery Child(this ChildQuery node, string path) { return node.Child(() => path); } @@ -50,8 +45,7 @@ namespace Firebase.Database.Query /// The child. /// The property name. /// The . - public static OrderQuery OrderBy(this ChildQuery child, string propertyName) - { + public static OrderQuery OrderBy(this ChildQuery child, string propertyName) { return child.OrderBy(() => propertyName); } @@ -62,8 +56,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, string value) - { + public static FilterQuery StartAt(this ParameterQuery child, string value) { return child.StartAt(() => value); } @@ -74,8 +67,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, string value) - { + public static FilterQuery EndAt(this ParameterQuery child, string value) { return child.EndAt(() => value); } @@ -85,8 +77,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, string value) - { + public static FilterQuery EqualTo(this ParameterQuery child, string value) { return child.EqualTo(() => value); } @@ -97,8 +88,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, double value) - { + public static FilterQuery StartAt(this ParameterQuery child, double value) { return child.StartAt(() => value); } @@ -109,8 +99,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, double value) - { + public static FilterQuery EndAt(this ParameterQuery child, double value) { return child.EndAt(() => value); } @@ -120,8 +109,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, double value) - { + public static FilterQuery EqualTo(this ParameterQuery child, double value) { return child.EqualTo(() => value); } @@ -131,8 +119,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, bool value) - { + public static FilterQuery EqualTo(this ParameterQuery child, bool value) { return child.EqualTo(() => value); } @@ -141,8 +128,7 @@ namespace Firebase.Database.Query /// /// Current node. /// The . - public static FilterQuery EqualTo(this ParameterQuery child) - { + public static FilterQuery EqualTo(this ParameterQuery child) { return child.EqualTo(() => null); } @@ -152,8 +138,7 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToFirst(this ParameterQuery child, int count) - { + public static FilterQuery LimitToFirst(this ParameterQuery child, int count) { return child.LimitToFirst(() => count); } @@ -163,24 +148,20 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToLast(this ParameterQuery child, int count) - { + public static FilterQuery LimitToLast(this ParameterQuery child, int count) { return child.LimitToLast(() => count); } - public static Task PutAsync(this FirebaseQuery query, T obj) - { + public static Task PutAsync(this FirebaseQuery query, T obj) { return query.PutAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } - public static Task PatchAsync(this FirebaseQuery query, T obj) - { + public static Task PatchAsync(this FirebaseQuery query, T obj) { return query.PatchAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } public static async Task> PostAsync(this FirebaseQuery query, T obj, - bool generateKeyOffline = true) - { + bool generateKeyOffline = true) { var result = await query.PostAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings), generateKeyOffline); @@ -196,8 +177,7 @@ namespace Firebase.Database.Query /// Current node. /// Object to fan out. /// Locations where to store the item. - public static async Task FanOut(this ChildQuery child, T item, params string[] relativePaths) - { + public static async Task FanOut(this ChildQuery child, T item, params string[] relativePaths) { if (relativePaths == null) throw new ArgumentNullException(nameof(relativePaths)); var fanoutObject = new Dictionary(relativePaths.Length); diff --git a/dsa/FireBase/Query/QueryFactoryExtensions.cs b/dsa/FireBase/Query/QueryFactoryExtensions.cs index 71dae5c..879affc 100644 --- a/dsa/FireBase/Query/QueryFactoryExtensions.cs +++ b/dsa/FireBase/Query/QueryFactoryExtensions.cs @@ -1,20 +1,17 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Query extensions providing linq like syntax for firebase server methods. /// - public static class QueryFactoryExtensions - { + public static class QueryFactoryExtensions { /// /// Adds an auth parameter to the query. /// /// The child. /// The auth token. /// The . - internal static AuthQuery WithAuth(this FirebaseQuery node, Func tokenFactory) - { + internal static AuthQuery WithAuth(this FirebaseQuery node, Func tokenFactory) { return new AuthQuery(node, tokenFactory, node.Client); } @@ -24,8 +21,7 @@ namespace Firebase.Database.Query /// The child. /// The path of sub child. /// The . - public static ChildQuery Child(this ChildQuery node, Func pathFactory) - { + public static ChildQuery Child(this ChildQuery node, Func pathFactory) { return new ChildQuery(node, pathFactory, node.Client); } @@ -37,8 +33,7 @@ namespace Firebase.Database.Query /// The child. /// The property name. /// The . - public static OrderQuery OrderBy(this ChildQuery child, Func propertyNameFactory) - { + public static OrderQuery OrderBy(this ChildQuery child, Func propertyNameFactory) { return new OrderQuery(child, propertyNameFactory, child.Client); } @@ -49,8 +44,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - public static OrderQuery OrderByKey(this ChildQuery child) - { + public static OrderQuery OrderByKey(this ChildQuery child) { return child.OrderBy("$key"); } @@ -61,8 +55,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - public static OrderQuery OrderByValue(this ChildQuery child) - { + public static OrderQuery OrderByValue(this ChildQuery child) { return child.OrderBy("$value"); } @@ -73,8 +66,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - public static OrderQuery OrderByPriority(this ChildQuery child) - { + public static OrderQuery OrderByPriority(this ChildQuery child) { return child.OrderBy("$priority"); } @@ -85,8 +77,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "startAt", valueFactory, child.Client); } @@ -97,8 +88,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "endAt", valueFactory, child.Client); } @@ -109,8 +99,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } @@ -121,8 +110,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "startAt", valueFactory, child.Client); } @@ -133,8 +121,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "endAt", valueFactory, child.Client); } @@ -145,8 +132,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } @@ -157,8 +143,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } @@ -168,8 +153,7 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToFirst(this ParameterQuery child, Func countFactory) - { + public static FilterQuery LimitToFirst(this ParameterQuery child, Func countFactory) { return new FilterQuery(child, () => "limitToFirst", () => countFactory(), child.Client); } @@ -179,8 +163,7 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToLast(this ParameterQuery child, Func countFactory) - { + public static FilterQuery LimitToLast(this ParameterQuery child, Func countFactory) { return new FilterQuery(child, () => "limitToLast", () => countFactory(), child.Client); } } diff --git a/dsa/FireBase/Query/SilentQuery.cs b/dsa/FireBase/Query/SilentQuery.cs index d09d38b..525826a 100644 --- a/dsa/FireBase/Query/SilentQuery.cs +++ b/dsa/FireBase/Query/SilentQuery.cs @@ -1,17 +1,13 @@ -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Appends print=silent to the url. /// - public class SilentQuery : ParameterQuery - { + public class SilentQuery : ParameterQuery { public SilentQuery(FirebaseQuery parent, FirebaseClient client) - : base(parent, () => "print", client) - { + : base(parent, () => "print", client) { } - protected override string BuildUrlParameter(FirebaseQuery child) - { + protected override string BuildUrlParameter(FirebaseQuery child) { return "silent"; } } diff --git a/dsa/FireBase/Streaming/FirebaseCache.cs b/dsa/FireBase/Streaming/FirebaseCache.cs index 66241e0..be6f2c7 100644 --- a/dsa/FireBase/Streaming/FirebaseCache.cs +++ b/dsa/FireBase/Streaming/FirebaseCache.cs @@ -6,19 +6,16 @@ using System.Reflection; using Firebase.Database.Http; using Newtonsoft.Json; -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// The firebase cache. /// /// Type of top-level entities in the cache. - public class FirebaseCache : IEnumerable> - { + public class FirebaseCache : IEnumerable> { private readonly IDictionary dictionary; private readonly bool isDictionaryType; - private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings - { + private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }; @@ -26,16 +23,14 @@ namespace Firebase.Database.Streaming /// Initializes a new instance of the class. /// public FirebaseCache() - : this(new Dictionary()) - { + : this(new Dictionary()) { } /// /// Initializes a new instance of the class and populates it with existing data. /// /// The existing items. - public FirebaseCache(IDictionary existingItems) - { + public FirebaseCache(IDictionary existingItems) { dictionary = existingItems; isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); } @@ -46,8 +41,7 @@ namespace Firebase.Database.Streaming /// The path of incoming data, separated by slash. /// The data in json format as returned by firebase. /// Collection of top-level entities which were affected by the push. - public IEnumerable> PushData(string path, string data, bool removeEmptyEntries = true) - { + public IEnumerable> PushData(string path, string data, bool removeEmptyEntries = true) { object obj = this.dictionary; Action primitiveObjSetter = null; Action objDeleter = null; @@ -57,8 +51,7 @@ namespace Firebase.Database.Streaming // first find where we should insert the data to foreach (var element in pathElements) - if (obj is IDictionary) - { + if (obj is IDictionary) { // if it's a dictionary, then it's just a matter of inserting into it / accessing existing object by key var dictionary = obj as IDictionary; var valueType = obj.GetType().GenericTypeArguments[1]; @@ -66,18 +59,15 @@ namespace Firebase.Database.Streaming primitiveObjSetter = d => dictionary[element] = d; objDeleter = () => dictionary.Remove(element); - if (dictionary.Contains(element)) - { + if (dictionary.Contains(element)) { obj = dictionary[element]; } - else - { + else { dictionary[element] = CreateInstance(valueType); obj = dictionary[element]; } } - else - { + else { // if it's not a dictionary, try to find the property of current object with the matching name var objParent = obj; var property = objParent @@ -89,16 +79,14 @@ namespace Firebase.Database.Streaming objDeleter = () => property.SetValue(objParent, null); primitiveObjSetter = d => property.SetValue(objParent, d); obj = property.GetValue(obj); - if (obj == null) - { + if (obj == null) { obj = CreateInstance(property.PropertyType); property.SetValue(objParent, obj); } } // if data is null (=empty string) delete it - if (string.IsNullOrWhiteSpace(data) || data == "null") - { + if (string.IsNullOrWhiteSpace(data) || data == "null") { var key = pathElements[0]; var target = dictionary[key]; @@ -109,15 +97,13 @@ namespace Firebase.Database.Streaming } // now insert the data - if (obj is IDictionary && !isDictionaryType) - { + if (obj is IDictionary && !isDictionaryType) { // insert data into dictionary and return it as a collection of FirebaseObject var dictionary = obj as IDictionary; var valueType = obj.GetType().GenericTypeArguments[1]; var objectCollection = data.GetObjectCollection(valueType); - foreach (var item in objectCollection) - { + foreach (var item in objectCollection) { dictionary[item.Key] = item.Object; // top level dictionary changed @@ -125,14 +111,12 @@ namespace Firebase.Database.Streaming } // nested dictionary changed - if (pathElements.Any()) - { + if (pathElements.Any()) { this.dictionary[pathElements[0]] = this.dictionary[pathElements[0]]; yield return new FirebaseObject(pathElements[0], this.dictionary[pathElements[0]]); } } - else - { + else { // set the data on a property of the given object var valueType = obj.GetType(); @@ -152,13 +136,11 @@ namespace Firebase.Database.Streaming } } - public bool Contains(string key) - { + public bool Contains(string key) { return dictionary.Keys.Contains(key); } - private object CreateInstance(Type type) - { + private object CreateInstance(Type type) { if (type == typeof(string)) return string.Empty; return Activator.CreateInstance(type); @@ -166,13 +148,11 @@ namespace Firebase.Database.Streaming #region IEnumerable - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return dictionary.Select(p => new FirebaseObject(p.Key, p.Value)).GetEnumerator(); } diff --git a/dsa/FireBase/Streaming/FirebaseEvent.cs b/dsa/FireBase/Streaming/FirebaseEvent.cs index 1761a72..2a1ec6d 100644 --- a/dsa/FireBase/Streaming/FirebaseEvent.cs +++ b/dsa/FireBase/Streaming/FirebaseEvent.cs @@ -1,11 +1,9 @@ -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// Firebase event which hold and the object affected by the event. /// /// Type of object affected by the event. - public class FirebaseEvent : FirebaseObject - { + public class FirebaseEvent : FirebaseObject { /// /// Initializes a new instance of the class. /// @@ -13,8 +11,7 @@ namespace Firebase.Database.Streaming /// The object. /// The event type. public FirebaseEvent(string key, T obj, FirebaseEventType eventType, FirebaseEventSource eventSource) - : base(key, obj) - { + : base(key, obj) { EventType = eventType; EventSource = eventSource; } @@ -29,8 +26,7 @@ namespace Firebase.Database.Streaming /// public FirebaseEventType EventType { get; } - public static FirebaseEvent Empty(FirebaseEventSource source) - { + public static FirebaseEvent Empty(FirebaseEventSource source) { return new FirebaseEvent(string.Empty, default(T), FirebaseEventType.InsertOrUpdate, source); } } diff --git a/dsa/FireBase/Streaming/FirebaseEventSource.cs b/dsa/FireBase/Streaming/FirebaseEventSource.cs index b1385ca..9c14f83 100644 --- a/dsa/FireBase/Streaming/FirebaseEventSource.cs +++ b/dsa/FireBase/Streaming/FirebaseEventSource.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// Specifies the origin of given /// - public enum FirebaseEventSource - { + public enum FirebaseEventSource { /// /// Event comes from an offline source. /// diff --git a/dsa/FireBase/Streaming/FirebaseEventType.cs b/dsa/FireBase/Streaming/FirebaseEventType.cs index 7606331..e6127bf 100644 --- a/dsa/FireBase/Streaming/FirebaseEventType.cs +++ b/dsa/FireBase/Streaming/FirebaseEventType.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// The type of event. /// - public enum FirebaseEventType - { + public enum FirebaseEventType { /// /// Item was inserted or updated. /// diff --git a/dsa/FireBase/Streaming/FirebaseServerEventType.cs b/dsa/FireBase/Streaming/FirebaseServerEventType.cs index 79c816d..9abdb43 100644 --- a/dsa/FireBase/Streaming/FirebaseServerEventType.cs +++ b/dsa/FireBase/Streaming/FirebaseServerEventType.cs @@ -1,7 +1,5 @@ -namespace Firebase.Database.Streaming -{ - internal enum FirebaseServerEventType - { +namespace Firebase.Database.Streaming { + internal enum FirebaseServerEventType { Put, Patch, diff --git a/dsa/FireBase/Streaming/FirebaseSubscription.cs b/dsa/FireBase/Streaming/FirebaseSubscription.cs index fb0f403..6488815 100644 --- a/dsa/FireBase/Streaming/FirebaseSubscription.cs +++ b/dsa/FireBase/Streaming/FirebaseSubscription.cs @@ -8,14 +8,12 @@ using System.Threading.Tasks; using Firebase.Database.Query; using Newtonsoft.Json.Linq; -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// The firebase subscription. /// /// Type of object to be streaming back to the called. - internal class FirebaseSubscription : IDisposable - { + internal class FirebaseSubscription : IDisposable { private static readonly HttpClient http; private readonly FirebaseCache cache; private readonly CancellationTokenSource cancel; @@ -24,10 +22,8 @@ namespace Firebase.Database.Streaming private readonly IObserver> observer; private readonly IFirebaseQuery query; - static FirebaseSubscription() - { - var handler = new HttpClientHandler - { + static FirebaseSubscription() { + var handler = new HttpClientHandler { AllowAutoRedirect = true, MaxAutomaticRedirections = 10, CookieContainer = new CookieContainer() @@ -47,8 +43,7 @@ namespace Firebase.Database.Streaming /// The query. /// The cache. public FirebaseSubscription(IObserver> observer, IFirebaseQuery query, string elementRoot, - FirebaseCache cache) - { + FirebaseCache cache) { this.observer = observer; this.query = query; this.elementRoot = elementRoot; @@ -57,30 +52,25 @@ namespace Firebase.Database.Streaming client = query.Client; } - public void Dispose() - { + public void Dispose() { cancel.Cancel(); } public event EventHandler> ExceptionThrown; - public IDisposable Run() - { + public IDisposable Run() { Task.Run(() => ReceiveThread()); return this; } - private async void ReceiveThread() - { - while (true) - { + private async void ReceiveThread() { + while (true) { var url = string.Empty; var line = string.Empty; var statusCode = HttpStatusCode.OK; - try - { + try { cancel.Token.ThrowIfCancellationRequested(); // initialize network connection @@ -97,10 +87,8 @@ namespace Firebase.Database.Streaming response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) - using (var reader = this.client.Options.SubscriptionStreamReaderFactory(stream)) - { - while (true) - { + using (var reader = this.client.Options.SubscriptionStreamReaderFactory(stream)) { + while (true) { cancel.Token.ThrowIfCancellationRequested(); line = reader.ReadLine()?.Trim(); @@ -110,8 +98,7 @@ namespace Firebase.Database.Streaming var tuple = line.Split(new[] {':'}, 2, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()).ToArray(); - switch (tuple[0].ToLower()) - { + switch (tuple[0].ToLower()) { case "event": serverEvent = ParseServerEvent(serverEvent, tuple[1]); break; @@ -126,18 +113,15 @@ namespace Firebase.Database.Streaming } } } - catch (OperationCanceledException) - { + catch (OperationCanceledException) { break; } - catch (Exception ex) when (statusCode != HttpStatusCode.OK) - { + catch (Exception ex) when (statusCode != HttpStatusCode.OK) { observer.OnError(new FirebaseException(url, string.Empty, line, statusCode, ex)); Dispose(); break; } - catch (Exception ex) - { + catch (Exception ex) { ExceptionThrown?.Invoke(this, new ExceptionEventArgs(new FirebaseException(url, string.Empty, line, statusCode, ex))); @@ -147,10 +131,8 @@ namespace Firebase.Database.Streaming } } - private FirebaseServerEventType ParseServerEvent(FirebaseServerEventType serverEvent, string eventName) - { - switch (eventName) - { + private FirebaseServerEventType ParseServerEvent(FirebaseServerEventType serverEvent, string eventName) { + switch (eventName) { case "put": serverEvent = FirebaseServerEventType.Put; break; @@ -171,10 +153,8 @@ namespace Firebase.Database.Streaming return serverEvent; } - private void ProcessServerData(string url, FirebaseServerEventType serverEvent, string serverData) - { - switch (serverEvent) - { + private void ProcessServerData(string url, FirebaseServerEventType serverEvent, string serverData) { + switch (serverEvent) { case FirebaseServerEventType.Put: case FirebaseServerEventType.Patch: var result = JObject.Parse(serverData); @@ -183,8 +163,7 @@ namespace Firebase.Database.Streaming // If an elementRoot parameter is provided, but it's not in the cache, it was already deleted. So we can return an empty object. if (string.IsNullOrWhiteSpace(elementRoot) || !cache.Contains(elementRoot)) - if (path == "/" && data == string.Empty) - { + if (path == "/" && data == string.Empty) { observer.OnNext(FirebaseEvent.Empty(FirebaseEventSource.OnlineStream)); return; } @@ -209,8 +188,7 @@ namespace Firebase.Database.Streaming } } - private HttpClient GetHttpClient() - { + private HttpClient GetHttpClient() { return http; } } diff --git a/dsa/FireBase/Streaming/NonBlockingStreamReader.cs b/dsa/FireBase/Streaming/NonBlockingStreamReader.cs index 8228e32..805716b 100644 --- a/dsa/FireBase/Streaming/NonBlockingStreamReader.cs +++ b/dsa/FireBase/Streaming/NonBlockingStreamReader.cs @@ -1,8 +1,7 @@ using System.IO; using System.Text; -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// When a regular is used in a UWP app its method /// tends to take a long @@ -11,8 +10,7 @@ namespace Firebase.Database.Streaming /// in your UWP app. Use to inject an instance of this class into your /// . /// - public class NonBlockingStreamReader : TextReader - { + public class NonBlockingStreamReader : TextReader { private const int DefaultBufferSize = 16000; private readonly byte[] buffer; private readonly int bufferSize; @@ -21,8 +19,7 @@ namespace Firebase.Database.Streaming private string cachedData; - public NonBlockingStreamReader(Stream stream, int bufferSize = DefaultBufferSize) - { + public NonBlockingStreamReader(Stream stream, int bufferSize = DefaultBufferSize) { this.stream = stream; this.bufferSize = bufferSize; buffer = new byte[bufferSize]; @@ -30,12 +27,10 @@ namespace Firebase.Database.Streaming cachedData = string.Empty; } - public override string ReadLine() - { + public override string ReadLine() { var currentString = TryGetNewLine(); - while (currentString == null) - { + while (currentString == null) { var read = stream.Read(buffer, 0, bufferSize); var str = Encoding.UTF8.GetString(buffer, 0, read); @@ -46,12 +41,10 @@ namespace Firebase.Database.Streaming return currentString; } - private string TryGetNewLine() - { + private string TryGetNewLine() { var newLine = cachedData.IndexOf('\n'); - if (newLine >= 0) - { + if (newLine >= 0) { var r = cachedData.Substring(0, newLine + 1); cachedData = cachedData.Remove(0, r.Length); return r.Trim(); diff --git a/dsa/NUnitTestProject1/Auxiliary/Calculator/ArgumentTests.cs b/dsa/NUnitTestProject1/Auxiliary/Calculator/ArgumentTests.cs index 3e8dbeb..cf2c1b4 100644 --- a/dsa/NUnitTestProject1/Auxiliary/Calculator/ArgumentTests.cs +++ b/dsa/NUnitTestProject1/Auxiliary/Calculator/ArgumentTests.cs @@ -2,39 +2,29 @@ using DSALib.Auxiliary.Calculator; using Moq; using NUnit.Framework; -namespace NUnitTest.Auxiliary.Calculator -{ +namespace NUnitTest.Auxiliary.Calculator { [TestFixture] - public class ArgumentTests - { - private MockRepository mockRepository; - - - + public class ArgumentTests { [SetUp] - public void SetUp() - { - this.mockRepository = new MockRepository(MockBehavior.Strict); - - + public void SetUp() { + mockRepository = new MockRepository(MockBehavior.Strict); } [TearDown] - public void TearDown() - { - this.mockRepository.VerifyAll(); + public void TearDown() { + mockRepository.VerifyAll(); } - private Argument CreateArgument() - { + private MockRepository mockRepository; + + private Argument CreateArgument() { return new Argument("3"); } [Test] - public void Solve_StateUnderTest_ExpectedBehavior() - { + public void Solve_StateUnderTest_ExpectedBehavior() { // Arrange - var unitUnderTest = this.CreateArgument(); + var unitUnderTest = CreateArgument(); // Act var result = unitUnderTest.Solve(); @@ -44,10 +34,9 @@ namespace NUnitTest.Auxiliary.Calculator } [Test] - public void ToString_StateUnderTest_ExpectedBehavior() - { + public void ToString_StateUnderTest_ExpectedBehavior() { // Arrange - var unitUnderTest = this.CreateArgument(); + var unitUnderTest = CreateArgument(); // Act var result = unitUnderTest.ToString(); @@ -56,4 +45,4 @@ namespace NUnitTest.Auxiliary.Calculator Assert.AreEqual("3", result); } } -} +} \ No newline at end of file diff --git a/dsa/NUnitTestProject1/Auxiliary/Calculator/StringSolverTests.cs b/dsa/NUnitTestProject1/Auxiliary/Calculator/StringSolverTests.cs index 998a78b..877d871 100644 --- a/dsa/NUnitTestProject1/Auxiliary/Calculator/StringSolverTests.cs +++ b/dsa/NUnitTestProject1/Auxiliary/Calculator/StringSolverTests.cs @@ -1,99 +1,86 @@ +using System; using DSALib.Auxiliary.Calculator; using Moq; using NUnit.Framework; -namespace NUnitTest.Auxiliary.Calculator -{ +namespace NUnitTest.Auxiliary.Calculator { [TestFixture] - public class StringSolverTests - { - private MockRepository mockRepository; - - - + public class StringSolverTests { [SetUp] - public void SetUp() - { - this.mockRepository = new MockRepository(MockBehavior.Strict); - - + public void SetUp() { + mockRepository = new MockRepository(MockBehavior.Strict); } [TearDown] - public void TearDown() - { - this.mockRepository.VerifyAll(); + public void TearDown() { + mockRepository.VerifyAll(); } - private StringSolver CreateStringSolver(string input) - { + private MockRepository mockRepository; + + private StringSolver CreateStringSolver(string input) { return new StringSolver(input); } [Test] - public void Solve_StateUnderTest_ExpectedBehavior() - { + public void Solve_braces() { // Arrange - var unitUnderTest = this.CreateStringSolver("1+1"); + var unitUnderTest = CreateStringSolver("1+(1-4)*6+2"); // Act var result = unitUnderTest.Solve(); // Assert - Assert.AreEqual(2,result); + Assert.AreEqual(-15, result); } [Test] - public void Solve_mult() - { + [MaxTime(200)] + public void Solve_braces_timeout() { // Arrange - var unitUnderTest = this.CreateStringSolver("1+1-4*6+2"); + var unitUnderTest = CreateStringSolver("1+(1-(4)*6+2"); // Act - var result = unitUnderTest.Solve(); - - // Assert - Assert.AreEqual(-20, result); + Assert.Throws(() => unitUnderTest.Solve(), "Invalid brace sequence"); } [Test] - public void Solve_braces() - { + public void Solve_mult() { // Arrange - var unitUnderTest = this.CreateStringSolver("1+(1-4)*6+2"); + var unitUnderTest = CreateStringSolver("1+1-4*6+2"); // Act var result = unitUnderTest.Solve(); // Assert - Assert.AreEqual(-15, result); + Assert.AreEqual(-20, result); } [Test] - public void Solve_wrong_braces() - { + public void Solve_StateUnderTest_ExpectedBehavior() { // Arrange - var unitUnderTest = this.CreateStringSolver("1+)(1-4)*6+2"); + var unitUnderTest = CreateStringSolver("1+1"); // Act - Assert.Throws(() =>unitUnderTest.Solve(), "Invalid brace sequence"); + var result = unitUnderTest.Solve(); + + // Assert + Assert.AreEqual(2, result); } - [Test, MaxTime(200)] - public void Solve_braces_timeout() - { + [Test] + public void Solve_wrong_braces() { // Arrange - var unitUnderTest = this.CreateStringSolver("1+(1-(4)*6+2"); + var unitUnderTest = CreateStringSolver("1+)(1-4)*6+2"); // Act - Assert.Throws(() => unitUnderTest.Solve(), "Invalid brace sequence"); + Assert.Throws(() => unitUnderTest.Solve(), "Invalid brace sequence"); } [Test] - public void ToString_StateUnderTest_ExpectedBehavior() - { + public void ToString_StateUnderTest_ExpectedBehavior() { // Arrange - var unitUnderTest = this.CreateStringSolver("3+-4"); + var unitUnderTest = CreateStringSolver("3+-4"); // Act var result = unitUnderTest.ToString(); @@ -102,4 +89,4 @@ namespace NUnitTest.Auxiliary.Calculator Assert.AreEqual("(0+3+-4)", result); } } -} +} \ No newline at end of file diff --git a/dsa/NUnitTestProject1/Auxiliary/DiceTests.cs b/dsa/NUnitTestProject1/Auxiliary/DiceTests.cs index 6b37492..9f9c208 100644 --- a/dsa/NUnitTestProject1/Auxiliary/DiceTests.cs +++ b/dsa/NUnitTestProject1/Auxiliary/DiceTests.cs @@ -1,63 +1,52 @@ +using System; using DSALib.Auxiliary; using Moq; using NUnit.Framework; -using System; -namespace NUnitTest.Auxiliary -{ +namespace NUnitTest.Auxiliary { [TestFixture] - public class DiceTests - { - private MockRepository mockRepository; - - - + public class DiceTests { [SetUp] - public void SetUp() - { - this.mockRepository = new MockRepository(MockBehavior.Strict); - - + public void SetUp() { + mockRepository = new MockRepository(MockBehavior.Strict); } [TearDown] - public void TearDown() - { - this.mockRepository.VerifyAll(); + public void TearDown() { + mockRepository.VerifyAll(); } - private void CreateDice() - {} + private MockRepository mockRepository; + + private void CreateDice() { + } [Test] - public void Roll_StateUnderTest_ExpectedBehavior() - { + public void Roll_StateUnderTest_ExpectedBehavior() { // Arrange - int d = 20; + var d = 20; // Act var result = Dice.Roll(d); // Assert - Assert.True(result > 0 && result < d+1); + Assert.True(result > 0 && result < d + 1); } [Test] - public void Roll_StateUnderTest_ExpectedBehavior1() - { + public void Roll_StateUnderTest_ExpectedBehavior1() { // Arrange - string input = "w"; + var input = "w"; // Act - Assert.Throws( () => Dice.Roll(input)); + Assert.Throws(() => Dice.Roll(input)); } [Test] - public void Roll_zero_dice() - { + public void Roll_zero_dice() { // Arrange - int count = 0; - int d = 2; + var count = 0; + var d = 2; // Act var result = Dice.Roll( @@ -68,4 +57,4 @@ namespace NUnitTest.Auxiliary Assert.AreEqual(0, result); } } -} +} \ No newline at end of file -- cgit v1.2.3-54-g00ecf