summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authornatrixaeria <janng@gmx.de>2019-05-19 17:40:59 +0200
committernatrixaeria <janng@gmx.de>2019-05-19 17:40:59 +0200
commit1509b5ef3d7e9e71d9294e234ec0e39f2d831998 (patch)
tree78300ffff230958101b422a4e6026925b287822f
parentc3bb858bb54dc8c64bbd48054c2c58dc0073f09c (diff)
parentc4d046858e0822b7c2c540ac2368b2c0e88e7a26 (diff)
Merge branch 'scribble' of https://github.com/TrueDoctor/DiscoBot into scribble
-rw-r--r--DSACore/Audio/Sound.cs8
-rw-r--r--DSACore/Auxiliary/Calculator/Argument.cs23
-rw-r--r--DSACore/Auxiliary/Calculator/ISolvable.cs4
-rw-r--r--DSACore/Auxiliary/Calculator/Operator.cs18
-rw-r--r--DSACore/Auxiliary/Calculator/Ops.cs4
-rw-r--r--DSACore/Auxiliary/Calculator/StringSolver.cs109
-rw-r--r--DSACore/Auxiliary/CommandInfo.cs18
-rw-r--r--DSACore/Auxiliary/Dice.cs23
-rw-r--r--DSACore/Auxiliary/Extensions.cs18
-rw-r--r--DSACore/Auxiliary/RandomMisc.cs32
-rw-r--r--DSACore/Auxiliary/SpellCorrect.cs113
-rw-r--r--DSACore/Auxiliary/TalentEnumerableExtension.cs43
-rw-r--r--DSACore/Auxiliary/WeaponImporter.cs61
-rw-r--r--DSACore/Commands/CommandHandler.cs25
-rw-r--r--DSACore/Commands/CommandTypes.cs2
-rw-r--r--DSACore/Commands/FileHandler.cs36
-rw-r--r--DSACore/Commands/Gm.cs11
-rw-r--r--DSACore/Commands/HeldList.cs74
-rw-r--r--DSACore/Commands/Help.cs52
-rw-r--r--DSACore/Commands/LebenUndAstral.cs56
-rw-r--r--DSACore/Commands/List.cs9
-rw-r--r--DSACore/Commands/MiscCommands.cs15
-rw-r--r--DSACore/Commands/NpcCommands.cs17
-rw-r--r--DSACore/Commands/ProbenTest.cs4
-rw-r--r--DSACore/Controllers/CommandsController.cs12
-rw-r--r--DSACore/Controllers/LobbyController.cs13
-rw-r--r--DSACore/Controllers/TokensController.cs19
-rw-r--r--DSACore/DSA_Game/Characters/Character.cs188
-rw-r--r--DSACore/DSA_Game/Characters/NPC.cs82
-rw-r--r--DSACore/DSA_Game/Characters/SaveChar.cs3
-rw-r--r--DSACore/DSA_Game/Dsa.cs27
-rw-r--r--DSACore/DSA_Game/Save/Properties.cs26
-rw-r--r--DSACore/DSA_Game/Save/SaveCommand.cs32
-rw-r--r--DSACore/DSA_Game/Save/Session.cs28
-rw-r--r--DSACore/FireBase/Database.cs90
-rw-r--r--DSACore/Hubs/Login.cs77
-rw-r--r--DSACore/Models/Database/DSA/Advantage.cs2
-rw-r--r--DSACore/Models/Database/DSA/CharSpell.cs2
-rw-r--r--DSACore/Models/Database/DSA/DatabaseChar.cs8
-rw-r--r--DSACore/Models/Database/DSA/Field.cs4
-rw-r--r--DSACore/Models/Database/DSA/GeneralSpell.cs4
-rw-r--r--DSACore/Models/Database/DSA/GroupChar.cs2
-rw-r--r--DSACore/Models/Database/DSA/Inventory.cs2
-rw-r--r--DSACore/Models/Database/DSA/Talent.cs4
-rw-r--r--DSACore/Models/Database/DSA/Weapon.cs20
-rw-r--r--DSACore/Models/Database/DSA/WeaponTalent.cs2
-rw-r--r--DSACore/Models/Database/Groups/DSAGroup.cs2
-rw-r--r--DSACore/Models/Database/Groups/Group.cs5
-rw-r--r--DSACore/Models/Network/Command.cs8
-rw-r--r--DSACore/Models/Network/CommandResponse.cs11
-rw-r--r--DSACore/Models/Network/Group.cs12
-rw-r--r--DSACore/Models/Network/Token.cs10
-rw-r--r--DSACore/Models/Network/User.cs9
-rw-r--r--DSACore/Program.cs19
-rw-r--r--DSACore/Startup.cs19
-rw-r--r--DSALib/Characters/Being.cs6
-rw-r--r--DSALib/Characters/Critter.cs63
-rw-r--r--DSALib/Characters/Entity.cs4
-rw-r--r--DSALib/Characters/ICharacter.cs2
-rw-r--r--DSALib/Characters/ICombatant.cs12
-rw-r--r--DSALib/CritterAttack.cs18
-rw-r--r--DSALib/KampfTalent.cs8
-rw-r--r--DSALib/Talent.cs19
-rw-r--r--DSALib/Vorteil.cs8
-rw-r--r--DSALib/Zauber.cs6
-rw-r--r--DiscoBot/Audio/AudioModule.cs28
-rw-r--r--DiscoBot/Audio/AudioService.cs70
-rw-r--r--DiscoBot/Audio/Sound.cs16
-rw-r--r--DiscoBot/Audio/Soundeffects.cs93
-rw-r--r--DiscoBot/Audio/Voice.cs69
-rw-r--r--DiscoBot/Auxiliary/Calculator/Argument.cs38
-rw-r--r--DiscoBot/Auxiliary/Calculator/ISolvable.cs10
-rw-r--r--DiscoBot/Auxiliary/Calculator/Operator.cs50
-rw-r--r--DiscoBot/Auxiliary/Calculator/Ops.cs13
-rw-r--r--DiscoBot/Auxiliary/Calculator/StringSolver.cs207
-rw-r--r--DiscoBot/Auxiliary/CommandExtension.cs (renamed from DiscoBot/ToRework/CommandExtension.cs)79
-rw-r--r--DiscoBot/Auxiliary/CommandInfo.cs32
-rw-r--r--DiscoBot/Auxiliary/Dice.cs37
-rw-r--r--DiscoBot/Auxiliary/Extensions.cs33
-rw-r--r--DiscoBot/Auxiliary/Permissions.cs32
-rw-r--r--DiscoBot/Auxiliary/RandomMisc.cs44
-rw-r--r--DiscoBot/Auxiliary/SpellCorrect.cs120
-rw-r--r--DiscoBot/Auxiliary/TalentEnumerableExtension.cs102
-rw-r--r--DiscoBot/Commands/CommandTypes.cs13
-rw-r--r--DiscoBot/Commands/FileHandler.cs38
-rw-r--r--DiscoBot/Commands/Gm.cs187
-rw-r--r--DiscoBot/Commands/HeldList.cs191
-rw-r--r--DiscoBot/Commands/Help.cs99
-rw-r--r--DiscoBot/Commands/LebenUndAstral.cs198
-rw-r--r--DiscoBot/Commands/List.cs62
-rw-r--r--DiscoBot/Commands/MiscCommands.cs206
-rw-r--r--DiscoBot/Commands/NpcCommands.cs39
-rw-r--r--DiscoBot/Commands/ProbenTest.cs91
-rw-r--r--DiscoBot/DSA_Game/Characters/Character.cs303
-rw-r--r--DiscoBot/DSA_Game/Characters/NPC.cs112
-rw-r--r--DiscoBot/DSA_Game/Characters/SaveChar.cs45
-rw-r--r--DiscoBot/DSA_Game/Dsa.cs72
-rw-r--r--DiscoBot/DSA_Game/Save/Properties.cs88
-rw-r--r--DiscoBot/DSA_Game/Save/SaveCommand.cs82
-rw-r--r--DiscoBot/DSA_Game/Save/Session.cs60
-rw-r--r--DiscoBot/DiscoBot.csproj31
-rw-r--r--DiscoBot/Program.cs100
-rw-r--r--DiscoBot/Properties/AssemblyInfo.cs3
-rw-r--r--DiscoBot/ToRework/Permissions.cs43
-rw-r--r--FireBase/ExceptionEventArgs.cs14
-rw-r--r--FireBase/Extensions/ObservableExtensions.cs43
-rw-r--r--FireBase/Extensions/TaskExtensions.cs12
-rw-r--r--FireBase/FirebaseClient.cs48
-rw-r--r--FireBase/FirebaseException.cs60
-rw-r--r--FireBase/FirebaseKeyGenerator.cs49
-rw-r--r--FireBase/FirebaseObject.cs28
-rw-r--r--FireBase/FirebaseOptions.cs78
-rw-r--r--FireBase/Http/HttpClientExtensions.cs55
-rw-r--r--FireBase/Http/PostResult.cs12
-rw-r--r--FireBase/ObservableExtensions.cs24
-rw-r--r--FireBase/Offline/ConcurrentOfflineDatabase.cs196
-rw-r--r--FireBase/Offline/DatabaseExtensions.cs186
-rw-r--r--FireBase/Offline/ISetHandler.cs11
-rw-r--r--FireBase/Offline/InitialPullStrategy.cs14
-rw-r--r--FireBase/Offline/Internals/MemberAccessVisitor.cs35
-rw-r--r--FireBase/Offline/OfflineCacheAdapter.cs115
-rw-r--r--FireBase/Offline/OfflineDatabase.cs195
-rw-r--r--FireBase/Offline/OfflineEntry.cs103
-rw-r--r--FireBase/Offline/RealtimeDatabase.cs422
-rw-r--r--FireBase/Offline/SetHandler.cs15
-rw-r--r--FireBase/Offline/StreamingOptions.cs12
-rw-r--r--FireBase/Offline/SyncOptions.cs12
-rw-r--r--FireBase/Query/AuthQuery.cs21
-rw-r--r--FireBase/Query/ChildQuery.cs28
-rw-r--r--FireBase/Query/FilterQuery.cs66
-rw-r--r--FireBase/Query/FirebaseQuery.cs218
-rw-r--r--FireBase/Query/IFirebaseQuery.cs39
-rw-r--r--FireBase/Query/OrderQuery.cs16
-rw-r--r--FireBase/Query/ParameterQuery.cs24
-rw-r--r--FireBase/Query/QueryExtensions.cs93
-rw-r--r--FireBase/Query/QueryFactoryExtensions.cs91
-rw-r--r--FireBase/Query/SilentQuery.cs6
-rw-r--r--FireBase/Streaming/FirebaseCache.cs93
-rw-r--r--FireBase/Streaming/FirebaseEvent.cs27
-rw-r--r--FireBase/Streaming/FirebaseEventSource.cs16
-rw-r--r--FireBase/Streaming/FirebaseEventType.cs8
-rw-r--r--FireBase/Streaming/FirebaseServerEventType.cs2
-rw-r--r--FireBase/Streaming/FirebaseSubscription.cs112
-rw-r--r--FireBase/Streaming/NonBlockingStreamReader.cs43
-rw-r--r--ZooBOTanica/CritCreate.cs95
-rw-r--r--ZooBOTanica/Program.cs11
-rw-r--r--ZooBOTanica/Properties/AssemblyInfo.cs3
147 files changed, 2363 insertions, 5187 deletions
diff --git a/DSACore/Audio/Sound.cs b/DSACore/Audio/Sound.cs
index d259850..aee3060 100644
--- a/DSACore/Audio/Sound.cs
+++ b/DSACore/Audio/Sound.cs
@@ -4,9 +4,9 @@
{
public Sound(string name, string url, int volume)
{
- this.Name = name;
- this.Url = url;
- this.Volume = volume;
+ Name = name;
+ Url = url;
+ Volume = volume;
}
public string Name { get; }
@@ -15,4 +15,4 @@
public int Volume { get; }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/Calculator/Argument.cs b/DSACore/Auxiliary/Calculator/Argument.cs
index 52f33a9..5ed9ee3 100644
--- a/DSACore/Auxiliary/Calculator/Argument.cs
+++ b/DSACore/Auxiliary/Calculator/Argument.cs
@@ -1,9 +1,9 @@
-namespace DSACore.Auxiliary.Calculator
+using System;
+
+namespace DSACore.Auxiliary.Calculator
{
- using System;
-
/// <summary>
- /// Provides an ISolvable class to save numbers. The class handles Argument checking and conversion from string to int.
+ /// Provides an ISolvable class to save numbers. The class handles Argument checking and conversion from string to int.
/// </summary>
public class Argument : ISolvable
{
@@ -12,27 +12,24 @@
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. ", nameof(value));
- }
+ if (string.IsNullOrEmpty(value))
+ throw new ArgumentException("Argument kann nicht mit einem leeren string instanziert werden. ",
+ nameof(value));
- if (!int.TryParse(value, out int result))
- {
+ if (!int.TryParse(value, out var result))
throw new ArgumentException($"Kann {value} nicht in Integer konvertieren");
- }
this.value = result;
}
public int Solve()
{
- return this.value;
+ return value;
}
public override string ToString()
{
- return this.value.ToString();
+ return value.ToString();
}
}
} \ No newline at end of file
diff --git a/DSACore/Auxiliary/Calculator/ISolvable.cs b/DSACore/Auxiliary/Calculator/ISolvable.cs
index 1f571d0..7be4d19 100644
--- a/DSACore/Auxiliary/Calculator/ISolvable.cs
+++ b/DSACore/Auxiliary/Calculator/ISolvable.cs
@@ -1,10 +1,10 @@
namespace DSACore.Auxiliary.Calculator
{
/// <summary>
- /// Object has to be able to return an integer as it's value
+ /// Object has to be able to return an integer as it's value
/// </summary>
public interface ISolvable
{
int Solve();
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/Calculator/Operator.cs b/DSACore/Auxiliary/Calculator/Operator.cs
index 440e21e..31b2a9b 100644
--- a/DSACore/Auxiliary/Calculator/Operator.cs
+++ b/DSACore/Auxiliary/Calculator/Operator.cs
@@ -4,7 +4,7 @@ using DSACorev.Auxiliary.Calculator;
namespace DSACore.Auxiliary.Calculator
{
/// <summary>
- /// The Operator Class represents a binary operator with tow Arguments and an Operation type
+ /// The Operator Class represents a binary operator with tow Arguments and an Operation type
/// </summary>
public class Operator : ISolvable
{
@@ -14,7 +14,7 @@ namespace DSACore.Auxiliary.Calculator
{
this.arg1 = arg1;
this.arg2 = arg2;
- this.OperatorType = operatorType;
+ OperatorType = operatorType;
}
public Ops OperatorType { get; set; }
@@ -22,19 +22,19 @@ namespace DSACore.Auxiliary.Calculator
public int Solve()
{
int result;
- switch (this.OperatorType)
+ switch (OperatorType)
{
case Ops.Dice:
- result = Dice.Roll(this.arg1.Solve(), this.arg2.Solve());
+ result = Dice.Roll(arg1.Solve(), arg2.Solve());
break;
case Ops.Multiply:
- result = this.arg1.Solve() * this.arg2.Solve();
+ result = arg1.Solve() * arg2.Solve();
break;
case Ops.Add:
- result = this.arg1.Solve() + this.arg2.Solve();
+ result = arg1.Solve() + arg2.Solve();
break;
case Ops.Subtract:
- result = this.arg1.Solve() - this.arg2.Solve();
+ result = arg1.Solve() - arg2.Solve();
break;
default:
throw new ArgumentOutOfRangeException();
@@ -45,7 +45,7 @@ namespace DSACore.Auxiliary.Calculator
public override string ToString()
{
- return $"({this.arg1} {this.OperatorType} {this.arg2})";
+ return $"({arg1} {OperatorType} {arg2})";
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/Calculator/Ops.cs b/DSACore/Auxiliary/Calculator/Ops.cs
index 702558d..a5c9a2d 100644
--- a/DSACore/Auxiliary/Calculator/Ops.cs
+++ b/DSACore/Auxiliary/Calculator/Ops.cs
@@ -1,7 +1,7 @@
namespace DSACorev.Auxiliary.Calculator
{
/// <summary>
- /// The Different Operations, witch can be performed in execution-order
+ /// The Different Operations, witch can be performed in execution-order
/// </summary>
public enum Ops
{
@@ -10,4 +10,4 @@
Subtract,
Add
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/Calculator/StringSolver.cs b/DSACore/Auxiliary/Calculator/StringSolver.cs
index 2eff5b4..b2a7d83 100644
--- a/DSACore/Auxiliary/Calculator/StringSolver.cs
+++ b/DSACore/Auxiliary/Calculator/StringSolver.cs
@@ -5,49 +5,47 @@ using DSACorev.Auxiliary.Calculator;
namespace DSACore.Auxiliary.Calculator
{
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
/// <summary>
- /// The StringSolver divides the calculation string into operations and SubStringSolvers if the string contains parentheses
+ /// The StringSolver divides the calculation string into operations and SubStringSolvers if the string contains
+ /// parentheses
/// </summary>
public class StringSolver : ISolvable
{
- private readonly string input;
private readonly List<object> arguments = new List<object>();
+ private readonly string input;
public StringSolver(string input)
{
this.input = input;
}
- public override string ToString()
- {
- return "(0+" + this.input.Replace(" ", string.Empty).ToLower() + ")";
- }
-
public int Solve()
{
- string workInput = "0+" + this.input.Replace(" ", string.Empty).ToLower();
+ var workInput = "0+" + input.Replace(" ", string.Empty).ToLower();
workInput = ExpandParentheses(workInput);
-
+
// Create a List of the different parts of the calculation, e.g.:{"0", "+", "(5+6)", "d", "3"}.
- this.AtomizeOperations(workInput);
+ AtomizeOperations(workInput);
// traverse the List in order of Operation to Create the binary operation tree .
- this.NestOperations();
+ NestOperations();
// the List now contains only the top operation node, witch can be solved recursively,
- return ((ISolvable)this.arguments.First()).Solve();
+ return ((ISolvable) arguments.First()).Solve();
}
- private static string GetInner(ref string input) // extract the inner bracket an remove the section from the input string
+ public override string ToString()
{
- int depth = 0;
+ return "(0+" + input.Replace(" ", string.Empty).ToLower() + ")";
+ }
+
+ private static string
+ 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++)
{
- char c = input[index];
+ var c = input[index];
switch (c)
{
case '(':
@@ -92,21 +90,13 @@ namespace DSACore.Auxiliary.Calculator
private static string ExpandParentheses(string input) // insert * between Parentheses and digits
{
- for (int i = 0; i < input.Length - 1; i++)
- {
+ for (var i = 0; i < input.Length - 1; i++)
if (input[i + 1] == '(' && char.IsNumber(input[i]))
- {
input = input.Insert(i + 1, "*");
- }
- }
- for (int i = 1; i < input.Length; i++)
- {
+ for (var i = 1; i < input.Length; i++)
if (input[i - 1] == ')' && char.IsNumber(input[i]))
- {
input = input.Insert(i, "*");
- }
- }
return input;
}
@@ -115,16 +105,14 @@ namespace DSACore.Auxiliary.Calculator
{
for (var index = 0; index < workInput.Length; index++)
{
- char c = workInput[index];
+ var c = workInput[index];
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
- this.arguments.Add(new Argument(workInput.Substring(0, index + 1)));
- }
+ arguments.Add(new Argument(workInput.Substring(0, index + 1)));
continue;
}
@@ -132,18 +120,15 @@ namespace DSACore.Auxiliary.Calculator
switch (c)
{
case ')':
- throw new ArgumentException($"Unmögliche Anordnung von Klammern");
+ throw new ArgumentException("Unmögliche Anordnung von Klammern");
case '(':
- this.arguments.Add(new StringSolver(GetInner(ref workInput)));
+ arguments.Add(new StringSolver(GetInner(ref workInput)));
index = -1;
break;
default:
- if (index > 0)
- {
- this.arguments.Add(new Argument(workInput.Substring(0, index)));
- }
+ if (index > 0) arguments.Add(new Argument(workInput.Substring(0, index)));
- this.arguments.Add(GetOps(c));
+ arguments.Add(GetOps(c));
workInput = workInput.Remove(0, index + 1);
index = -1;
break;
@@ -154,58 +139,44 @@ namespace DSACore.Auxiliary.Calculator
private void NestOperations()
{
foreach (Ops currentOp in Enum.GetValues(typeof(Ops)))
- {
// cycle through operators in operational order
- for (var index = 0; index < this.arguments.Count; index++)
+ for (var index = 0; index < arguments.Count; index++)
{
- var arg = this.arguments[index];
+ var arg = arguments[index];
- if (arg.GetType() != typeof(Ops))
- {
- continue;
- }
+ if (arg.GetType() != typeof(Ops)) continue;
// arg is of type Ops
- var op = (Ops)arg;
+ var op = (Ops) arg;
- if (op != currentOp)
- {
- continue;
- }
+ if (op != currentOp) continue;
// arg describes the current operation
- this.HandleSpecialFormatting(ref index, op); // Deal with special needs...
+ HandleSpecialFormatting(ref index, op); // Deal with special needs...
// replace the previous current and next Element in the List with one Operation object
- var temp = new Operator((ISolvable)this.arguments[index - 1], (ISolvable)this.arguments[index + 1], op);
- this.arguments[index - 1] = temp;
- this.arguments.RemoveRange(index, 2);
+ var temp = new Operator((ISolvable) arguments[index - 1], (ISolvable) arguments[index + 1], op);
+ arguments[index - 1] = temp;
+ arguments.RemoveRange(index, 2);
index--;
}
- }
}
private void HandleSpecialFormatting(ref int index, Ops op)
{
- var arg1 = this.arguments[index - 1];
+ var arg1 = arguments[index - 1];
if (arg1.GetType() == typeof(Ops))
{
- if (op == Ops.Dice)
- {
- this.arguments.Insert(index++, new Argument("1")); // w6 -> 1w6
- }
+ if (op == Ops.Dice) arguments.Insert(index++, new Argument("1")); // w6 -> 1w6
- if (op == Ops.Subtract)
- {
- this.arguments.Insert(index++, new Argument("0")); // +-3 -> +0-3
- }
+ if (op == Ops.Subtract) arguments.Insert(index++, new Argument("0")); // +-3 -> +0-3
}
- var arg2 = this.arguments[index + 1]; // 3+-5 -> 3+(0-5)
+ var arg2 = arguments[index + 1]; // 3+-5 -> 3+(0-5)
if (arg2.GetType() == typeof(Ops))
{
- this.arguments[index + 1] = new Operator(new Argument("0"), (ISolvable)this.arguments[index + 2], (Ops)arg2);
- this.arguments.RemoveAt(index + 2);
+ arguments[index + 1] = new Operator(new Argument("0"), (ISolvable) arguments[index + 2], (Ops) arg2);
+ arguments.RemoveAt(index + 2);
}
}
}
diff --git a/DSACore/Auxiliary/CommandInfo.cs b/DSACore/Auxiliary/CommandInfo.cs
index a83e30a..1472587 100644
--- a/DSACore/Auxiliary/CommandInfo.cs
+++ b/DSACore/Auxiliary/CommandInfo.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Linq;
namespace DSACore.Auxiliary
{
@@ -10,10 +6,10 @@ namespace DSACore.Auxiliary
{
public CommandInfo(string name, string brief, string[] description, string scope)
{
- this.Name = name;
- this.Scope = scope;
- this.Brief = brief;
- this.Description = description;
+ Name = name;
+ Scope = scope;
+ Brief = brief;
+ Description = description;
}
public string Name { get; }
@@ -26,7 +22,7 @@ namespace DSACore.Auxiliary
public string GetDescription()
{
- return this.Description.Aggregate((s, c) => s + c);
+ return Description.Aggregate((s, c) => s + c);
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/Dice.cs b/DSACore/Auxiliary/Dice.cs
index 2df8aa7..3dd6562 100644
--- a/DSACore/Auxiliary/Dice.cs
+++ b/DSACore/Auxiliary/Dice.cs
@@ -5,7 +5,7 @@ namespace DSACore.Auxiliary
{
public static class Dice // roll it!
{
- private static readonly System.Random Rnd = new System.Random();
+ private static readonly Random Rnd = new Random();
public static int Roll(int d = 20)
{
@@ -14,29 +14,24 @@ namespace DSACore.Auxiliary
public static int Roll(string input)
{
- var strings = input.ToLower().Split(new[] { 'w', 'd' }, 2, StringSplitOptions.RemoveEmptyEntries).ToList();
- int count = Convert.ToInt32(strings[0]);
- int d = Convert.ToInt32(strings[0]);
+ var strings = input.ToLower().Split(new[] {'w', 'd'}, 2, StringSplitOptions.RemoveEmptyEntries).ToList();
+ var count = Convert.ToInt32(strings[0]);
+ var d = Convert.ToInt32(strings[0]);
if (strings.Count != 2)
- {
throw new ArgumentException($"{input}: erfüllt nicht die Formatvogaben( Anzahl d Augenzahl)");
- }
return Roll(count, d);
}
public static int Roll(int count, int d)
{
- if (d <= 0)
- {
- return 0;
- }
+ if (d <= 0) return 0;
- int sum = 0;
- for (int i = 0; i < Math.Abs(count); i++)
+ var sum = 0;
+ for (var i = 0; i < Math.Abs(count); i++)
{
- var roll = Dice.Roll(d);
+ var roll = Roll(d);
sum += roll;
}
@@ -45,4 +40,4 @@ namespace DSACore.Auxiliary
return sum;
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/Extensions.cs b/DSACore/Auxiliary/Extensions.cs
index 8ef6298..f8e9d8e 100644
--- a/DSACore/Auxiliary/Extensions.cs
+++ b/DSACore/Auxiliary/Extensions.cs
@@ -6,14 +6,10 @@
//If the original string is already longer, it is returner unmodified.
public static string AddSpaces(this string str, int length)
{
- string temp = str;
- for(int i = str.Length; i < length; i++)
- {
- temp += " ";
- }
+ var temp = str;
+ for (var i = str.Length; i < length; i++) temp += " ";
return temp;
}
-
//This mehod extends string.
@@ -21,13 +17,9 @@
//If the original string is already longer, it is returner unmodified.
public static string AddSpacesAtHead(this string str, int length)
{
- string temp = "";
- for (int i = str.Length; i < length; i++)
- {
- temp += " ";
- }
+ var temp = "";
+ for (var i = str.Length; i < length; i++) temp += " ";
return temp + str;
}
}
-
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/RandomMisc.cs b/DSACore/Auxiliary/RandomMisc.cs
index 1295f02..72c2234 100644
--- a/DSACore/Auxiliary/RandomMisc.cs
+++ b/DSACore/Auxiliary/RandomMisc.cs
@@ -13,40 +13,40 @@ namespace DSACore.Auxiliary
{
var output = new StringBuilder();
var strings = input.Split('w', 'd').ToList();
- int count = Convert.ToInt32(strings[0]);
+ var count = Convert.ToInt32(strings[0]);
strings = strings[1].Split(' ').ToList();
- int d = Convert.ToInt32(strings[0]);
+ var d = Convert.ToInt32(strings[0]);
if (strings.Count > 0)
{
}
- int sum = 0;
- for (int i = 0; i < count; i++)
+ var sum = 0;
+ for (var i = 0; i < count; i++)
{
var roll = Dice.Roll(d);
sum += roll;
output.Append("[" + roll + "] ");
}
-
- if (strings.Count > 1)
- {
- sum += Convert.ToInt32(strings[1]);
- output.Append("sum: " + sum);
- }
+
+ if (strings.Count > 1)
+ {
+ sum += Convert.ToInt32(strings[1]);
+ output.Append("sum: " + sum);
+ }
return output.ToString();
}
public static double Random(double stdDev = 1, double mean = 0)
{
- double u1 = Rand.NextDouble(); // uniform(0,1) random doubles
- double u2 = Rand.NextDouble();
- double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
- Math.Sin(2.0 * Math.PI * u2); // random normal(0,1)
- double randNormal =
+ var u1 = Rand.NextDouble(); // uniform(0,1) random doubles
+ var u2 = Rand.NextDouble();
+ var randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
+ Math.Sin(2.0 * Math.PI * u2); // random normal(0,1)
+ var randNormal =
mean + stdDev * randStdNormal; // random normal(mean,stdDev^2)
return randNormal;
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/SpellCorrect.cs b/DSACore/Auxiliary/SpellCorrect.cs
index c9603f6..77d1cf3 100644
--- a/DSACore/Auxiliary/SpellCorrect.cs
+++ b/DSACore/Auxiliary/SpellCorrect.cs
@@ -1,9 +1,9 @@
-namespace DSACore.Auxiliary
-{
- using System;
- using System.Diagnostics;
- using System.Linq;
+using System;
+using System.Diagnostics;
+using System.Linq;
+namespace DSACore.Auxiliary
+{
public class SpellCorrect : StringComparer
{
public const int ErrorThreshold = 94100;
@@ -15,44 +15,25 @@
public static int CompareEasy(string x, string y)
{
- if (string.IsNullOrEmpty(x))
- {
- throw new ArgumentException("message", nameof(x));
- }
+ if (string.IsNullOrEmpty(x)) throw new ArgumentException("message", nameof(x));
- if (string.IsNullOrEmpty(y))
- {
- throw new ArgumentException("message", nameof(y));
- }
+ if (string.IsNullOrEmpty(y)) throw new ArgumentException("message", nameof(y));
- if (x.Equals(y))
- {
- return 0;
- }
+ if (x.Equals(y)) return 0;
x = x.ToLower();
y = y.ToLower();
- if (x.Equals(y))
- {
- return 1;
- }
+ if (x.Equals(y)) return 1;
var subs = y.Split(' ', '/');
- int score = subs.Count();
- foreach (string s in subs)
- {
+ var score = subs.Count();
+ foreach (var s in subs)
if (s.Equals(x))
- {
score--;
- }
- }
- if (score < subs.Count())
- {
- return score + 1;
- }
+ if (score < subs.Count()) return score + 1;
- return 100000 - (int)(CompareExact(x, y) * 1000.0);
+ return 100000 - (int) (CompareExact(x, y) * 1000.0);
/*if (y.Contains(x))
return 6;*/
}
@@ -70,7 +51,6 @@
public static double CompareExact(string s, string q)
{
-
s = s.ToLower();
q = q.ToLower();
@@ -81,67 +61,46 @@
double decay;
- double[,] matrix = new double[s.Length + 1, q.Length + 1];
- double max = 0.0;
+ var matrix = new double[s.Length + 1, q.Length + 1];
+ var max = 0.0;
matrix[0, 0] = 0.0;
-
+
for (i = 1; i < s.Length; i++)
- {
- // matrix[i, 0] = 0.0;
+ // matrix[i, 0] = 0.0;
matrix[i, 0] = i * Gap;
- }
- for (i = 1; i < q.Length; i++)
- {
- matrix[0, i] = 0.0;
- }
+ for (i = 1; i < q.Length; i++) matrix[0, i] = 0.0;
for (i = 1; i <= s.Length; i++)
+ for (j = 1; j <= q.Length; j++)
{
- for (j = 1; j <= q.Length; j++)
- {
- decay = j / (double)(s.Length * 1000);
- double add = s[i - 1] == q[j - 1] ? (Match - decay) : Mismatch;
- double score = matrix[i - 1, j - 1] + add;
+ decay = j / (double) (s.Length * 1000);
+ 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 (i > 1 && j > 1)
+ if (s[i - 1] == q[j - 2] && s[i - 2] == q[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;
- }
- }
+ add = 3 / 2.0 * Match - decay;
+ if (score < matrix[i - 2, j - 2] + add) score = matrix[i - 2, j - 2] + add;
}
-
- // if (score < 0)
- // {
- // score = 0;
- // }
- if (max < score && i == s.Length)
- {
- max = score;
- }
+ // if (score < 0)
+ // {
+ // score = 0;
+ // }
+
+ if (max < score && i == s.Length) max = score;
- matrix[i, j] = score;
- }
+ matrix[i, j] = score;
}
return max;
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/TalentEnumerableExtension.cs b/DSACore/Auxiliary/TalentEnumerableExtension.cs
index a4ace2f..d83114c 100644
--- a/DSACore/Auxiliary/TalentEnumerableExtension.cs
+++ b/DSACore/Auxiliary/TalentEnumerableExtension.cs
@@ -1,7 +1,7 @@
-using DSACore.DSA_Game.Characters;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.Linq;
using System.Text;
+using DSACore.DSA_Game.Characters;
using DSALib;
namespace DSACore.Auxiliary
@@ -15,12 +15,10 @@ namespace DSACore.Auxiliary
var tTalent = List.OrderBy(x => sc.Compare(talent, x.Name)).First();
if (sc.Compare(talent, tTalent.Name) > SpellCorrect.ErrorThreshold)
- {
return $"{c.Name} kann nicht {talent}...";
- }
var props = tTalent.GetEigenschaften(); // get the required properties
- int tap = tTalent.Value; // get taw
+ var tap = tTalent.Value; // get taw
var werte = props.Select(p => c.Eigenschaften[c.PropTable[p]]).ToList();
output.AppendFormat(
@@ -34,51 +32,42 @@ namespace DSACore.Auxiliary
output.Append(" ");
tap -= erschwernis;
- int gesamtErschwernis = tap;
+ var gesamtErschwernis = tap;
if (gesamtErschwernis < 0)
{
tap = 0;
- for (int i = 0; i <= 2; i++)
+ for (var i = 0; i <= 2; i++)
{
// foreach property, dice and tap
- int temp = Dice.Roll();
- int eigenschaft = c.Eigenschaften[c.PropTable[props[i]]];
+ var temp = Dice.Roll();
+ var eigenschaft = c.Eigenschaften[c.PropTable[props[i]]];
- if (eigenschaft + gesamtErschwernis < temp)
- {
- tap -= temp - (eigenschaft + gesamtErschwernis);
- }
+ if (eigenschaft + gesamtErschwernis < temp) tap -= temp - (eigenschaft + gesamtErschwernis);
output.Append($"[{temp}]"); // add to string
}
- if (tap >= 0)
- {
- tap = 1;
- }
+ if (tap >= 0) tap = 1;
}
else
{
- for (int i = 0; i <= 2; i++)
+ for (var i = 0; i <= 2; i++)
{
// foreach property, dice and tap
- int temp = Dice.Roll();
- int eigenschaft = c.Eigenschaften[c.PropTable[props[i]]];
+ var temp = Dice.Roll();
+ var eigenschaft = c.Eigenschaften[c.PropTable[props[i]]];
- if (eigenschaft < temp)
- {
- tap -= temp - eigenschaft;
- }
+ if (eigenschaft < temp) tap -= temp - eigenschaft;
output.Append($"[{temp}]"); // add to string
}
}
- tap = (tap == 0) ? 1 : tap;
-
+ tap = tap == 0 ? 1 : tap;
+
output.AppendFormat(" tap: {0,2}", tap);
return output.ToString(); // return output
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Auxiliary/WeaponImporter.cs b/DSACore/Auxiliary/WeaponImporter.cs
index 635d477..3375236 100644
--- a/DSACore/Auxiliary/WeaponImporter.cs
+++ b/DSACore/Auxiliary/WeaponImporter.cs
@@ -1,5 +1,4 @@
-using DSACore.Models.Database;
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
@@ -7,26 +6,25 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DSACore.FireBase;
using DSACore.Models.Database.DSA;
-using Group = System.Text.RegularExpressions.Group;
namespace DSACore.Auxiliary
{
public class WeaponImporter
{
- private List<MeleeWeapon> Weapons = new List<MeleeWeapon>();
- private List<RangedWeapon> Range = new List<RangedWeapon>();
+ private readonly List<RangedWeapon> Range = new List<RangedWeapon>();
+ private readonly List<MeleeWeapon> Weapons = new List<MeleeWeapon>();
public async Task DownloadWeapons()
{
var client = new HttpClient();
-
- for (int 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);
+ var responseString =
+ await client.GetStringAsync("http://diarium.eu/dsa4-forge/ajax/categoryChanged/" + i);
- Regex talentRegex = new Regex(@"(?<=<option value="")([0-9]*)("">)(.*?)(?=<)");
+ var talentRegex = new Regex(@"(?<=<option value="")([0-9]*)("">)(.*?)(?=<)");
//Regex idsRegex = new Regex(@"(?<=<option value=\"")([0-9]*)");
@@ -37,25 +35,25 @@ namespace DSACore.Auxiliary
var ids = new List<int>();
foreach (var matchGroup in talentMatch.ToList())
- {
if (matchGroup.Success)
{
lines.Add(matchGroup.Groups[3].Value);
ids.Add(int.Parse(matchGroup.Groups[1].Value));
}
- }
-
- for (int 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 + "/" + ids[j] + "/0/0/0/0/0/10/0/0/0");
+ var values = await client.GetStringAsync("http://diarium.eu/dsa4-forge/ajax/calculate/" + i + "/" +
+ ids[j] + "/0/0/0/0/0/10/0/0/0");
values = Regex.Unescape(values.Replace(@"\t", ""));
// ... Use named group in regular expression.
- Regex expression = new Regex(@"(((?<=(<td>))|(?<=(<td style=\""padding:2px\"">))).*?(?=<\/td>))|((?<=<span style=\""font-weight:bold;text-decoration:underline;\"">).*?(?=<\/span>))");
+ var expression =
+ new Regex(
+ @"(((?<=(<td>))|(?<=(<td style=\""padding:2px\"">))).*?(?=<\/td>))|((?<=<span style=\""font-weight:bold;text-decoration:underline;\"">).*?(?=<\/span>))");
// ... See if we matched.
var matches = expression.Matches(values).Select(x => x.ToString()).ToList();
@@ -64,7 +62,6 @@ namespace DSACore.Auxiliary
await AddMelee(i, talent, matches);
Console.Write(j + ",");
//await Task.Delay(TimeSpan.FromSeconds(5));
-
}
Console.WriteLine($"{i}: {ids.Count} => {Weapons.Count}");
@@ -76,17 +73,17 @@ namespace DSACore.Auxiliary
private async Task AddMelee(int i, string talent, List<string> matches)
{
- string name = talent.Replace(' ', '_').Replace(".", "");
+ var name = talent.Replace(' ', '_').Replace(".", "");
if (!matches[1].Equals(string.Empty))
{
var temp = new MeleeWeapon(
name,
matches[1],
- int.TryParse(matches[10], out int weight) ? weight : 0,
+ int.TryParse(matches[10], out var weight) ? weight : 0,
matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(),
matches[11])
{
- INI = int.TryParse(matches[3], out int ini) ? ini : 0,
+ INI = int.TryParse(matches[3], out var ini) ? ini : 0,
MW = matches[4],
TpKK = matches[2]
};
@@ -94,6 +91,7 @@ namespace DSACore.Auxiliary
Weapons.Add(temp);
await Database.AddWeapon(temp);
}
+
/*if (i > 23)
{
var range = new RangedWeapon(
@@ -118,15 +116,15 @@ namespace DSACore.Auxiliary
var range = new RangedWeapon(
name,
matches[13].Replace(' ', '+'),
- int.TryParse(matches[10], out int weight) ? weight : 0,
+ int.TryParse(matches[10], out var weight) ? weight : 0,
matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(),
matches[11])
{
- AtMod = int.TryParse(matches[18], out int atMod) ? atMod : 0,
- KKMod = int.TryParse(matches[17], out int kkMod) ? kkMod : 0,
+ AtMod = int.TryParse(matches[18], out var atMod) ? atMod : 0,
+ KKMod = int.TryParse(matches[17], out var kkMod) ? kkMod : 0,
AtReach = matches[14],
TpReach = matches[15],
- LoadTime = int.TryParse(matches[18], out int loadTime) ? loadTime : 0
+ LoadTime = int.TryParse(matches[18], out var loadTime) ? loadTime : 0
};
Range.Add(range);
await Database.AddWeapon(range);
@@ -135,17 +133,17 @@ namespace DSACore.Auxiliary
private async Task AddRanged(int i, string talent, List<string> matches)
{
- string name = talent.Replace(' ', '_').Replace(".", "");
+ var name = talent.Replace(' ', '_').Replace(".", "");
if (!matches[1].Equals(string.Empty))
{
var temp = new MeleeWeapon(
name,
matches[1],
- int.TryParse(matches[10], out int weight) ? weight : 0,
+ int.TryParse(matches[10], out var weight) ? weight : 0,
matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(),
matches[11])
{
- INI = int.TryParse(matches[3], out int ini) ? ini : 0,
+ INI = int.TryParse(matches[3], out var ini) ? ini : 0,
MW = matches[4],
TpKK = matches[2]
};
@@ -159,20 +157,19 @@ namespace DSACore.Auxiliary
var range = new RangedWeapon(
name,
matches[13].Replace(' ', '+'),
- int.TryParse(matches[10], out int weight) ? weight : 0,
+ int.TryParse(matches[10], out var weight) ? weight : 0,
matches[0].Split(':', StringSplitOptions.RemoveEmptyEntries).First(),
matches[11])
{
- AtMod = int.TryParse(matches[18], out int atMod) ? atMod : 0,
- KKMod = int.TryParse(matches[17], out int kkMod) ? kkMod : 0,
+ AtMod = int.TryParse(matches[18], out var atMod) ? atMod : 0,
+ KKMod = int.TryParse(matches[17], out var kkMod) ? kkMod : 0,
AtReach = matches[14],
TpReach = matches[15],
- LoadTime = int.TryParse(matches[18], out int loadTime) ? loadTime : 0
+ LoadTime = int.TryParse(matches[18], out var loadTime) ? loadTime : 0
};
Range.Add(range);
await Database.AddWeapon(range);
}
}
}
-}
-
+} \ No newline at end of file
diff --git a/DSACore/Commands/CommandHandler.cs b/DSACore/Commands/CommandHandler.cs
index f43633f..f74f87f 100644
--- a/DSACore/Commands/CommandHandler.cs
+++ b/DSACore/Commands/CommandHandler.cs
@@ -1,7 +1,7 @@
using System;
using DSACore.Auxiliary;
+using DSACore.Auxiliary.Calculator;
using DSACore.DSA_Game;
-using DSACore.Models;
using DSACore.Models.Network;
namespace DSACore.Commands
@@ -10,8 +10,8 @@ namespace DSACore.Commands
{
public static CommandResponse ExecuteCommand(Command cmd)
{
- string res = string.Empty;
- ResponseType type = ResponseType.Broadcast;
+ var res = string.Empty;
+ var type = ResponseType.Broadcast;
switch (cmd.CmdIdentifier.ToLower())
{
case "addChar":
@@ -21,7 +21,7 @@ namespace DSACore.Commands
case "wert":
case "werte":
case "char":
- res = Commands.HeldList.ListAsync(cmd.CharId, cmd.CmdText);
+ res = HeldList.ListAsync(cmd.CharId, cmd.CmdText);
break;
case "help":
case "man":
@@ -49,28 +49,21 @@ namespace DSACore.Commands
res = RandomMisc.Roll(cmd.CmdText + " " + cmd.Cmdmodifier);
break;
case "solve":
- res = new Auxiliary.Calculator.StringSolver(cmd.CmdText + cmd.Cmdmodifier).Solve().ToString();
+ res = new StringSolver(cmd.CmdText + cmd.Cmdmodifier).Solve().ToString();
break;
case "npc":
res = NpcCommands.CreateNpc(cmd.CharId, cmd.CmdTexts, cmd.Cmdmodifier);
break;
-
}
- if (res == string.Empty)
- {
- res= Proben(cmd.Name, cmd.CmdIdentifier, cmd.CmdText, cmd.Cmdmodifier);
- }
- if (res != string.Empty)
- {
- return new CommandResponse(res, type);
- }
+ if (res == string.Empty) res = Proben(cmd.Name, cmd.CmdIdentifier, cmd.CmdText, cmd.Cmdmodifier);
+ if (res != string.Empty) return new CommandResponse(res, type);
return new CommandResponse($"Kommando {cmd.CmdIdentifier} nicht gefunden", ResponseType.Error);
}
private static string Proben(string name, string command, string waffe, int erschwernis = 0)
{
- string res = string.Empty;
+ var res = string.Empty;
switch (command.ToLower())
{
case "f":
@@ -138,4 +131,4 @@ namespace DSACore.Commands
throw new NotImplementedException("access char by id ore name and group id");
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Commands/CommandTypes.cs b/DSACore/Commands/CommandTypes.cs
index d53328b..6838ac2 100644
--- a/DSACore/Commands/CommandTypes.cs
+++ b/DSACore/Commands/CommandTypes.cs
@@ -10,4 +10,4 @@
KeinChar,
Zauber
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Commands/FileHandler.cs b/DSACore/Commands/FileHandler.cs
index af4698a..bce7c54 100644
--- a/DSACore/Commands/FileHandler.cs
+++ b/DSACore/Commands/FileHandler.cs
@@ -1,37 +1,29 @@
-using DSACore.DSA_Game;
+using System;
+using System.Linq;
+using System.Net;
+using DSACore.DSA_Game;
using DSACore.DSA_Game.Characters;
+using DSALib;
namespace DSACore.Commands
{
- using System;
- using System.Linq;
- using System.Net;
-
- using DSALib;
-
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 == string.Empty) throw new ArgumentException("Es wurde keine Datei angehängt");
+
+
+ if (!url.EndsWith(".xml")) throw new ArgumentException("Es wurde kein xml Held mitgeschickt");
- if (!url.EndsWith(".xml"))
+ using (var client = new WebClient())
{
- throw new ArgumentException("Es wurde kein xml Held mitgeschickt");
+ client.DownloadFile(url, "helden\\" + url.Split("/").Last());
}
-
- using (var client = new WebClient())
- {
- client.DownloadFile(url, "helden\\" + url.Split("/").Last());
- }
- Dsa.Chars.Add(new Character("helden\\" + url.Split("/").Last()));
- (Dsa.Chars.Last() as Character)?.Talente.Select(x => new Talent(x.Name, x.Probe, 0))
- .Where(c => !Dsa.Talente.Exists(v => v.Name.Equals(c.Name))).ToList().ForEach(v => Dsa.Talente.Add(v));
+ Dsa.Chars.Add(new Character("helden\\" + url.Split("/").Last()));
+ (Dsa.Chars.Last() as Character)?.Talente.Select(x => new Talent(x.Name, x.Probe, 0))
+ .Where(c => !Dsa.Talente.Exists(v => v.Name.Equals(c.Name))).ToList().ForEach(v => Dsa.Talente.Add(v));
return $"{url.Split("/").Last()} wurde erfolgreich gespeichert";
}
diff --git a/DSACore/Commands/Gm.cs b/DSACore/Commands/Gm.cs
index a320269..98b62db 100644
--- a/DSACore/Commands/Gm.cs
+++ b/DSACore/Commands/Gm.cs
@@ -1,12 +1,5 @@
-using DSACore.Auxiliary;
-using DSACore.DSA_Game;
-
-namespace DSACore.Commands
+namespace DSACore.Commands
{
- using System.Linq;
- using System.Threading.Tasks;
- using DSALib.Characters;
-
/*public class Iam
{
@@ -180,4 +173,4 @@ namespace DSACore.Commands
return res;
}
}*/
-}
+} \ No newline at end of file
diff --git a/DSACore/Commands/HeldList.cs b/DSACore/Commands/HeldList.cs
index 825474c..370af34 100644
--- a/DSACore/Commands/HeldList.cs
+++ b/DSACore/Commands/HeldList.cs
@@ -1,9 +1,9 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
-using DSACore.DSA_Game.Characters;
using DSACore.Auxiliary;
using DSACore.DSA_Game;
+using DSACore.DSA_Game.Characters;
namespace DSACore.Commands
{
@@ -15,63 +15,65 @@ namespace DSACore.Commands
var character = Dsa.GetCharacter(id) as Character;
- int first_column_width = 18;
-
+ var first_column_width = 18;
- if (prop_list.Length == 0 || prop_list[0].ToLower().StartsWith("all") || prop_list[0].ToLower().StartsWith("brief") || prop_list[0].ToLower().StartsWith("zettel"))
- {
+ if (prop_list.Length == 0 || prop_list[0].ToLower().StartsWith("all") ||
+ prop_list[0].ToLower().StartsWith("brief") || prop_list[0].ToLower().StartsWith("zettel"))
+ {
res.Add(character.Name + ":\n");
//Eigenschaften
res.AddRange(
- character.Eigenschaften.Take(9).Select(s => s.Key + ":\t " + s.Value));
+ character.Eigenschaften.Take(9).Select(s => s.Key + ":\t " + s.Value));
res.Add("");
//LE/AE
res.Add("LE:\t " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
if (character.Astralpunkte_Basis > 0)
- {
res.Add("AE:\t " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis);
- }
res.Add("");
//Kampfwerte
res.Add("".AddSpaces(first_column_width) + " AT/PA");
res.AddRange(
- character.Kampftalente.Select(s => s.Name.AddSpaces(first_column_width) + " " + s.At.ToString().AddSpacesAtHead(2) + "/" + s.Pa.ToString().AddSpacesAtHead(2)));
+ character.Kampftalente.Select(s =>
+ s.Name.AddSpaces(first_column_width) + " " + s.At.ToString().AddSpacesAtHead(2) + "/" +
+ s.Pa.ToString().AddSpacesAtHead(2)));
res.Add("");
//Fernkampf
res.Add("".AddSpaces(first_column_width) + " FK");
res.AddRange(
- character.Talente.Where(x => x.IstFernkampftalent()).Select(s => s.Name.AddSpaces(first_column_width) + " " + (character.Eigenschaften["fk"] + s.Value).ToString().AddSpacesAtHead(2)));
+ character.Talente.Where(x => x.IstFernkampftalent()).Select(s =>
+ s.Name.AddSpaces(first_column_width) + " " +
+ (character.Eigenschaften["fk"] + s.Value).ToString().AddSpacesAtHead(2)));
res.Add("");
//Vorteile
res.AddRange(
character.Vorteile
- .Select(s => s.Name + "\t " + s.Value));
+ .Select(s => s.Name + "\t " + s.Value));
res.Add("");
//Talente
res.AddRange(
- character.Talente.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
+ character.Talente.Select(s =>
+ (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " +
+ s.Probe));
res.Add("");
//evtl Zauber
if (character.Zauber.Count > 0)
- {
res.AddRange(
- character.Zauber.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
- }
-
+ character.Zauber.Select(s =>
+ (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) +
+ " " + s.Probe));
}
- else if (prop_list[0].ToLower().StartsWith("man") || prop_list[0].ToLower().StartsWith("help") || prop_list[0].ToLower().StartsWith("hilf"))
+ else if (prop_list[0].ToLower().StartsWith("man") || prop_list[0].ToLower().StartsWith("help") ||
+ prop_list[0].ToLower().StartsWith("hilf"))
{
return "```xl\n" + Help.Get_Specific_Help("Held") + "\n```";
}
else
{
-
res.Add(character.Name + ":\n");
- foreach (string prop in prop_list)
+ foreach (var prop in prop_list)
{
-
switch (prop.ToLower())
{
case "e":
@@ -79,18 +81,16 @@ namespace DSACore.Commands
case "eigenschaft":
case "eigenschaften":
res.AddRange(
- character.Eigenschaften.Take(8).Select(s => s.Key + ":\t " + s.Value));
+ character.Eigenschaften.Take(8).Select(s => s.Key + ":\t " + s.Value));
break;
case "stat":
case "stats":
res.AddRange(
- character.Eigenschaften.Take(9).Select(s => s.Key + ":\t " + s.Value));
+ character.Eigenschaften.Take(9).Select(s => s.Key + ":\t " + s.Value));
res.Add("");
res.Add("LE:\t " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
if (character.Astralpunkte_Basis > 0)
- {
res.Add("AE:\t " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis);
- }
break;
case "le":
res.Add("LE:\t " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
@@ -103,12 +103,16 @@ namespace DSACore.Commands
case "talent":
case "talente":
res.AddRange(
- character.Talente.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
+ character.Talente.Select(s =>
+ (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(
+ first_column_width + 5) + " " + s.Probe));
break;
case "zauber":
case "z":
res.AddRange(
- character.Zauber.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
+ character.Zauber.Select(s =>
+ (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(
+ first_column_width + 5) + " " + s.Probe));
break;
case "w":
case "waffe":
@@ -118,13 +122,17 @@ namespace DSACore.Commands
case "kampfwerte":
res.Add("".AddSpaces(first_column_width) + " AT/PA");
res.AddRange(
- character.Kampftalente.Select(s => s.Name.AddSpaces(first_column_width) + " " + s.At.ToString().AddSpacesAtHead(2) + "/" + s.Pa.ToString().AddSpacesAtHead(2)));
+ character.Kampftalente.Select(s =>
+ s.Name.AddSpaces(first_column_width) + " " + s.At.ToString().AddSpacesAtHead(2) +
+ "/" + s.Pa.ToString().AddSpacesAtHead(2)));
break;
case "f":
case "fern":
res.Add("".AddSpaces(first_column_width) + " FK");
res.AddRange(
- character.Talente.Where(x => x.IstFernkampftalent()).Select(s => s.Name.AddSpaces(first_column_width) + " " + (character.Eigenschaften["fk"] + s.Value).ToString().AddSpacesAtHead(2)));
+ character.Talente.Where(x => x.IstFernkampftalent()).Select(s =>
+ s.Name.AddSpaces(first_column_width) + " " +
+ (character.Eigenschaften["fk"] + s.Value).ToString().AddSpacesAtHead(2)));
break;
case "v":
case "vt":
@@ -135,7 +143,7 @@ namespace DSACore.Commands
case "nachteile":
res.AddRange(
character.Vorteile
- .Select(s => s.Name + "\t " + s.Value));
+ .Select(s => s.Name + "\t " + s.Value));
break;
default:
@@ -145,15 +153,11 @@ namespace DSACore.Commands
res.Add("");
}
-
}
var sb = new StringBuilder();
- foreach (string re in res)
- {
- sb.AppendLine(re);
- }
+ foreach (var re in res) sb.AppendLine(re);
return sb.ToString();
/*
@@ -167,4 +171,4 @@ namespace DSACore.Commands
}*/
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Commands/Help.cs b/DSACore/Commands/Help.cs
index 1575b36..974c44c 100644
--- a/DSACore/Commands/Help.cs
+++ b/DSACore/Commands/Help.cs
@@ -1,76 +1,54 @@
using System.Linq;
-using System.Threading.Tasks;
using DSACore.Auxiliary;
+using DSACore.DSA_Game.Save;
namespace DSACore.Commands
{
public class Help
{
- static Help()
- {
- /*TextReader stream = new StreamReader(@"..\..\Help.json"); // Load command-description file
- var reader = new JsonTextReader(stream); // create stream reader
-
- reader.Read(); // step into structure, until the array starts
- reader.Read();
- reader.Read();
-
- try
- {
- var test = new JsonSerializer().Deserialize<List<CommandInfo>>(reader); // Deserialize Data and create CommandInfo Struct
-
- Commands.AddRange(test); // Add new CommandInfos to List
- }
- catch (Exception e)
- {
- // ignored
- }*/
- }
-
//public static List<CommandInfo> Commands { get; } = new List<CommandInfo>();
public static string Get_Specific_Help(string command)
{
// return command specific help
- var com = DSACore.DSA_Game.Save.Properties.CommandInfos.OrderBy(x => SpellCorrect.CompareEasy(x.Name, command.ToLower())).First(); // get best fit command
+ var com = Properties.CommandInfos
+ .OrderBy(x => SpellCorrect.CompareEasy(x.Name, command.ToLower())).First(); // get best fit command
return com.GetDescription();
}
public static string Get_Generic_Help()
{
- string res = "";
- foreach (var com in DSACore.DSA_Game.Save.Properties.CommandInfos)
+ var res = "";
+ foreach (var com in Properties.CommandInfos)
{
- int first_column_width = 8;
+ var first_column_width = 8;
res += ("!" + com.Name + ": ").AddSpaces(first_column_width) + com.Brief;
if (com.Description.Length > 1)
- {
- res += "\n" + "".AddSpaces(first_column_width) + "(\"!man " + com.Name + "\" gibt genauere Informationen)";
- }
+ res += "\n" + "".AddSpaces(first_column_width) + "(\"!man " + com.Name +
+ "\" gibt genauere Informationen)";
res += "\n\n";
}
+
return res;
}
-
+
public static string ShowHelp(params string[] commandList)
{
var command = "";
- if (commandList.Length > 0) {
- command = commandList.Aggregate((s, c) => s + " " + c);
- }
+ if (commandList.Length > 0) command = commandList.Aggregate((s, c) => s + " " + c);
if (command.Equals(string.Empty)) // return generic Help
{
- string res = Get_Generic_Help();
-
+ var res = Get_Generic_Help();
+
return res;
}
-
+
return Get_Specific_Help(command);
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Commands/LebenUndAstral.cs b/DSACore/Commands/LebenUndAstral.cs
index b5bc260..a671296 100644
--- a/DSACore/Commands/LebenUndAstral.cs
+++ b/DSACore/Commands/LebenUndAstral.cs
@@ -1,8 +1,6 @@
using System;
-using System.Linq;
-using System.Threading.Tasks;
-using DSACore.DSA_Game;
using DSACore.Auxiliary;
+using DSACore.DSA_Game;
using DSALib.Characters;
namespace DSACore.Commands
@@ -12,9 +10,9 @@ namespace DSACore.Commands
public static string LEAsync(ulong id, string modifier)
{
//This is the string that will be printed
- string res = "";
+ var res = "";
+
-
//Get the actual text
res += Dsa.GetCharacter(id).get_LE_Text(modifier);
@@ -23,17 +21,17 @@ namespace DSACore.Commands
}
}
- public class AE
+ public class AE
{
public static string AEAsync(ulong id, string modifier)
{
//This is the string that will be printed
- string res = "";
+ var res = "";
//Get the actual text
res += Dsa.GetCharacter(id).get_AE_Text(modifier);
-
+
return res;
}
}
@@ -42,11 +40,11 @@ namespace DSACore.Commands
{
public static string get_LE_Text(this ICharacter c, string prop)
{
- string res = "";
+ var res = "";
var comp = new SpellCorrect();
var character = c;
- res += (character.Name + ":\n");
+ res += character.Name + ":\n";
//If there is actual input we process it
if (prop.Length > 0)
@@ -60,15 +58,20 @@ namespace DSACore.Commands
//Allow overflowing the max
if (prop.StartsWith("++"))
{
- character.Lebenspunkte_Aktuell = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop.Substring(1, prop.Length - 1));
+ character.Lebenspunkte_Aktuell = character.Lebenspunkte_Aktuell +
+ Convert.ToInt32(prop.Substring(1, prop.Length - 1));
}
else
{
- int temp = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop) - character.Lebenspunkte_Basis;
+ var temp = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop) -
+ character.Lebenspunkte_Basis;
//Stop from overflow overflow
if (temp > 0 && prop.StartsWith("+"))
{
- character.Lebenspunkte_Aktuell = (character.Lebenspunkte_Basis > character.Lebenspunkte_Aktuell) ? character.Lebenspunkte_Basis : character.Lebenspunkte_Aktuell;
+ character.Lebenspunkte_Aktuell =
+ character.Lebenspunkte_Basis > character.Lebenspunkte_Aktuell
+ ? character.Lebenspunkte_Basis
+ : character.Lebenspunkte_Aktuell;
res += " Maximale Lebenspunkte sind erreicht ";
}
//Simply apply change
@@ -91,23 +94,23 @@ namespace DSACore.Commands
//If no value is passed, the curent value is displayed
else
{
- res += ("LE: " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
+ res += "LE: " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis;
}
return res;
}
+
public static string get_AE_Text(this ICharacter c, string prop)
{
- string res = "";
+ var res = "";
var comp = new SpellCorrect();
var character = c;
- res += (character.Name + ":\n");
+ res += character.Name + ":\n";
//If there is actual input we process it
if (prop.Length > 0)
{
-
res += "AE: ";
res += character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis + " -> ";
@@ -117,15 +120,20 @@ namespace DSACore.Commands
//Allow overflowing the max
if (prop.StartsWith("++"))
{
- character.Astralpunkte_Aktuell = character.Astralpunkte_Aktuell + Convert.ToInt32(prop.Substring(1, prop.Length - 1));
+ character.Astralpunkte_Aktuell = character.Astralpunkte_Aktuell +
+ Convert.ToInt32(prop.Substring(1, prop.Length - 1));
}
else
{
- int temp = character.Astralpunkte_Aktuell + Convert.ToInt32(prop) - character.Astralpunkte_Basis;
+ var temp = character.Astralpunkte_Aktuell + Convert.ToInt32(prop) -
+ character.Astralpunkte_Basis;
//Stop from overflow overflow
if (temp > 0 && prop.StartsWith("+"))
{
- character.Astralpunkte_Aktuell = (character.Astralpunkte_Basis > character.Astralpunkte_Aktuell) ? character.Astralpunkte_Basis : character.Astralpunkte_Aktuell;
+ character.Astralpunkte_Aktuell =
+ character.Astralpunkte_Basis > character.Astralpunkte_Aktuell
+ ? character.Astralpunkte_Basis
+ : character.Astralpunkte_Aktuell;
res += " Maximale Astralpunkte sind erreicht ";
}
//Simply apply change
@@ -142,7 +150,6 @@ namespace DSACore.Commands
}
res += character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis;
-
}
//Set to new value regardless of original
else
@@ -155,14 +162,11 @@ namespace DSACore.Commands
//If no value is passed, the curent value is displayed
else
{
- res += ("AE: " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis);
+ res += "AE: " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis;
}
return res;
}
}
-}
-
-
-
+} \ No newline at end of file
diff --git a/DSACore/Commands/List.cs b/DSACore/Commands/List.cs
index 1fa0dde..7fc682f 100644
--- a/DSACore/Commands/List.cs
+++ b/DSACore/Commands/List.cs
@@ -1,9 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Threading.Tasks;
-using DSACore.DSA_Game;
using DSACore.Audio;
+using DSACore.DSA_Game;
namespace DSACore.Commands
{
@@ -12,7 +11,7 @@ namespace DSACore.Commands
public static string ListAsync(string prop)
{
var res = new List<string>();
-
+
//int persist = 0;
switch (prop.ToLower())
@@ -20,7 +19,7 @@ namespace DSACore.Commands
case "man":
case "help":
return Help.Get_Specific_Help("List");
- // break;
+ // break;
case "chars":
res.AddRange(Dsa.Chars.Select(x => x.Name));
break;
@@ -44,4 +43,4 @@ namespace DSACore.Commands
return res.ToString();
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Commands/MiscCommands.cs b/DSACore/Commands/MiscCommands.cs
index 21646e7..ebd1598 100644
--- a/DSACore/Commands/MiscCommands.cs
+++ b/DSACore/Commands/MiscCommands.cs
@@ -1,15 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Net.Http;
-using System.Text;
-using System.Threading.Tasks;
-using DSACore.DSA_Game;
-using DSACore.Auxiliary;
-using Microsoft.AspNetCore.Hosting.Internal;
-
-namespace DSACore.Commands
+namespace DSACore.Commands
{
public class MiscCommands
{
@@ -227,4 +216,4 @@ namespace DSACore.Commands
}*/
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Commands/NpcCommands.cs b/DSACore/Commands/NpcCommands.cs
index 50ea966..95243ca 100644
--- a/DSACore/Commands/NpcCommands.cs
+++ b/DSACore/Commands/NpcCommands.cs
@@ -1,27 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Threading.Tasks;
using DSACore.Characters;
using DSACore.DSA_Game;
using DSACore.DSA_Game.Characters;
-using DSACore.Auxiliary;
-using Microsoft.AspNetCore.Mvc.Internal;
namespace DSACore.Commands
{
public class NpcCommands
{
-
public static string CreateNpc(ulong id, IEnumerable<string> props, int modifier)
{
- if (int.TryParse(props.Last(), out int mean))
- {
- return Random(id, props.First(), mean, 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)
@@ -30,13 +22,10 @@ namespace DSACore.Commands
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)
{
- if (Dsa.Chars.Exists(x => x.Name.Equals(npcName)))
- {
- throw new Exception("Char gibt es schon");
- }
+ if (Dsa.Chars.Exists(x => x.Name.Equals(npcName))) throw new Exception("Char gibt es schon");
throw new NotImplementedException();
var chr = Dsa.GetCharacter(id);
Dsa.Chars.Add(new Character(chr as Character, npcName, stDv));
diff --git a/DSACore/Commands/ProbenTest.cs b/DSACore/Commands/ProbenTest.cs
index a927cd9..d0800d6 100644
--- a/DSACore/Commands/ProbenTest.cs
+++ b/DSACore/Commands/ProbenTest.cs
@@ -1,6 +1,6 @@
namespace DSACore.Commands
{
- public class ProbenTest
+ public class ProbenTest
{
/*[Command("t"), Summary("Würfelt ein Talent-/Zauberprobe")]
[Alias("T", "Talent", "talent", "versuche")]
@@ -82,4 +82,4 @@
return this.ReplyAsync("```xl\n" + Dsa.Chars.Find(x => x.Name.Equals(Dsa.Session.Relation[this.Context.User.Username])).Fernkampf(waffe, erschwernis) + "\n```");
}*/
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Controllers/CommandsController.cs b/DSACore/Controllers/CommandsController.cs
index d35690c..5addf82 100644
--- a/DSACore/Controllers/CommandsController.cs
+++ b/DSACore/Controllers/CommandsController.cs
@@ -1,8 +1,5 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-using DSACore.Models;
+using DSACore.Commands;
using DSACore.Models.Network;
using Microsoft.AspNetCore.Mvc;
@@ -29,17 +26,16 @@ namespace DSACore.Controllers
// POST api/<controller>/Felis
[HttpPost]
- public string Post([FromBody]Command cmd)
+ public string Post([FromBody] Command cmd)
{
try
{
- return Commands.CommandHandler.ExecuteCommand(cmd).message;
+ return CommandHandler.ExecuteCommand(cmd).message;
}
catch (Exception e)
{
return $"Ein Fehler ist aufgetreten: \n {e.Message}";
}
-
}
/*
@@ -56,4 +52,4 @@ namespace DSACore.Controllers
{
}*/
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Controllers/LobbyController.cs b/DSACore/Controllers/LobbyController.cs
index a946184..df22607 100644
--- a/DSACore/Controllers/LobbyController.cs
+++ b/DSACore/Controllers/LobbyController.cs
@@ -1,5 +1,6 @@
-using DSACore.Models.Network;
using System;
+using DSACore.Commands;
+using DSACore.Models.Network;
using Microsoft.AspNetCore.Mvc;
namespace DSACore.Controllers
@@ -13,20 +14,18 @@ namespace DSACore.Controllers
{
return "Usage: get /tokens/{Token}";
}
-
+
[HttpPost]
- public string Post([FromBody]Command cmd)
+ public string Post([FromBody] Command cmd)
{
try
{
- return Commands.CommandHandler.ExecuteCommand(cmd).message;
+ return CommandHandler.ExecuteCommand(cmd).message;
}
catch (Exception e)
{
return $"Ein Fehler ist aufgetreten: \n {e.Message}";
}
-
- }
-
+ }
}
} \ No newline at end of file
diff --git a/DSACore/Controllers/TokensController.cs b/DSACore/Controllers/TokensController.cs
index 1d49f44..a85cabe 100644
--- a/DSACore/Controllers/TokensController.cs
+++ b/DSACore/Controllers/TokensController.cs
@@ -1,3 +1,4 @@
+using DSACore.Hubs;
using Microsoft.AspNetCore.Mvc;
namespace DSACore.Controllers
@@ -6,23 +7,19 @@ namespace DSACore.Controllers
[ApiController]
public class TokensController : Controller
{
-
// GET
[HttpGet("{token}")]
public ActionResult<string> Get(string token)
{
- if (!int.TryParse(token, out var inttoken))
- {
+ if (!int.TryParse(token, out var intToken))
return BadRequest("The token has to be a 32 bit unsigned integer");
- }
- if (!Hubs.Users.Tokens.Exists(x => x.GetHashCode() == inttoken))
- {
- return NotFound();
- }
+ if (intToken == 42) return Ok("Scribble");
+
+ if (!Users.Tokens.Exists(x => x.GetHashCode() == intToken)) return NotFound();
- var group = Hubs.Users.Tokens.Find(x => x.GetHashCode() == inttoken);
- return Ok(group);
+ var group = Users.Tokens.Find(x => x.GetHashCode() == intToken);
+ return Ok(group.Group);
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/DSA_Game/Characters/Character.cs b/DSACore/DSA_Game/Characters/Character.cs
index 247fc58..ac890cb 100644
--- a/DSACore/DSA_Game/Characters/Character.cs
+++ b/DSACore/DSA_Game/Characters/Character.cs
@@ -1,129 +1,117 @@
-using System.IO;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Xml;
using DSACore.Auxiliary;
using DSALib;
using DSALib.Characters;
namespace DSACore.DSA_Game.Characters
{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Xml;
-
-
public class Character : Being, ICharacter
{
public Character()
{
- this.PropTable.Add("MU", "Mut"); // routing
- this.PropTable.Add("KL", "Klugheit");
- this.PropTable.Add("IN", "Intuition");
- this.PropTable.Add("CH", "Charisma");
- this.PropTable.Add("FF", "Fingerfertigkeit");
- this.PropTable.Add("GE", "Gewandtheit");
- this.PropTable.Add("KO", "Konstitution");
- this.PropTable.Add("KK", "Körperkraft");
-
+ PropTable.Add("MU", "Mut"); // routing
+ PropTable.Add("KL", "Klugheit");
+ PropTable.Add("IN", "Intuition");
+ PropTable.Add("CH", "Charisma");
+ PropTable.Add("FF", "Fingerfertigkeit");
+ PropTable.Add("GE", "Gewandtheit");
+ PropTable.Add("KO", "Konstitution");
+ PropTable.Add("KK", "Körperkraft");
}
public Character(string path) : this()
{
- this.Load(new MemoryStream(File.ReadAllBytes(path))); // load
- this.Post_process(); // calculate derived values
+ Load(new MemoryStream(File.ReadAllBytes(path))); // load
+ Post_process(); // calculate derived values
}
+
public Character(MemoryStream stream) : this()
{
- this.Load(stream); // load
- this.Post_process(); // calculate derived values
+ Load(stream); // load
+ Post_process(); // calculate derived values
}
public Character(Character c, string name, int stDv = 2) : this()
{
- this.Name = name;
+ Name = name;
foreach (var i in c.Eigenschaften)
- {
- this.Eigenschaften.Add(i.Key, i.Value + (int)Math.Round(RandomMisc.Random(stDv)));
- }
+ Eigenschaften.Add(i.Key, i.Value + (int) Math.Round(RandomMisc.Random(stDv)));
foreach (var i in c.Vorteile)
- {
- this.Vorteile.Add(new Vorteil(i.Name, i.Value + (int)Math.Round(RandomMisc.Random(stDv))));
- }
+ Vorteile.Add(new Vorteil(i.Name, i.Value + (int) Math.Round(RandomMisc.Random(stDv))));
foreach (var i in c.Talente)
- {
- this.Talente.Add(new Talent(i.Name, i.Probe, i.Value + (int)Math.Round(RandomMisc.Random(stDv))));
- }
+ Talente.Add(new Talent(i.Name, i.Probe, i.Value + (int) Math.Round(RandomMisc.Random(stDv))));
foreach (var i in c.Zauber)
- {
- this.Zauber.Add(new Zauber(i.Name, i.Probe, i.Value + (int)Math.Round(RandomMisc.Random(stDv)), i.Complexity, i.Representation));
- }
+ Zauber.Add(new Zauber(i.Name, i.Probe, i.Value + (int) Math.Round(RandomMisc.Random(stDv)),
+ i.Complexity, i.Representation));
foreach (var i in c.Kampftalente)
- {
- this.Kampftalente.Add(new KampfTalent(i.Name, i.At + (int)Math.Round(RandomMisc.Random(stDv)), i.Pa + (int)Math.Round(RandomMisc.Random(stDv))));
- }
+ Kampftalente.Add(new KampfTalent(i.Name, i.At + (int) Math.Round(RandomMisc.Random(stDv)),
+ i.Pa + (int) Math.Round(RandomMisc.Random(stDv))));
- this.Post_process(); // calculate derived values
+ Post_process(); // calculate derived values
}
- public Dictionary<string, int> Eigenschaften { get; set; } = new Dictionary<string, int>(); // char properties
+ public Dictionary<string, int> Eigenschaften { get; set; } = new Dictionary<string, int>(); // char properties
- public List<Talent> Talente { get; set; } = new List<Talent>(); // list of talent objects (talents)
+ public List<Talent> Talente { get; set; } = new List<Talent>(); // list of talent objects (talents)
- public List<Zauber> Zauber { get; set; } = new List<Zauber>(); // list of spell objects
+ public List<Zauber> Zauber { get; set; } = new List<Zauber>(); // list of spell objects
- public List<KampfTalent> Kampftalente { get; set; } = new List<KampfTalent>(); // list of combat objects
+ public List<KampfTalent> Kampftalente { get; set; } = new List<KampfTalent>(); // list of combat objects
public List<Vorteil> Vorteile { get; set; } = new List<Vorteil>();
public Dictionary<string, string> PropTable { get; set; } = new Dictionary<string, string>(); // -> Körperkraft
- public string TestTalent(string talent, int erschwernis = 0) // Talentprobe
+ public string TestTalent(string talent, int erschwernis = 0) // Talentprobe
{
- return this.Talente.ProbenTest(this, talent, erschwernis);
+ return Talente.ProbenTest(this, talent, erschwernis);
}
- public string TestZauber(string zauber, int erschwernis = 0) // Talentprobe
+ public string TestZauber(string zauber, int erschwernis = 0) // Talentprobe
{
- return this.Zauber.ProbenTest(this, zauber, erschwernis);
+ return Zauber.ProbenTest(this, zauber, erschwernis);
}
public string TestEigenschaft(string eigenschaft, int erschwernis = 0)
{
var output = new StringBuilder();
- var prop = this.PropTable[eigenschaft.ToUpper()];
- int tap = this.Eigenschaften[prop];
+ var prop = PropTable[eigenschaft.ToUpper()];
+ var tap = Eigenschaften[prop];
output.AppendFormat(
"{0}-Eigenschaftsprobe ew:{1} {2} \n",
prop,
tap,
erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
- int roll = Dice.Roll();
+ var roll = Dice.Roll();
output.Append($"Gewürfelt: {roll} übrig: {tap - roll - erschwernis}");
return output.ToString();
}
- public string Angriff(string talent, int erschwernis = 0) // pretty self explanatory
+ public string Angriff(string talent, int erschwernis = 0) // pretty self explanatory
{
var output = new StringBuilder();
var sc = new SpellCorrect();
- var attack = this.Kampftalente.OrderBy(x => sc.Compare(talent, x.Name)).First();
+ var attack = Kampftalente.OrderBy(x => sc.Compare(talent, x.Name)).First();
if (sc.Compare(talent, attack.Name) > SpellCorrect.ErrorThreshold)
- {
- return $"{this.Name} kann nicht mit der Waffenart {talent} umgehen...";
- }
+ return $"{Name} kann nicht mit der Waffenart {talent} umgehen...";
- int tap = attack.At;
+ var tap = attack.At;
output.AppendFormat(
"{0}-Angriff taw:{1} {2} \n",
attack.Name,
tap,
erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
- int temp = Dice.Roll();
+ var temp = Dice.Roll();
output.Append(temp - erschwernis);
return output.ToString();
}
@@ -132,21 +120,19 @@ namespace DSACore.DSA_Game.Characters
{
var output = new StringBuilder();
var sc = new SpellCorrect();
- var attack = this.Kampftalente.OrderBy(x => sc.Compare(talent, x.Name)).First();
+ var attack = Kampftalente.OrderBy(x => sc.Compare(talent, x.Name)).First();
if (sc.Compare(talent, attack.Name) > SpellCorrect.ErrorThreshold)
- {
- return $"{this.Name} kann nicht mit der Waffenart {talent} umgehen...";
- }
+ return $"{Name} kann nicht mit der Waffenart {talent} umgehen...";
- int tap = attack.Pa;
+ var tap = attack.Pa;
output.AppendFormat(
"{0}-Parade taw:{1} {2}\n",
attack.Name,
tap,
erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
- int temp = Dice.Roll();
+ var temp = Dice.Roll();
output.Append(temp - erschwernis);
return output.ToString();
}
@@ -155,21 +141,19 @@ namespace DSACore.DSA_Game.Characters
{
var output = new StringBuilder();
var sc = new SpellCorrect();
- int fk = this.Eigenschaften["fk"];
- var attack = this.Talente.OrderBy(x => sc.Compare(talent, x.Name)).First();
+ var fk = Eigenschaften["fk"];
+ var attack = Talente.OrderBy(x => sc.Compare(talent, x.Name)).First();
if (sc.Compare(talent, attack.Name) > SpellCorrect.ErrorThreshold)
- {
- return $"{this.Name} kann nicht mit der Waffenart {talent} umgehen...";
- }
+ return $"{Name} kann nicht mit der Waffenart {talent} umgehen...";
- int tap = attack.Value;
+ var tap = attack.Value;
output.AppendFormat(
"{0} taw:{1} {2} \n",
attack.Name,
tap,
erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
tap -= erschwernis;
- int temp = Dice.Roll();
+ var temp = Dice.Roll();
tap -= temp > fk ? temp - fk : 0;
output.Append($"W20: {temp} tap: {tap}");
return output.ToString();
@@ -177,34 +161,30 @@ namespace DSACore.DSA_Game.Characters
private void Post_process()
{
- var LE_Wert = this.Eigenschaften["Lebensenergie"];
- var AE_Wert = this.Eigenschaften.First(s => s.Key.Contains("Astralenergie")).Value;
+ var LE_Wert = Eigenschaften["Lebensenergie"];
+ var AE_Wert = Eigenschaften.First(s => s.Key.Contains("Astralenergie")).Value;
//var KL_Wert = this.Eigenschaften.First(s => s.Key.Contains("Klugheit")).Value;
- var MU_Wert = this.Eigenschaften.First(s => s.Key.Contains("Mut")).Value;
- var IN_Wert = this.Eigenschaften.First(s => s.Key.Contains("Intuition")).Value;
- var CH_Wert = this.Eigenschaften.First(s => s.Key.Contains("Charisma")).Value;
- var KK_Wert = this.Eigenschaften["Körperkraft"];
- var KO__Wert = this.Eigenschaften["Konstitution"];
-
- this.Astralpunkte_Basis = 0;
+ var MU_Wert = Eigenschaften.First(s => s.Key.Contains("Mut")).Value;
+ var IN_Wert = Eigenschaften.First(s => s.Key.Contains("Intuition")).Value;
+ var CH_Wert = Eigenschaften.First(s => s.Key.Contains("Charisma")).Value;
+ var KK_Wert = Eigenschaften["Körperkraft"];
+ var KO__Wert = Eigenschaften["Konstitution"];
- this.Ausdauer_Basis = 0;
+ Astralpunkte_Basis = 0;
- this.Lebenspunkte_Basis = LE_Wert + (int)(KO__Wert + (KK_Wert / 2.0) + 0.5);
+ Ausdauer_Basis = 0;
- if (this.Vorteile.Exists(x => x.Name.ToLower().Contains("zauberer")))
- {
- this.Astralpunkte_Basis = AE_Wert + (int)((MU_Wert + IN_Wert + CH_Wert) / 2.0 + 0.5);
- }
+ Lebenspunkte_Basis = LE_Wert + (int) (KO__Wert + KK_Wert / 2.0 + 0.5);
- this.Lebenspunkte_Aktuell = this.Lebenspunkte_Basis;
- this.Astralpunkte_Aktuell = this.Astralpunkte_Basis;
- this.Ausdauer_Aktuell = this.Ausdauer_Basis;
+ if (Vorteile.Exists(x => x.Name.ToLower().Contains("zauberer")))
+ Astralpunkte_Basis = AE_Wert + (int) ((MU_Wert + IN_Wert + CH_Wert) / 2.0 + 0.5);
+ Lebenspunkte_Aktuell = Lebenspunkte_Basis;
+ Astralpunkte_Aktuell = Astralpunkte_Basis;
+ Ausdauer_Aktuell = Ausdauer_Basis;
}
-
private void Load(MemoryStream stream)
{
@@ -212,10 +192,7 @@ namespace DSACore.DSA_Game.Characters
while (reader.Read())
{
// read until he hits keywords
- if (reader.NodeType != XmlNodeType.Element)
- {
- continue;
- }
+ if (reader.NodeType != XmlNodeType.Element) continue;
switch (reader.Name)
{
@@ -223,12 +200,13 @@ namespace DSACore.DSA_Game.Characters
reader.Skip();
break;
case "held":
- this.Name = reader.GetAttribute("name"); // name
+ Name = reader.GetAttribute("name"); // name
break;
case "eigenschaft":
- this.Eigenschaften.Add(
+ Eigenschaften.Add(
reader.GetAttribute("name") ?? throw new InvalidOperationException(),
- Convert.ToInt32(reader.GetAttribute("value")) + Convert.ToInt32(reader.GetAttribute("mod")));
+ Convert.ToInt32(reader.GetAttribute("value")) +
+ Convert.ToInt32(reader.GetAttribute("mod")));
break;
case "vt":
reader.Read();
@@ -236,14 +214,14 @@ namespace DSACore.DSA_Game.Characters
{
try
{
- this.Vorteile.Add(new Vorteil(
+ Vorteile.Add(new Vorteil(
reader.GetAttribute("name"),
- // Convert.ToInt32(reader.GetAttribute("value"))));
- reader.GetAttribute("value")));
+ // Convert.ToInt32(reader.GetAttribute("value"))));
+ reader.GetAttribute("value")));
}
catch
{
- this.Vorteile.Add(new Vorteil(reader.GetAttribute("name")));
+ Vorteile.Add(new Vorteil(reader.GetAttribute("name")));
}
reader.Read();
@@ -254,7 +232,7 @@ namespace DSACore.DSA_Game.Characters
reader.Read();
while (reader.Name.Equals("talent"))
{
- this.Talente.Add(
+ Talente.Add(
new Talent(
reader.GetAttribute("name"),
reader.GetAttribute("probe")?.Remove(0, 2).Trim(')'),
@@ -267,7 +245,7 @@ namespace DSACore.DSA_Game.Characters
reader.Read();
while (reader.Name.Equals("zauber"))
{
- this.Zauber.Add(
+ Zauber.Add(
new Zauber(
reader.GetAttribute("name"),
reader.GetAttribute("probe")?.Remove(0, 2).Trim(')'),
@@ -279,12 +257,12 @@ namespace DSACore.DSA_Game.Characters
break;
case "kampfwerte":
- string atName = reader.GetAttribute("name");
+ var atName = reader.GetAttribute("name");
reader.Read();
- int at = Convert.ToInt32(reader.GetAttribute("value"));
+ var at = Convert.ToInt32(reader.GetAttribute("value"));
reader.Read();
- int pa = Convert.ToInt32(reader.GetAttribute("value"));
- this.Kampftalente.Add(new KampfTalent(atName, at, pa));
+ var pa = Convert.ToInt32(reader.GetAttribute("value"));
+ Kampftalente.Add(new KampfTalent(atName, at, pa));
break;
}
}
diff --git a/DSACore/DSA_Game/Characters/NPC.cs b/DSACore/DSA_Game/Characters/NPC.cs
index 0a660ee..75c3fe9 100644
--- a/DSACore/DSA_Game/Characters/NPC.cs
+++ b/DSACore/DSA_Game/Characters/NPC.cs
@@ -4,11 +4,6 @@ using DSALib.Characters;
namespace DSACore.Characters
{
- using System;
-
- using DSACore.Auxiliary;
- using DSACore.DSA_Game.Characters;
-
public class Npc : Being, ICharacter
{
private readonly int mean, stDv;
@@ -17,94 +12,67 @@ namespace DSACore.Characters
{
this.mean = mean;
this.stDv = stDv;
- this.Name = name;
+ Name = name;
}
public string TestTalent(string talent, int tap = 3)
{
- for (int i = 0; i <= 2; i++)
+ for (var i = 0; i <= 2; i++)
{
// foreach property, dice and tap
- int temp = Dice.Roll();
- int eigenschaft = (int)Math.Round(RandomMisc.Random(this.stDv, this.mean));
+ var temp = Dice.Roll();
+ var eigenschaft = (int) Math.Round(RandomMisc.Random(stDv, mean));
- if (eigenschaft < temp)
- {
- tap -= temp - eigenschaft;
- }
+ if (eigenschaft < temp) tap -= temp - eigenschaft;
}
- if (tap >= 0)
- {
- return $"{this.Name} vollführt {talent} erfolgreich";
- }
+ if (tap >= 0) return $"{Name} vollführt {talent} erfolgreich";
- return $"{this.Name} scheitert an {talent}";
+ return $"{Name} scheitert an {talent}";
}
public string TestEigenschaft(string eigenschaft, int erschwernis = 0)
{
- int temp = Dice.Roll();
- int prop = (int)Math.Round(RandomMisc.Random(this.stDv, this.stDv));
-
- if (temp + erschwernis < prop)
- {
- return $"{this.Name} vollführt {eigenschaft} erfolgreich";
- }
+ var temp = Dice.Roll();
+ var prop = (int) Math.Round(RandomMisc.Random(stDv, stDv));
+
+ if (temp + erschwernis < prop) return $"{Name} vollführt {eigenschaft} erfolgreich";
- return $"{this.Name} scheitert an {eigenschaft}";
+ return $"{Name} scheitert an {eigenschaft}";
}
public string Angriff(string waffe, int erschwernis = 0)
{
- int temp = Dice.Roll();
+ var temp = Dice.Roll();
- if (temp == 1)
- {
- return $"{this.Name} greift kritisch mit {waffe} an";
- }
+ if (temp == 1) return $"{Name} greift kritisch mit {waffe} an";
- if (temp < erschwernis)
- {
- return $"{this.Name} greift mit {waffe} an";
- }
+ if (temp < erschwernis) return $"{Name} greift mit {waffe} an";
- return $"{this.Name} haut mit {waffe} daneben";
+ return $"{Name} haut mit {waffe} daneben";
}
public string Parade(string waffe, int erschwernis = 0)
{
- int temp = Dice.Roll();
+ var temp = Dice.Roll();
- if (temp == 1)
- {
- return $"{this.Name} pariert mit {waffe} meisterlich";
- }
+ if (temp == 1) return $"{Name} pariert mit {waffe} meisterlich";
- if (temp < erschwernis)
- {
- return $"{this.Name} pariert mit {waffe} an";
- }
+ if (temp < erschwernis) return $"{Name} pariert mit {waffe} an";
- return $"{this.Name} schafft es nicht mit {waffe} zu parieren";
+ return $"{Name} schafft es nicht mit {waffe} zu parieren";
}
public string Fernkampf(string waffe, int erschwernis = 0)
{
- int temp = Dice.Roll();
+ var temp = Dice.Roll();
- if (temp == 1)
- {
- return $"{this.Name} trifft kritisch mit {waffe}";
- }
+ if (temp == 1) return $"{Name} trifft kritisch mit {waffe}";
- if (temp < erschwernis)
- {
- return $"{this.Name} greift mit {waffe} an";
- }
+ if (temp < erschwernis) return $"{Name} greift mit {waffe} an";
- return $"{this.Name} schießt mit {waffe} daneben";
+ return $"{Name} schießt mit {waffe} daneben";
}
public string TestZauber(string zauber, int erschwernis)
@@ -112,4 +80,4 @@ namespace DSACore.Characters
return TestTalent(zauber, erschwernis);
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/DSA_Game/Characters/SaveChar.cs b/DSACore/DSA_Game/Characters/SaveChar.cs
index 87c2566..7b29b4e 100644
--- a/DSACore/DSA_Game/Characters/SaveChar.cs
+++ b/DSACore/DSA_Game/Characters/SaveChar.cs
@@ -2,7 +2,6 @@
namespace DSACore.DSA_Game.Characters
{
-
public class SaveChar
{
public string Name { get; set; }
@@ -36,4 +35,4 @@ namespace DSACore.DSA_Game.Characters
c.Name = s.Name;
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/DSA_Game/Dsa.cs b/DSACore/DSA_Game/Dsa.cs
index cbdb734..18d0b81 100644
--- a/DSACore/DSA_Game/Dsa.cs
+++ b/DSACore/DSA_Game/Dsa.cs
@@ -1,28 +1,24 @@
using System;
-using DSACore.Auxiliary;
-using DSACore.FireBase;
+using System.Collections.Generic;
+using System.Linq;
+using DSACore.DSA_Game.Characters;
+using DSACore.DSA_Game.Save;
using DSALib;
using DSALib.Characters;
-using Microsoft.EntityFrameworkCore.Design;
namespace DSACore.DSA_Game
{
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using DSACore.DSA_Game.Characters;
- using DSACore.DSA_Game.Save;
-
public static class Dsa
{
#if DEBUG
- public const string rootPath = "";//"C:\\Users\\Dennis\\Source\\Repos\\DiscoBot\\DSACore\\";//"DiscoBot\\DSACore\\";
+ public const string
+ rootPath = ""; //"C:\\Users\\Dennis\\Source\\Repos\\DiscoBot\\DSACore\\";//"DiscoBot\\DSACore\\";
#else
public const string rootPath = "";//"DiscoBot\\DSACore\\";
#endif
private static Session s_session;
- public static List<ICharacter> Chars { get; set; } = new List<ICharacter>(); // list of all characters
+ public static List<ICharacter> Chars { get; set; } = new List<ICharacter>(); // list of all characters
public static List<Talent> Talente { get; set; } = new List<Talent>();
@@ -39,10 +35,7 @@ namespace DSACore.DSA_Game
set
{
s_session = value;
- foreach (var x in value.Chars)
- {
- Chars.Find(c => c.Name.Equals(x.Name)).Update(x);
- }
+ foreach (var x in value.Chars) Chars.Find(c => c.Name.Equals(x.Name)).Update(x);
}
}
@@ -61,9 +54,9 @@ namespace DSACore.DSA_Game
}
*/
- Properties.Deserialize(rootPath+"Properties");
+ Properties.Deserialize();
Properties.Serialize(rootPath + "Properties");
-
+
Talente = Talente.OrderBy(x => x.Name).ToList();
Zauber = Zauber.OrderBy(x => x.Name).ToList();
diff --git a/DSACore/DSA_Game/Save/Properties.cs b/DSACore/DSA_Game/Save/Properties.cs
index 459a9c7..7eba911 100644
--- a/DSACore/DSA_Game/Save/Properties.cs
+++ b/DSACore/DSA_Game/Save/Properties.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@@ -8,10 +9,6 @@ using Newtonsoft.Json;
namespace DSACore.DSA_Game.Save
{
- using System.Collections;
- using System.IO;
- using Newtonsoft.Json;
-
public static class Properties
{
public static Dictionary<string, object> objects;
@@ -39,17 +36,13 @@ namespace DSACore.DSA_Game.Save
{
var files = Directory.GetFiles(path, "*.json");
- foreach (string file in files)
- {
+ foreach (var file in files)
try
{
- string name = file.Split('\\').Last().Split('.')[0].Replace('-', '.');
- string data = File.ReadAllText(file);
- Type type = Type.GetType(name);
- if (data.StartsWith("["))
- {
- type = typeof(List<>).MakeGenericType(type);
- }
+ var name = file.Split('\\').Last().Split('.')[0].Replace('-', '.');
+ var data = File.ReadAllText(file);
+ var type = Type.GetType(name);
+ if (data.StartsWith("[")) type = typeof(List<>).MakeGenericType(type);
var o = JsonConvert.DeserializeObject(data, type);
objects.Add(name.Split('.').Last(), o);
@@ -59,7 +52,6 @@ namespace DSACore.DSA_Game.Save
// ignored
Console.WriteLine($"Laden von Save-File {file} fehlgeschlagen." + e);
}
- }
}
public static void Serialize(string path = @"..\..\Properties\")
@@ -68,8 +60,8 @@ namespace DSACore.DSA_Game.Save
{
foreach (var o in objects)
{
- string assembly = o.Value is IList list
- ? ((IList) list)[0]?.GetType().FullName
+ var assembly = o.Value is IList list
+ ? list[0]?.GetType().FullName
: o.Value.GetType().FullName;
var name = path + assembly.Replace('.', '-') + ".json";
@@ -81,7 +73,7 @@ namespace DSACore.DSA_Game.Save
catch (Exception e)
{
// ignored
- Console.WriteLine($"Speichern von Save-File fehlgeschlagen." + e);
+ Console.WriteLine("Speichern von Save-File fehlgeschlagen." + e);
}
}
}
diff --git a/DSACore/DSA_Game/Save/SaveCommand.cs b/DSACore/DSA_Game/Save/SaveCommand.cs
index 198d707..f358047 100644
--- a/DSACore/DSA_Game/Save/SaveCommand.cs
+++ b/DSACore/DSA_Game/Save/SaveCommand.cs
@@ -1,23 +1,21 @@
using System;
+using System.IO;
using System.Linq;
-using System.Threading.Tasks;
namespace DSACore.DSA_Game.Save
{
- using System.IO;
-
- public class SaveCommand
+ public class SaveCommand
{
public void LoadSession(string name = "")
{
if (name.Equals("?") || name.Equals(string.Empty))
{
- Console.WriteLine($"Gespeicherte Sessions:");
- Console.WriteLine(this.ListSessions());
+ Console.WriteLine("Gespeicherte Sessions:");
+ Console.WriteLine(ListSessions());
return;
}
- var path = Save.Session.DirectoryPath + @"\" + name;
+ var path = Session.DirectoryPath + @"\" + name;
var files = Directory.GetFiles(path);
var session = files.OrderByDescending(x => Convert.ToInt32(x.Split('-').Last().Split('.').First())).First();
@@ -32,16 +30,16 @@ namespace DSACore.DSA_Game.Save
if (name.Equals("?") || name.Equals(string.Empty))
{
- Console.WriteLine($"Gespeicherte Sessions:");
- Console.WriteLine(this.ListSessions());
+ Console.WriteLine("Gespeicherte Sessions:");
+ Console.WriteLine(ListSessions());
return;
}
- var path = DSA_Game.Save.Session.DirectoryPath + @"\" + name;
+ var path = Session.DirectoryPath + @"\" + name;
if (Directory.Exists(path))
{
var files = Directory.GetFiles(path);
- int current = files.Max(x => Convert.ToInt32(x.Split('-').Last().Split('.').First()));
+ var current = files.Max(x => Convert.ToInt32(x.Split('-').Last().Split('.').First()));
Dsa.Session.SessionName = name;
Dsa.Session.Save(path + "\\" + name + $"-{++current}.json");
}
@@ -49,7 +47,7 @@ namespace DSACore.DSA_Game.Save
{
Directory.CreateDirectory(path);
Dsa.Session.SessionName = name;
- Dsa.Session.Save(path + "\\" + name + $"-0.json");
+ Dsa.Session.Save(path + "\\" + name + "-0.json");
}
Console.WriteLine($"{name} wurde gespeichert");
@@ -58,13 +56,11 @@ namespace DSACore.DSA_Game.Save
private string[] ListSessions()
{
- string[] dirs = Directory.GetDirectories(Session.DirectoryPath).OrderByDescending(x => new DirectoryInfo(x).LastAccessTime.Ticks).ToArray();
- for (int i = 0; i < dirs.Length; i++)
- {
- dirs[i] += "; " + new DirectoryInfo(dirs[i]).LastAccessTime;
- }
+ 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;
return dirs;
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/DSA_Game/Save/Session.cs b/DSACore/DSA_Game/Save/Session.cs
index b402656..6944fb1 100644
--- a/DSACore/DSA_Game/Save/Session.cs
+++ b/DSACore/DSA_Game/Save/Session.cs
@@ -1,32 +1,34 @@
using System;
using System.Collections.Generic;
+using System.IO;
+using DSACore.DSA_Game.Characters;
+using Newtonsoft.Json;
namespace DSACore.DSA_Game.Save
{
- using System.IO;
- using Characters;
- using Newtonsoft.Json;
-
public class Session
{
public static string DirectoryPath { get; set; } = Dsa.rootPath + @"sessions";
- public Dictionary<string, string> Relation { get; set; } = new Dictionary<string, string>(); // dictionary to match the char
+ public Dictionary<string, string> Relation { get; set; } =
+ new Dictionary<string, string>(); // dictionary to match the char
- public List<SaveChar> Chars { get; set; } = new List<SaveChar>(); // list of all characters
+ public List<SaveChar> Chars { get; set; } = new List<SaveChar>(); // list of all characters
public string SessionName { get; set; }
-
+
public static Session Load(string path)
{
try
{
- return JsonConvert.DeserializeObject<Session>(File.ReadAllText(path)); // Deserialize Data and create Session Object
+ return
+ JsonConvert.DeserializeObject<Session>(
+ File.ReadAllText(path)); // Deserialize Data and create Session Object
}
catch (Exception e)
{
// ignored
- Console.WriteLine($"Laden von Save-File {path} fehlgeschlagen."+ e);
+ Console.WriteLine($"Laden von Save-File {path} fehlgeschlagen." + e);
return null;
}
}
@@ -35,13 +37,15 @@ namespace DSACore.DSA_Game.Save
{
try
{
- File.WriteAllText(path, JsonConvert.SerializeObject(this, Formatting.Indented)); // Deserialize Data and create CommandInfo Struct
+ File.WriteAllText(path,
+ JsonConvert.SerializeObject(this,
+ Formatting.Indented)); // Deserialize Data and create CommandInfo Struct
}
catch (Exception e)
{
- Console.WriteLine($"Speichern von Save-File {path} fehlgeschlagen.\n"+ e);
+ Console.WriteLine($"Speichern von Save-File {path} fehlgeschlagen.\n" + e);
// ignored
}
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/FireBase/Database.cs b/DSACore/FireBase/Database.cs
index 15b76f0..8946cf0 100644
--- a/DSACore/FireBase/Database.cs
+++ b/DSACore/FireBase/Database.cs
@@ -1,14 +1,13 @@
-using DSACore.DSA_Game.Characters;
-using DSACore.Models.Database;
-using Firebase.Database;
-using Firebase.Database.Query;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
+using DSACore.DSA_Game;
+using DSACore.DSA_Game.Characters;
using DSACore.Models.Database.DSA;
-using DSACore.Models.Database.Groups;
-
+using DSACore.Models.Network;
+using Firebase.Database;
+using Firebase.Database.Query;
namespace DSACore.FireBase
{
@@ -16,9 +15,20 @@ namespace DSACore.FireBase
{
public static FirebaseClient firebase;
+ public static Dictionary<string, DatabaseChar> Chars = new Dictionary<string, DatabaseChar>();
+
+ public static Dictionary<string, MeleeWeapon> MeleeList = new Dictionary<string, MeleeWeapon>();
+
+ public static Dictionary<string, RangedWeapon> RangedWeapons = new Dictionary<string, RangedWeapon>();
+
+ public static Dictionary<string, Talent> Talents = new Dictionary<string, Talent>();
+
+ public static Dictionary<string, GeneralSpell> Spells = new Dictionary<string, GeneralSpell>();
+
static Database()
{
- var auth = File.ReadAllText(DSACore.DSA_Game.Dsa.rootPath + "Token"); ; // your app secret
+ var auth = File.ReadAllText(Dsa.rootPath + "Token");
+ ; // your app secret
firebase = new FirebaseClient(
"https://heldenonline-4d828.firebaseio.com/",
new FirebaseOptions
@@ -45,32 +55,19 @@ namespace DSACore.FireBase
.OrderByKey()
.OnceAsync<T>();
- foreach (var firebaseObject in temp)
- {
- list.Add(firebaseObject.Key, firebaseObject.Object);
- }
+ foreach (var firebaseObject in temp) list.Add(firebaseObject.Key, firebaseObject.Object);
}
- public static Dictionary<string,DatabaseChar> Chars = new Dictionary<string, DatabaseChar>();
-
- public static Dictionary<string, MeleeWeapon> MeleeList = new Dictionary<string, MeleeWeapon>();
-
- public static Dictionary<string, RangedWeapon> RangedWeapons = new Dictionary<string, RangedWeapon>();
-
- public static Dictionary<string, Talent> Talents = new Dictionary<string, Talent>();
-
- public static Dictionary<string, GeneralSpell> Spells = new Dictionary<string, GeneralSpell>();
-
- public static async Task<int> AddChar(Character file, Models.Network.Group group)
+ public static async Task<int> AddChar(Character file, Group group)
{
- DatabaseChar.LoadChar(file, out GroupChar groupChar, out DatabaseChar data);
+ DatabaseChar.LoadChar(file, out var groupChar, out var data);
var lastChar = await firebase
.Child("Chars")
.OrderByKey()
.LimitToLast(1)
.OnceAsync<DatabaseChar>();
- int id = groupChar.Id = data.Id = lastChar.First().Object.Id + 1;
+ var id = groupChar.Id = data.Id = lastChar.First().Object.Id + 1;
await firebase //TODO Reomve await Operators
.Child("Groups")
@@ -94,7 +91,6 @@ namespace DSACore.FireBase
public static async Task RemoveChar(int id)
{
-
await firebase
.Child("Groups")
.Child("Char" + id)
@@ -111,7 +107,6 @@ namespace DSACore.FireBase
.Child("Inventories")
.Child("Inventory" + id)
.DeleteAsync();
-
}
public static async Task<DatabaseChar> GetChar(int id)
@@ -158,11 +153,12 @@ namespace DSACore.FireBase
}
public static async Task<Talent> GetTalent(string talent)
- {/*
- return await firebase
- .Child("Talents")
- .Child(talent)
- .OnceSingleAsync<Talent>();*/
+ {
+ /*
+ return await firebase
+ .Child("Talents")
+ .Child(talent)
+ .OnceSingleAsync<Talent>();*/
return Talents[talent];
}
@@ -194,7 +190,7 @@ namespace DSACore.FireBase
public static async Task AddWeapon(Weapon wep)
{
- string collection = wep.GetType() == typeof(MeleeWeapon) ? "MeleeWeapons" : "RangedWeapons";
+ var collection = wep.GetType() == typeof(MeleeWeapon) ? "MeleeWeapons" : "RangedWeapons";
await firebase
.Child(collection)
.Child(wep.Name)
@@ -203,7 +199,7 @@ namespace DSACore.FireBase
public static async Task RemoveWeapon(string weapon, bool ranged = false)
{
- string collection = ranged ? "RangedWeapons" : "MeleeWeapons";
+ var collection = ranged ? "RangedWeapons" : "MeleeWeapons";
await firebase
.Child(collection)
.Child(weapon)
@@ -212,46 +208,44 @@ namespace DSACore.FireBase
public static async Task<Weapon> GetWeapon(string weapon, bool ranged = false)
{
- string collection = ranged ? "RangedWeapons" : "MeleeWeapons";
+ var collection = ranged ? "RangedWeapons" : "MeleeWeapons";
return await firebase
.Child(collection)
.Child(weapon)
.OnceSingleAsync<Weapon>();
}
- public static async Task<List<Models.Network.Group>> GetGroups()
+ public static async Task<List<Group>> GetGroups()
{
var groups = await firebase
.Child("Groups")
.OrderByKey()
- .OnceAsync<Group>();
- var ret = new List<Models.Network.Group>();
+ .OnceAsync<Models.Database.Groups.Group>();
+ var ret = new List<Group>();
foreach (var firebaseObject in groups)
- {
- ret.Add(new Models.Network.Group(firebaseObject.Object.Name, firebaseObject.Object.Password));
- }
+ ret.Add(new Group(firebaseObject.Object.Name, firebaseObject.Object.Password));
return ret;
}
- public static async Task<Group> GetGroup(int id)
+ public static async Task<Models.Database.Groups.Group> GetGroup(int id)
{
var group = await firebase
.Child("Groups")
.Child("Group" + id)
- .OnceSingleAsync<Group>();
+ .OnceSingleAsync<Models.Database.Groups.Group>();
return group;
}
- public static async Task AddGroup(Group group)
+ public static async Task AddGroup(Models.Database.Groups.Group group)
{
var lastChar = await firebase
.Child("Groups")
.OrderByKey()
.LimitToLast(1)
- .OnceAsync<Group>();
- int id = group.Id = lastChar.First().Object.Id + 1;
+ .OnceAsync<Models.Database.Groups.Group>();
+ var id = group.Id = lastChar.First().Object.Id + 1;
await firebase
.Child("Groups")
@@ -259,7 +253,7 @@ namespace DSACore.FireBase
.PutAsync(group);
}
- public static async void SetGroup(Group group)
+ public static async void SetGroup(Models.Database.Groups.Group group)
{
await firebase
.Child("Groups")
@@ -275,4 +269,4 @@ namespace DSACore.FireBase
.DeleteAsync();
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Hubs/Login.cs b/DSACore/Hubs/Login.cs
index 5f984e2..1f6ca39 100644
--- a/DSACore/Hubs/Login.cs
+++ b/DSACore/Hubs/Login.cs
@@ -1,25 +1,22 @@
-using DSACore.DSA_Game.Characters;
-using DSACore.FireBase;
-using DSACore.Models.Network;
-using Microsoft.AspNetCore.SignalR;
-using System;
+using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
-using Microsoft.CodeAnalysis.CSharp.Syntax;
+using DSACore.Commands;
+using DSACore.DSA_Game.Characters;
+using DSACore.FireBase;
+using DSACore.Models.Network;
+using Microsoft.AspNetCore.SignalR;
namespace DSACore.Hubs
{
public class Users : Hub
{
//private static Dictionary<string, User> UserGroup = new Dictionary<string, User>();
-
- private const string ReceiveMethod = "ReceiveMessage";//receiveMethod;
- private static List<Group> DsaGroups {get; set; }
- public static List<Token> Tokens { get;} = new List<Token>();
+ private const string ReceiveMethod = "ReceiveMessage"; //receiveMethod;
static Users()
{
@@ -29,41 +26,41 @@ namespace DSACore.Hubs
//AddGroups();
}
-
+ private static List<Group> DsaGroups { get; }
+ public static List<Token> Tokens { get; } = new List<Token>();
+
+
[Obsolete]
private static async void AddGroups()
{
- await Database.AddGroup(new Models.Database.Groups.Group { Name = "HalloWelt", Password = "valid" });
- await Database.AddGroup(new Models.Database.Groups.Group { Name = "Die Krassen Gamer", Password = "valid" });
- await Database.AddGroup(new Models.Database.Groups.Group { Name = "DSA", Password = "valid" });
- await Database.AddGroup(new Models.Database.Groups.Group { Name = "Die Überhelden", Password = "valid" });
+ await Database.AddGroup(new Models.Database.Groups.Group {Name = "HalloWelt", Password = "valid"});
+ await Database.AddGroup(new Models.Database.Groups.Group {Name = "Die Krassen Gamer", Password = "valid"});
+ await Database.AddGroup(new Models.Database.Groups.Group {Name = "DSA", Password = "valid"});
+ await Database.AddGroup(new Models.Database.Groups.Group {Name = "Die Überhelden", Password = "valid"});
}
public async Task SendMessage(string user, string message)
{
try
{
- string group = getGroup(Context.ConnectionId).Name;
+ var group = getGroup(Context.ConnectionId).Name;
}
catch (InvalidOperationException e)
{
//await Clients.Caller.SendCoreAsync(receiveMethod,
- // new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" });
+ // new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" });
}
if (message[0] == '/')
{
var args = message.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
- bool Timon = args.Any(x => x == "hallo");
+ var Timon = args.Any(x => x == "hallo");
var ident = args.First().Replace("/", "");
- if (args.Count > 0)
- {
- args.RemoveAt(0);
- }
+ if (args.Count > 0) args.RemoveAt(0);
- var ret = Commands.CommandHandler.ExecuteCommand(new Command
+ var ret = CommandHandler.ExecuteCommand(new Command
{
CharId = 0,
CmdIdentifier = ident,
@@ -81,63 +78,57 @@ namespace DSACore.Hubs
await SendToGroup(ret.message);
break;
}
-
-
}
else
{
await SendToGroup(message);
}
-
}
private Task SendToGroup(string message)
{
try
{
- string group = getGroup(Context.ConnectionId).Name;
+ var group = getGroup(Context.ConnectionId).Name;
return Clients.Group(group).SendCoreAsync(ReceiveMethod,
new object[] {getUser(Context.ConnectionId).Name, message});
}
catch (InvalidOperationException e)
{
return Clients.Caller.SendCoreAsync(ReceiveMethod,
- new object[] { "Nutzer ist in keiner Gruppe. Erst joinen!" });
+ new object[] {"Nutzer ist in keiner Gruppe. Erst joinen!"});
}
}
- private Models.Network.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)
{
- return DsaGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))).Users.First(z => z.ConnectionId.Equals(id));
+ return DsaGroups.First(x => x.Users.Exists(y => y.ConnectionId.Equals(id))).Users
+ .First(z => z.ConnectionId.Equals(id));
}
public async Task GetGroups()
{
var test = await Database.GetGroups();
-
+
foreach (var group in test)
- {
if (!DsaGroups.Exists(x => x.Name.Equals(group.Name)))
- {
DsaGroups.Add(group);
- }
- }
- await Clients.Caller.SendCoreAsync("ListGroups", new object[] { DsaGroups.Select(x => x.SendGroup()) });
+ await Clients.Caller.SendCoreAsync("ListGroups", new object[] {DsaGroups.Select(x => x.SendGroup())});
//throw new NotImplementedException("add database call to get groups");
}
public async Task AddGroup(string group, string password)
{
DsaGroups.Add(new Group(group, password));
- var Dgroup = new Models.Database.Groups.Group { Name = group, Id = DsaGroups.Count - 1 };
+ var Dgroup = new Models.Database.Groups.Group {Name = group, Id = DsaGroups.Count - 1};
//Database.AddGroup(Dgroup);
- await Clients.Caller.SendCoreAsync(ReceiveMethod, new[] { $"group {@group} sucessfully added" });
+ await Clients.Caller.SendCoreAsync(ReceiveMethod, new[] {$"group {group} sucessfully added"});
//throw new NotImplementedException("add database call to add groups");
}
@@ -159,7 +150,7 @@ namespace DSACore.Hubs
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "login");
await Groups.AddToGroupAsync(Context.ConnectionId, group);
- gGroup.Users.Add(new User { ConnectionId = Context.ConnectionId, Name = user });
+ gGroup.Users.Add(new User {ConnectionId = Context.ConnectionId, Name = user});
await SendToGroup("Ein neuer Nutzer hat die Gruppe betreten");
await Clients.Caller.SendAsync("LoginResponse", 0);
await Clients.Caller.SendAsync("PlayerStatusChanged", new[] {user, "online"});
@@ -202,7 +193,6 @@ namespace DSACore.Hubs
{
await Groups.RemoveFromGroupAsync(Context.ConnectionId, "online");
if (DsaGroups.Exists(x => x.Users.Exists(y => y.ConnectionId == Context.ConnectionId)))
- {
try
{
var group = getGroup(Context.ConnectionId);
@@ -210,7 +200,7 @@ namespace DSACore.Hubs
var user = getUser(Context.ConnectionId);
- await Clients.Caller.SendAsync("PlayerStatusChanged", new[] { user.Name, "offline" });
+ await Clients.Caller.SendAsync("PlayerStatusChanged", new[] {user.Name, "offline"});
//await SendToGroup(user.Name + " disconnected from the Server");
group.Users.Remove(user);
await Groups.RemoveFromGroupAsync(Context.ConnectionId, group.Name);
@@ -220,9 +210,6 @@ namespace DSACore.Hubs
Console.WriteLine(e);
//throw;
}
- }
-
}
-
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/Advantage.cs b/DSACore/Models/Database/DSA/Advantage.cs
index 2f0b443..cc8f5cc 100644
--- a/DSACore/Models/Database/DSA/Advantage.cs
+++ b/DSACore/Models/Database/DSA/Advantage.cs
@@ -13,4 +13,4 @@ namespace DSACore.Models.Database.DSA
public string Name { get; set; }
public string Value { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/CharSpell.cs b/DSACore/Models/Database/DSA/CharSpell.cs
index 63d917a..fabd456 100644
--- a/DSACore/Models/Database/DSA/CharSpell.cs
+++ b/DSACore/Models/Database/DSA/CharSpell.cs
@@ -13,4 +13,4 @@ namespace DSACore.Models.Database.DSA
public string representation { get; set; }
public int value { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/DatabaseChar.cs b/DSACore/Models/Database/DSA/DatabaseChar.cs
index 8c51821..872b82e 100644
--- a/DSACore/Models/Database/DSA/DatabaseChar.cs
+++ b/DSACore/Models/Database/DSA/DatabaseChar.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using DSACore.DSA_Game.Characters;
namespace DSACore.Models.Database.DSA
{
@@ -10,7 +11,8 @@ namespace DSACore.Models.Database.DSA
{
}
- public DatabaseChar(int id, string name, string rasse, List<Field> skills, List<Field> talents, List<Advantage> advantages, List<CharSpell> spells, List<WeaponTalent> weaponTalents)
+ public DatabaseChar(int id, string name, string rasse, List<Field> skills, List<Field> talents,
+ List<Advantage> advantages, List<CharSpell> spells, List<WeaponTalent> weaponTalents)
{
Id = id;
Name = name ?? throw new ArgumentNullException(nameof(name));
@@ -39,7 +41,7 @@ namespace DSACore.Models.Database.DSA
public List<WeaponTalent> WeaponTalents { get; set; } = new List<WeaponTalent>();
- public static void LoadChar(DSA_Game.Characters.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();
@@ -58,4 +60,4 @@ namespace DSACore.Models.Database.DSA
data.WeaponTalents = file.Kampftalente.Select(x => new WeaponTalent(x.Name, x.At, x.Pa)).ToList();
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/Field.cs b/DSACore/Models/Database/DSA/Field.cs
index 5022768..e63aeb4 100644
--- a/DSACore/Models/Database/DSA/Field.cs
+++ b/DSACore/Models/Database/DSA/Field.cs
@@ -7,10 +7,10 @@ namespace DSACore.Models.Database.DSA
public Field(string name, int value = 0)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
- this.Value = value;
+ Value = value;
}
public string Name { get; set; }
public int Value { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/GeneralSpell.cs b/DSACore/Models/Database/DSA/GeneralSpell.cs
index 74b95d7..b4dbc0b 100644
--- a/DSACore/Models/Database/DSA/GeneralSpell.cs
+++ b/DSACore/Models/Database/DSA/GeneralSpell.cs
@@ -4,7 +4,7 @@
{
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;
}
@@ -17,4 +17,4 @@
{
}
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/GroupChar.cs b/DSACore/Models/Database/DSA/GroupChar.cs
index 70b8fc1..31fc583 100644
--- a/DSACore/Models/Database/DSA/GroupChar.cs
+++ b/DSACore/Models/Database/DSA/GroupChar.cs
@@ -10,4 +10,4 @@
public int AsMax { get; set; }
public Weapon Weapon { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/Inventory.cs b/DSACore/Models/Database/DSA/Inventory.cs
index 69c7b08..9a025d4 100644
--- a/DSACore/Models/Database/DSA/Inventory.cs
+++ b/DSACore/Models/Database/DSA/Inventory.cs
@@ -9,4 +9,4 @@ namespace DSACore.Models.Database.DSA
public Dictionary<string, bool> Food { get; set; } = new Dictionary<string, bool>();
public List<Weapon> Weapons { get; set; } = new List<Weapon>();
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/Talent.cs b/DSACore/Models/Database/DSA/Talent.cs
index a6de395..59ff4bc 100644
--- a/DSACore/Models/Database/DSA/Talent.cs
+++ b/DSACore/Models/Database/DSA/Talent.cs
@@ -13,7 +13,7 @@ namespace DSACore.Models.Database.DSA
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('/');
@@ -23,4 +23,4 @@ namespace DSACore.Models.Database.DSA
public string[] Roll { get; set; } = new string[3];
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/Weapon.cs b/DSACore/Models/Database/DSA/Weapon.cs
index 24b334a..58a44cd 100644
--- a/DSACore/Models/Database/DSA/Weapon.cs
+++ b/DSACore/Models/Database/DSA/Weapon.cs
@@ -26,25 +26,27 @@ namespace DSACore.Models.Database.DSA
public class MeleeWeapon : Weapon
{
+ public MeleeWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name,
+ damage, weight, weaponTalent, price)
+ {
+ }
+
public string TpKK { get; set; }
public int INI { get; set; }
public string MW { get; set; }
-
- public MeleeWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, damage, weight, weaponTalent, price)
- {
- }
}
public class RangedWeapon : Weapon
{
+ public RangedWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name,
+ damage, weight, weaponTalent, price)
+ {
+ }
+
public int AtMod { get; set; }
public int KKMod { get; set; }
public string AtReach { get; set; }
public string TpReach { get; set; }
public int LoadTime { get; set; }
-
- public RangedWeapon(string name, string damage, int weight, string weaponTalent, string price) : base(name, damage, weight, weaponTalent, price)
- {
- }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Database/DSA/WeaponTalent.cs b/DSACore/Models/Database/DSA/WeaponTalent.cs
index 869cb35..98eb38d 100644
--- a/DSACore/Models/Database/DSA/WeaponTalent.cs
+++ b/DSACore/Models/Database/DSA/WeaponTalent.cs
@@ -2,7 +2,7 @@
namespace DSACore.Models.Database.DSA
{
- public class WeaponTalent
+ public class WeaponTalent
{
public WeaponTalent(string name, int at, int pa)
{
diff --git a/DSACore/Models/Database/Groups/DSAGroup.cs b/DSACore/Models/Database/Groups/DSAGroup.cs
index 8f20278..89fac2f 100644
--- a/DSACore/Models/Database/Groups/DSAGroup.cs
+++ b/DSACore/Models/Database/Groups/DSAGroup.cs
@@ -5,6 +5,6 @@ namespace DSACore.Models.Database.Groups
{
public class DSAGroup : Group
{
- public List<GroupChar> Chars { get; set; }= new List<GroupChar>();
+ public List<GroupChar> Chars { get; set; } = new List<GroupChar>();
}
} \ No newline at end of file
diff --git a/DSACore/Models/Database/Groups/Group.cs b/DSACore/Models/Database/Groups/Group.cs
index 23e5f68..77d3a64 100644
--- a/DSACore/Models/Database/Groups/Group.cs
+++ b/DSACore/Models/Database/Groups/Group.cs
@@ -6,8 +6,5 @@
public string Discord { get; set; }
public string Password { get; set; }
public int Id { get; set; }
-
}
-
-
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Network/Command.cs b/DSACore/Models/Network/Command.cs
index 456a896..00b00a6 100644
--- a/DSACore/Models/Network/Command.cs
+++ b/DSACore/Models/Network/Command.cs
@@ -1,7 +1,5 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.Linq;
-using System.Threading.Tasks;
namespace DSACore.Models.Network
{
@@ -14,7 +12,7 @@ namespace DSACore.Models.Network
public List<string> CmdTexts { get; set; }
public string CmdText => CmdTexts.Count != 0 ? CmdTexts.First() : "";
- public int Cmdmodifier => CmdTexts.Count != 0 && int.TryParse(CmdTexts.Last(), out int mod) ? mod : 0;
+ public int Cmdmodifier => CmdTexts.Count != 0 && int.TryParse(CmdTexts.Last(), out var mod) ? mod : 0;
public bool IsDm { get; set; } = false;
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Network/CommandResponse.cs b/DSACore/Models/Network/CommandResponse.cs
index ed4b7d0..c7a410a 100644
--- a/DSACore/Models/Network/CommandResponse.cs
+++ b/DSACore/Models/Network/CommandResponse.cs
@@ -1,20 +1,17 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
namespace DSACore.Models.Network
{
public class CommandResponse
{
- public CommandResponse(string message, ResponseType responseType= ResponseType.Broadcast)
+ public CommandResponse(string message, ResponseType responseType = ResponseType.Broadcast)
{
this.message = message ?? throw new ArgumentNullException(nameof(message));
ResponseType = responseType;
}
- public string message { get; private set; }
- public ResponseType ResponseType { get; private set;}
+ public string message { get; }
+ public ResponseType ResponseType { get; }
public override string ToString()
{
@@ -28,4 +25,4 @@ namespace DSACore.Models.Network
Caller,
Error
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Network/Group.cs b/DSACore/Models/Network/Group.cs
index 76c3efb..efe12ee 100644
--- a/DSACore/Models/Network/Group.cs
+++ b/DSACore/Models/Network/Group.cs
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
namespace DSACore.Models.Network
{
@@ -22,14 +20,11 @@ namespace DSACore.Models.Network
public string Password { get; set; }
public List<User> Users { get; set; } = new List<User>();
- public int UserCount
- {
- get { return Users.Count; }
- }
+ public int UserCount => Users.Count;
public SendGroup SendGroup()
{
- return new SendGroup( Name, UserCount);
+ return new SendGroup(Name, UserCount);
}
}
@@ -44,6 +39,5 @@ namespace DSACore.Models.Network
public string Name { get; set; }
public int UserCount { get; set; }
-
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Models/Network/Token.cs b/DSACore/Models/Network/Token.cs
index 0021317..451cafc 100644
--- a/DSACore/Models/Network/Token.cs
+++ b/DSACore/Models/Network/Token.cs
@@ -1,18 +1,18 @@
using System;
-using Microsoft.EntityFrameworkCore;
namespace DSACore.Models.Network
{
public class Token
{
- public string Group { get; set; }
- private DateTime creation = DateTime.Now;
+ private readonly DateTime creation = DateTime.Now;
- public Token(string @group)
+ public Token(string group)
{
- Group = @group;
+ Group = group;
}
+ public string Group { get; set; }
+
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 04ef0a9..8b8008c 100644
--- a/DSACore/Models/Network/User.cs
+++ b/DSACore/Models/Network/User.cs
@@ -1,9 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
-
-namespace DSACore.Models.Network
+namespace DSACore.Models.Network
{
public class User
{
@@ -11,4 +6,4 @@ namespace DSACore.Models.Network
public string ConnectionId { get; set; }
public int Char { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Program.cs b/DSACore/Program.cs
index d8cb67c..46baf2d 100644
--- a/DSACore/Program.cs
+++ b/DSACore/Program.cs
@@ -1,13 +1,7 @@
-using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Threading.Tasks;
+using DSACore.DSA_Game;
using DSACore.FireBase;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.Logging;
namespace DSACore
{
@@ -16,14 +10,15 @@ namespace DSACore
public static void Main(string[] args)
{
Database.GetGroup(0).Wait();
- DSA_Game.Dsa.Startup();
+ Dsa.Startup();
CreateWebHostBuilder(args).Build().Run();
}
- public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
+ public static IWebHostBuilder CreateWebHostBuilder(string[] args)
+ {
+ return WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseUrls("http://0.0.0.0:5000");
-
+ }
}
-}
+} \ No newline at end of file
diff --git a/DSACore/Startup.cs b/DSACore/Startup.cs
index 1dcc690..372caca 100644
--- a/DSACore/Startup.cs
+++ b/DSACore/Startup.cs
@@ -1,16 +1,9 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
+using DSACore.Hubs;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
-using DSACore.Hubs;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
-using Microsoft.Extensions.Options;
namespace DSACore
{
@@ -52,23 +45,19 @@ namespace DSACore
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
- {
app.UseDeveloperExceptionPage();
- }
else
- {
app.UseHsts();
- }
app.UseCors("CorsPolicy");
app.UseSignalR(routes => { routes.MapHub<Users>("/login"); });
app.UseWebSockets();
-
- //app.UseCors("AllowSpecificOrigin");
+
+ //app.UseCors("AllowSpecificOrigin");
app.UseHttpsRedirection();
app.UseMvc();
}
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Characters/Being.cs b/DSALib/Characters/Being.cs
index 7ac7341..27879a1 100644
--- a/DSALib/Characters/Being.cs
+++ b/DSALib/Characters/Being.cs
@@ -1,6 +1,4 @@
-using DiscoBot.DSA_Game.Characters;
-
-namespace DSALib.Characters
+namespace DSALib.Characters
{
public class Being : Entity
{
@@ -16,4 +14,4 @@ namespace DSALib.Characters
public int Astralpunkte_Aktuell { get; set; } = 0;
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Characters/Critter.cs b/DSALib/Characters/Critter.cs
index 8092101..d9f8b53 100644
--- a/DSALib/Characters/Critter.cs
+++ b/DSALib/Characters/Critter.cs
@@ -1,16 +1,32 @@
using System;
using System.Collections.Generic;
+using System.IO;
+using DiscoBot.DSA_Game.Characters;
+using Newtonsoft.Json;
namespace DSALib.Characters
{
- using System.IO;
+ public class Critter : Being, ICombatant
+ {
+ public CritterAttack lastAttack;
- using DiscoBot.DSA_Game.Characters;
+ public Critter(int gw, int gs, int rs, int mr, int ko, int pa, string ini, List<CritterAttack> critterAttacks)
+ {
+ Gw = gw;
+ Gs = gs;
+ Rs = rs;
+ Mr = mr;
+ Ko = ko;
+ Pa = pa;
+ Ini = ini;
+ CritterAttacks = critterAttacks;
+ lastAttack = CritterAttacks[new Random().Next(critterAttacks.Count)];
+ }
- using Newtonsoft.Json;
+ public Critter()
+ {
+ }
- public class Critter : Being, ICombatant
- {
public int Rs { get; set; }
public int Mr { get; set; }
@@ -29,30 +45,23 @@ namespace DSALib.Characters
public List<CritterAttack> CritterAttacks { get; set; }
- public CritterAttack lastAttack;
-
- public Critter(int gw, int gs, int rs, int mr, int ko, int pa, string ini, List<CritterAttack> critterAttacks)
+ public string Angriff(string talent, int erschwernis = 0)
{
- this.Gw = gw;
- this.Gs = gs;
- this.Rs = rs;
- this.Mr = mr;
- this.Ko = ko;
- this.Pa = pa;
- this.Ini = ini;
- this.CritterAttacks = critterAttacks;
- this.lastAttack = this.CritterAttacks[new Random().Next(critterAttacks.Count)];
+ throw new NotImplementedException();
}
- public Critter()
+ public string Parade(string talent, int erschwernis = 0)
{
+ throw new NotImplementedException();
}
public static Critter Load(string path)
{
try
{
- return JsonConvert.DeserializeObject<Critter>(File.ReadAllText(path)); // Deserialize Data and create Session Object
+ return
+ JsonConvert.DeserializeObject<Critter>(
+ File.ReadAllText(path)); // Deserialize Data and create Session Object
}
catch (Exception e)
{
@@ -61,21 +70,13 @@ namespace DSALib.Characters
}
}
- public string Angriff(string talent, int erschwernis = 0)
- {
- throw new NotImplementedException();
- }
-
- public string Parade(string talent, int erschwernis = 0)
- {
- throw new NotImplementedException();
- }
-
public void Save(string path = @"..\..\Critters\")
{
try
{
- File.WriteAllText(path + this.Name + ".json", JsonConvert.SerializeObject(this, Formatting.Indented)); // Deserialize Data and create CommandInfo Struct
+ File.WriteAllText(path + Name + ".json",
+ JsonConvert.SerializeObject(this,
+ Formatting.Indented)); // Deserialize Data and create CommandInfo Struct
}
catch (Exception e)
{
@@ -83,4 +84,4 @@ namespace DSALib.Characters
}
}
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Characters/Entity.cs b/DSALib/Characters/Entity.cs
index 6b03e50..a8a5e81 100644
--- a/DSALib/Characters/Entity.cs
+++ b/DSALib/Characters/Entity.cs
@@ -6,7 +6,7 @@
public override string ToString()
{
- return this.Name;
+ return Name;
}
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Characters/ICharacter.cs b/DSALib/Characters/ICharacter.cs
index 83b53bf..256fecd 100644
--- a/DSALib/Characters/ICharacter.cs
+++ b/DSALib/Characters/ICharacter.cs
@@ -12,4 +12,4 @@ namespace DSALib.Characters
string TestZauber(string waffe, int erschwernis);
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Characters/ICombatant.cs b/DSALib/Characters/ICombatant.cs
index a99bff9..a4ce601 100644
--- a/DSALib/Characters/ICombatant.cs
+++ b/DSALib/Characters/ICombatant.cs
@@ -1,10 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.DSA_Game.Characters
+namespace DiscoBot.DSA_Game.Characters
{
public interface ICombatant
{
@@ -18,9 +12,9 @@ namespace DiscoBot.DSA_Game.Characters
int Astralpunkte_Basis { get; set; }
int Astralpunkte_Aktuell { get; set; }
-
+
string Angriff(string talent, int erschwernis = 0);
string Parade(string talent, int erschwernis = 0);
}
-}
+} \ No newline at end of file
diff --git a/DSALib/CritterAttack.cs b/DSALib/CritterAttack.cs
index 0ad4a66..3b0a11d 100644
--- a/DSALib/CritterAttack.cs
+++ b/DSALib/CritterAttack.cs
@@ -1,19 +1,13 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DSALib
+namespace DSALib
{
public class CritterAttack
{
public CritterAttack(string name, int at, string tp, string comment = "")
{
- this.Name = name;
- this.At = at;
- this.Tp = tp;
- this.Comment = comment;
+ Name = name;
+ At = at;
+ Tp = tp;
+ Comment = comment;
}
public string Name { get; set; }
@@ -24,4 +18,4 @@ namespace DSALib
public string Comment { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSALib/KampfTalent.cs b/DSALib/KampfTalent.cs
index 7e4e9be..7c7eed4 100644
--- a/DSALib/KampfTalent.cs
+++ b/DSALib/KampfTalent.cs
@@ -4,9 +4,9 @@
{
public KampfTalent(string name, int at, int pa)
{
- this.Name = name;
- this.At = at;
- this.Pa = pa;
+ Name = name;
+ At = at;
+ Pa = pa;
}
public string Name { get; set; }
@@ -15,4 +15,4 @@
public int Pa { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Talent.cs b/DSALib/Talent.cs
index bf1e52d..a39709c 100644
--- a/DSALib/Talent.cs
+++ b/DSALib/Talent.cs
@@ -4,9 +4,9 @@
{
public Talent(string name, string probe, int value)
{
- this.Name = name;
- this.Probe = probe;
- this.Value = value;
+ Name = name;
+ Probe = probe;
+ Value = value;
}
public string Name { get; set; }
@@ -14,18 +14,15 @@
public string Probe { get; set; }
public int Value { get; set; }
-
+
public string[] GetEigenschaften() // turn XX/XX/XX into string[]{XX,XX,XX}
{
- var temp = this.Probe.Split('/');
- for (var index = 0; index < temp.Length; index++)
- {
- temp[index] = temp[index].Replace("/", string.Empty);
- }
+ var temp = Probe.Split('/');
+ for (var index = 0; index < temp.Length; index++) temp[index] = temp[index].Replace("/", string.Empty);
return temp;
}
-
+
public bool IstFernkampftalent()
{
switch (Name)
@@ -45,4 +42,4 @@
}
}
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Vorteil.cs b/DSALib/Vorteil.cs
index bf698d8..c239676 100644
--- a/DSALib/Vorteil.cs
+++ b/DSALib/Vorteil.cs
@@ -4,9 +4,9 @@
{
public Vorteil(string name, string value = "")
{
- this.Name = name;
- this.Value = value;
- // this.Choice = choice;
+ Name = name;
+ Value = value;
+ // this.Choice = choice;
}
public string Name { get; set; }
@@ -15,4 +15,4 @@
//public string Choice { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/DSALib/Zauber.cs b/DSALib/Zauber.cs
index 3c7533f..0f460a1 100644
--- a/DSALib/Zauber.cs
+++ b/DSALib/Zauber.cs
@@ -5,12 +5,12 @@
public Zauber(string name, string probe, int value, char complexity = 'A', string representation = "Magier")
: base(name, probe, value)
{
- this.Complexity = complexity;
- this.Representation = this.Representation;
+ Complexity = complexity;
+ Representation = Representation;
}
public char Complexity { get; }
public string Representation { get; }
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Audio/AudioModule.cs b/DiscoBot/Audio/AudioModule.cs
index f8834f3..add4bf0 100644
--- a/DiscoBot/Audio/AudioModule.cs
+++ b/DiscoBot/Audio/AudioModule.cs
@@ -1,33 +1,21 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Security.Cryptography;
-using System.Threading.Tasks;
-
-using DiscoBot;
-using DiscoBot.Audio;
-using DiscoBot.Auxiliary;
-using DiscoBot.Commands;
-
+using System.Threading.Tasks;
using Discord;
using Discord.Commands;
namespace DiscoBot.Audio
{
- using DiscoBot.DSA_Game;
-
public class AudioModule : ModuleBase
{
// Scroll down further for the AudioService.
// Like, way down
- private readonly AudioService _service;
+ private readonly AudioService service;
// Remember to add an instance of the AudioService
// to your IServiceCollection when you initialize your bot
public AudioModule(AudioService service)
{
- _service = service;
- Dsa.Service = service;
+ this.service = service;
+ //Dsa.Service = service;
}
// You *MUST* mark these commands with 'RunMode.Async'
@@ -35,7 +23,7 @@ namespace DiscoBot.Audio
[Command("_join", RunMode = RunMode.Async)]
public async Task JoinCmd()
{
- await _service.JoinAudio(Context.Guild, (Context.User as IVoiceState).VoiceChannel);
+ await service.JoinAudio(Context.Guild, (Context.User as IVoiceState).VoiceChannel);
}
// Remember to add preconditions to your commands,
@@ -44,13 +32,13 @@ namespace DiscoBot.Audio
[Command("_leave", RunMode = RunMode.Async)]
public async Task LeaveCmd()
{
- await _service.LeaveAudio(Context.Guild);
+ await service.LeaveAudio(Context.Guild);
}
[Command("_play", RunMode = RunMode.Async)]
public async Task PlayCmd([Remainder] string song)
{
- if (Dsa.GeneralContext == null)
+ /*if (Dsa.GeneralContext == null)
{
Dsa.GeneralContext = this.Context;
}
@@ -71,7 +59,7 @@ namespace DiscoBot.Audio
await _service.SendAudioAsync(Context.Guild, Context.Channel, song);
}
- SoundEffects.Play(song);
+ SoundEffects.Play(song);*/
}
}
} \ No newline at end of file
diff --git a/DiscoBot/Audio/AudioService.cs b/DiscoBot/Audio/AudioService.cs
index 6e01980..a198eb2 100644
--- a/DiscoBot/Audio/AudioService.cs
+++ b/DiscoBot/Audio/AudioService.cs
@@ -1,34 +1,27 @@
-namespace DiscoBot.Audio
-{
- using System.Collections.Concurrent;
- using System.Diagnostics;
- using System.IO;
- using System.Threading.Tasks;
-
- using DiscoBot.DSA_Game;
-
- using Discord;
- using Discord.Audio;
+using System;
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.IO;
+using System.Threading.Tasks;
+using Discord;
+using Discord.Audio;
+namespace DiscoBot.Audio
+{
public class AudioService
{
- private readonly ConcurrentDictionary<ulong, IAudioClient> connectedChannels = new ConcurrentDictionary<ulong, IAudioClient>();
+ private readonly ConcurrentDictionary<ulong, IAudioClient> connectedChannels =
+ new ConcurrentDictionary<ulong, IAudioClient>();
public async Task JoinAudio(IGuild guild, IVoiceChannel target)
{
- if (this.connectedChannels.TryGetValue(guild.Id, out var client))
- {
- return;
- }
+ if (connectedChannels.TryGetValue(guild.Id, out var client)) return;
- if (target.Guild.Id != guild.Id)
- {
- return;
- }
+ if (target.Guild.Id != guild.Id) return;
var audioClient = await target.ConnectAsync();
- if (this.connectedChannels.TryAdd(guild.Id, audioClient))
+ if (connectedChannels.TryAdd(guild.Id, audioClient))
{
// If you add a method to log happenings from this service,
// you can uncomment these commented lines to make use of that.
@@ -38,11 +31,9 @@
public async Task LeaveAudio(IGuild guild)
{
- if (this.connectedChannels.TryRemove(guild.Id, out var client))
- {
+ if (connectedChannels.TryRemove(guild.Id, out var client))
await client.StopAsync();
- //await Log(LogSeverity.Info, $"Disconnected from voice on {guild.Name}.");
- }
+ //await Log(LogSeverity.Info, $"Disconnected from voice on {guild.Name}.");
}
public async Task SendAudioAsync(IGuild guild, IMessageChannel channel, string path)
@@ -54,28 +45,31 @@
return;
}
- if (this.connectedChannels.TryGetValue(guild.Id, out var client))
- {
+ if (connectedChannels.TryGetValue(guild.Id, out var client))
//await Log(LogSeverity.Debug, $"Starting playback of {path} in {guild.Name}");
- using (var ffmpeg = this.CreateStream(path))
+ using (var ffmpeg = CreateStream(path))
using (var stream = client.CreatePCMStream(AudioApplication.Music))
{
- try { await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream); }
- finally { await stream.FlushAsync(); }
+ try
+ {
+ await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream);
+ }
+ finally
+ {
+ await stream.FlushAsync();
+ }
}
- }
}
- public async Task SendAudioAsync(string path, int Volume)
+ public async Task SendAudioAsync(string path, int volume)
{
// Your task: Get a full path to the file if the value of 'path' is only a filename.
if (!File.Exists(path) && false)
- {
//await channel.SendMessageAsync("File does not exist.");
return;
- }
- if (this.connectedChannels.TryGetValue(Dsa.GeneralContext.Guild.Id, out var client))
+ throw new NotImplementedException("get channel data from server");
+ /*if (this.connectedChannels.TryGetValue())
{
//await Log(LogSeverity.Debug, $"Starting playback of {path} in {guild.Name}");
using (var ffmpeg = this.CreateStream(path))
@@ -84,10 +78,10 @@
try { await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream); }
finally { await stream.FlushAsync(); }
}
- }
+ }*/
}
- private Process CreateStream(string path)
+ private static Process CreateStream(string path)
{
return Process.Start(new ProcessStartInfo
{
@@ -98,4 +92,4 @@
});
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Audio/Sound.cs b/DiscoBot/Audio/Sound.cs
index a9a2768..85023c8 100644
--- a/DiscoBot/Audio/Sound.cs
+++ b/DiscoBot/Audio/Sound.cs
@@ -1,18 +1,12 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.Audio
+namespace DiscoBot.Audio
{
public class Sound
{
public Sound(string name, string url, int volume)
{
- this.Name = name;
- this.Url = url;
- this.Volume = volume;
+ Name = name;
+ Url = url;
+ Volume = volume;
}
public string Name { get; }
@@ -21,4 +15,4 @@ namespace DiscoBot.Audio
public int Volume { get; }
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Audio/Soundeffects.cs b/DiscoBot/Audio/Soundeffects.cs
deleted file mode 100644
index f3a014c..0000000
--- a/DiscoBot/Audio/Soundeffects.cs
+++ /dev/null
@@ -1,93 +0,0 @@
-namespace DiscoBot.Audio
-{
- using System;
- using System.Linq;
- using System.Threading.Tasks;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.Commands;
- using DiscoBot.DSA_Game;
-
- /*public enum Sound
- {
- Bell,
- Ding,
- Nooo,
- Monsterkill,
- Finish,
- Wrong,
- Magic,
- Stupid,
- Police,
- Roblox
- }*/
-
- public static class SoundEffects
- {
- public static int MaxVolume { get; set; } = 50;
-
- public static void Play(string s)
- {
- string url = string.Empty;
- int volume = 255;
-
- var tSound = DSA_Game.Save.Properties.Sounds.OrderBy(x => SpellCorrect.CompareEasy(s, x.Name)).First();
-
- url = s;
-
- switch (s)
- {
- case "Bell":
- case "Ding":
- url = "https://www.myinstants.com/media/sounds/boxing-bell.mp3";
- break;
- case "Finish":
- url = "https://www.myinstants.com/media/sounds/finishhim.swf.mp3";
- break;
- case "Magic":
- url = "https://www.myinstants.com/media/sounds/dream-harp-sound-effect.mp3";
- break;
- case "Monsterkill":
- url = "https://www.myinstants.com/media/sounds/announcer_kill_monster_01.mp3";
- break;
- case "Nooo":
- url = "https://www.myinstants.com/media/sounds/nooo.swf.mp3";
- break;
- case "Roblox":
- url = "https://www.myinstants.com/media/sounds/roblox-death-sound_ytkBL7X.mp3";
- break;
- case "Stupid":
- url = "https://www.myinstants.com/media/sounds/stupid_dum_03.mp3";
- volume = 10;
- break;
- case "Police":
- url = "https://www.myinstants.com/media/sounds/sound-of-the-police.mp3";
- break;
- case "Wrong":
- url = "https://www.myinstants.com/media/sounds/wrong-answer-sound-effect.mp3";
- volume = 50;
- break;
- }
-
-
-
- if (SpellCorrect.CompareEasy(s, tSound.Name) < SpellCorrect.ErrorThreshold)
- {
- url = tSound.Url;
- volume = tSound.Volume;
- }
-
- volume = (int)(volume * (MaxVolume / 100.0));
-
-
- if (url != string.Empty)
- {
- // await Dsa.Service.SendAudioAsync(url, vol);
- Voice.Send(url, volume);
- return;
- }
-
- throw new Exception("Ton Existiert nicht");
- }
- }
-}
diff --git a/DiscoBot/Audio/Voice.cs b/DiscoBot/Audio/Voice.cs
index 379f65b..c2a3097 100644
--- a/DiscoBot/Audio/Voice.cs
+++ b/DiscoBot/Audio/Voice.cs
@@ -1,42 +1,34 @@
-namespace DiscoBot.Audio
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Threading.Tasks;
+using DiscoBot.Auxiliary;
+using Discord;
+using Discord.Audio;
+using Discord.Commands;
+
+namespace DiscoBot.Audio
{
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Linq;
- using System.Threading.Tasks;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game;
-
- using Discord;
- using Discord.Audio;
- using Discord.Commands;
- using Discord.WebSocket;
-
public class Voice : ModuleBase
{
public static IAudioClient Client { get; set; }
public static void Send(string path, int volume = 256)
{
- if (Client == null)
- {
- throw new NullReferenceException("Bot befindet sich nicht in einem Sprachchannel");
- }
+ if (Client == null) throw new NullReferenceException("Bot befindet sich nicht in einem Sprachchannel");
// Create FFmpeg using the previous example
var ffmpeg = CreateStream(path, volume);
var output = ffmpeg.StandardOutput.BaseStream;
var barInvoker = new BackgroundWorker();
barInvoker.DoWork += delegate
- {
- var discord = Client.CreatePCMStream(AudioApplication.Music);
- output.CopyToAsync(discord);
+ {
+ var discord = Client.CreatePCMStream(AudioApplication.Music);
+ output.CopyToAsync(discord);
- discord.FlushAsync();
- };
+ discord.FlushAsync();
+ };
barInvoker.RunWorkerAsync();
}
@@ -44,7 +36,7 @@
[Command("join", RunMode = RunMode.Async)]
public async Task JoinChannelAsync(IVoiceChannel channel = null)
{
- var msg = this.Context.Message;
+ var msg = Context.Message;
// Get the audio channel
channel = channel ?? (msg.Author as IGuildUser)?.VoiceChannel;
@@ -67,37 +59,22 @@
if (Client != null)
{
- SoundEffects.Play("Nooo");
await Client.StopAsync();
Client = null;
}
}
- [Command("volume")]
- public void SetVolume(int volume)
- {
- if (volume <= 100 && volume >= 0)
- {
- SoundEffects.MaxVolume = volume;
- }
- }
[Command("play", RunMode = RunMode.Async)]
public async Task PlayAudioAsync(string path)
{
- if (Client == null)
- {
- await this.Context.Channel.SendMessageAsync("Erst Joinen!");
- }
+ if (Client == null) await Context.Channel.SendMessageAsync("Erst Joinen!");
- SoundEffects.Play(path);
+ //SoundEffects.Play(path);
var sounds = Enum.GetValues(typeof(Sound));
var soundList = new List<Sound>();
- foreach (var sound in sounds)
- {
- soundList.Add((Sound)sound);
- }
+ foreach (var sound in sounds) soundList.Add((Sound) sound);
var sc = new SpellCorrect();
}
@@ -109,9 +86,9 @@
FileName = "ffmpeg",
Arguments = $"-i {path} -ac 2 -f s16le -ar 48000 -ab 620000 -vol {vol} pipe:1",
UseShellExecute = false,
- RedirectStandardOutput = true,
+ RedirectStandardOutput = true
};
return Process.Start(ffmpeg);
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Auxiliary/Calculator/Argument.cs b/DiscoBot/Auxiliary/Calculator/Argument.cs
deleted file mode 100644
index 2379bfe..0000000
--- a/DiscoBot/Auxiliary/Calculator/Argument.cs
+++ /dev/null
@@ -1,38 +0,0 @@
-namespace DiscoBot.Auxiliary.Calculator
-{
- using System;
-
- /// <summary>
- /// Provides an ISolvable class to save numbers. The class handles Argument checking and conversion from string to int.
- /// </summary>
- public class Argument : ISolvable
- {
- private readonly int 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. ", nameof(value));
- }
-
- if (!int.TryParse(value, out int result))
- {
- throw new ArgumentException($"Kann {value} nicht in Integer konvertieren");
- }
-
- this.value = result;
- }
-
- public int Solve()
- {
- return this.value;
- }
-
- public override string ToString()
- {
- return this.value.ToString();
- }
- }
-} \ No newline at end of file
diff --git a/DiscoBot/Auxiliary/Calculator/ISolvable.cs b/DiscoBot/Auxiliary/Calculator/ISolvable.cs
deleted file mode 100644
index a869bdb..0000000
--- a/DiscoBot/Auxiliary/Calculator/ISolvable.cs
+++ /dev/null
@@ -1,10 +0,0 @@
-namespace DiscoBot.Auxiliary.Calculator
-{
- /// <summary>
- /// Object has to be able to return an integer as it's value
- /// </summary>
- public interface ISolvable
- {
- int Solve();
- }
-}
diff --git a/DiscoBot/Auxiliary/Calculator/Operator.cs b/DiscoBot/Auxiliary/Calculator/Operator.cs
deleted file mode 100644
index 0928ec2..0000000
--- a/DiscoBot/Auxiliary/Calculator/Operator.cs
+++ /dev/null
@@ -1,50 +0,0 @@
-using System;
-
-namespace DiscoBot.Auxiliary.Calculator
-{
- /// <summary>
- /// The Operator Class represents a binary operator with tow Arguments and an Operation type
- /// </summary>
- public class Operator : ISolvable
- {
- private readonly ISolvable arg1, arg2;
-
- public Operator(ISolvable arg1, ISolvable arg2, Ops operatorType)
- {
- this.arg1 = arg1;
- this.arg2 = arg2;
- this.OperatorType = operatorType;
- }
-
- public Ops OperatorType { get; set; }
-
- public int Solve()
- {
- int result;
- switch (this.OperatorType)
- {
- case Ops.Dice:
- result = Dice.Roll(this.arg1.Solve(), this.arg2.Solve());
- break;
- case Ops.Multiply:
- result = this.arg1.Solve() * this.arg2.Solve();
- break;
- case Ops.Add:
- result = this.arg1.Solve() + this.arg2.Solve();
- break;
- case Ops.Subtract:
- result = this.arg1.Solve() - this.arg2.Solve();
- break;
- default:
- throw new ArgumentOutOfRangeException();
- }
-
- return result;
- }
-
- public override string ToString()
- {
- return $"({this.arg1} {this.OperatorType} {this.arg2})";
- }
- }
-}
diff --git a/DiscoBot/Auxiliary/Calculator/Ops.cs b/DiscoBot/Auxiliary/Calculator/Ops.cs
deleted file mode 100644
index 62c1309..0000000
--- a/DiscoBot/Auxiliary/Calculator/Ops.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace DiscoBot.Auxiliary.Calculator
-{
- /// <summary>
- /// The Different Operations, witch can be performed in execution-order
- /// </summary>
- public enum Ops
- {
- Dice,
- Multiply,
- Subtract,
- Add
- }
-}
diff --git a/DiscoBot/Auxiliary/Calculator/StringSolver.cs b/DiscoBot/Auxiliary/Calculator/StringSolver.cs
deleted file mode 100644
index 6e5b3a9..0000000
--- a/DiscoBot/Auxiliary/Calculator/StringSolver.cs
+++ /dev/null
@@ -1,207 +0,0 @@
-namespace DiscoBot.Auxiliary.Calculator
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
-
- /// <summary>
- /// The StringSolver divides the calculation string into operations and SubStringSolvers if the string contains parentheses
- /// </summary>
- public class StringSolver : ISolvable
- {
- public readonly string input;
- public readonly List<object> arguments = new List<object>();
-
- public StringSolver(string input)
- {
- this.input = input;
- }
-
- public override string ToString()
- {
- return "(0+" + this.input.Replace(" ", string.Empty).ToLower() + ")";
- }
-
- public int Solve()
- {
- string workInput = "0+" + this.input.Replace(" ", string.Empty).ToLower();
- workInput = ExpandParentheses(workInput);
-
- // Create a List of the different parts of the calculation, e.g.:{"0", "+", "(5+6)", "d", "3"}.
- this.AtomizeOperations(workInput);
-
- // traverse the List in order of Operation to Create the binary operation tree .
- this.NestOperations();
-
- // the List now contains only the top operation node, witch can be solved recursively,
- return ((ISolvable)this.arguments.First()).Solve();
- }
-
- public static string GetInner(ref string input) // extract the inner bracket an remove the section from the input string
- {
- int depth = 0;
- for (var index = 1; index < input.Length; index++)
- {
- char c = input[index];
- switch (c)
- {
- case '(':
- depth++;
- break;
- case ')':
- if (depth == 0)
- {
- var split = input.Substring(1, index - 1);
- input = input.Substring(index + 1);
- return split.Equals(string.Empty) ? "0" : split;
- }
- else
- {
- depth--;
- }
-
- break;
- }
- }
-
- return string.Empty;
- }
-
- public static Ops GetOps(char c)
- {
- switch (c)
- {
- case 'd':
- case 'w':
- return Ops.Dice;
- case '+':
- return Ops.Add;
- case '-':
- return Ops.Subtract;
- case '*':
- return Ops.Multiply;
- default:
- return Ops.Multiply;
- }
- }
-
- public static string ExpandParentheses(string input) // insert * between Parentheses and digits
- {
- for (int i = 0; i < input.Length - 1; i++)
- {
- if (input[i + 1] == '(' && char.IsNumber(input[i]))
- {
- input = input.Insert(i + 1, "*");
- }
- }
-
- for (int i = 1; i < input.Length; i++)
- {
- if (input[i - 1] == ')' && char.IsNumber(input[i]))
- {
- input = input.Insert(i, "*");
- }
- }
-
- return input;
- }
-
- public void AtomizeOperations(string workInput)
- {
- for (var index = 0; index < workInput.Length; index++)
- {
- char c = workInput[index];
-
- 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
- this.arguments.Add(new Argument(workInput.Substring(0, index + 1)));
- }
-
- continue;
- }
-
- switch (c)
- {
- case ')':
- throw new ArgumentException($"Unmögliche Anordnung von Klammern");
- case '(':
- this.arguments.Add(new StringSolver(GetInner(ref workInput)));
- index = -1;
- break;
- default:
- if (index > 0)
- {
- this.arguments.Add(new Argument(workInput.Substring(0, index)));
- }
-
- this.arguments.Add(GetOps(c));
- workInput = workInput.Remove(0, index + 1);
- index = -1;
- break;
- }
- }
- }
-
- public void NestOperations()
- {
- foreach (Ops currentOp in Enum.GetValues(typeof(Ops)))
- {
- // cycle through operators in operational order
- for (var index = 0; index < this.arguments.Count; index++)
- {
- var arg = this.arguments[index];
-
- if (arg.GetType() != typeof(Ops))
- {
- continue;
- }
-
- // arg is of type Ops
- var op = (Ops)arg;
-
- if (op != currentOp)
- {
- continue;
- }
-
- // arg describes the current operation
- this.HandleSpecialFormatting(ref index, op); // Deal with special needs...
-
- // replace the previous current and next Element in the List with one Operation object
- var temp = new Operator((ISolvable)this.arguments[index - 1], (ISolvable)this.arguments[index + 1], op);
- this.arguments[index - 1] = temp;
- this.arguments.RemoveRange(index, 2);
- index--;
- }
- }
- }
-
- public void HandleSpecialFormatting(ref int index, Ops op)
- {
- var arg1 = this.arguments[index - 1];
- if (arg1.GetType() == typeof(Ops))
- {
- if (op == Ops.Dice)
- {
- this.arguments.Insert(index++, new Argument("1")); // w6 -> 1w6
- }
-
- if (op == Ops.Subtract)
- {
- this.arguments.Insert(index++, new Argument("0")); // +-3 -> +0-3
- }
- }
-
- var arg2 = this.arguments[index + 1]; // 3+-5 -> 3+(0-5)
- if (arg2.GetType() == typeof(Ops))
- {
- this.arguments[index + 1] = new Operator(new Argument("0"), (ISolvable)this.arguments[index + 2], (Ops)arg2);
- this.arguments.RemoveAt(index + 2);
- }
- }
- }
-} \ No newline at end of file
diff --git a/DiscoBot/ToRework/CommandExtension.cs b/DiscoBot/Auxiliary/CommandExtension.cs
index 098e35f..ad9f323 100644
--- a/DiscoBot/ToRework/CommandExtension.cs
+++ b/DiscoBot/Auxiliary/CommandExtension.cs
@@ -1,33 +1,31 @@
-namespace DiscoBot.Auxiliary
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using Discord;
+using Discord.Commands;
+
+namespace DiscoBot.Auxiliary
{
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
-
- using Discord;
- using Discord.Commands;
-
public static class CommandExtension
{
- private static WebClient client;
+ private static WebClient _client;
public static async Task ReplyTimedAsync(this ModuleBase m, string message, TimeSpan time)
{
var token = message.GetHashCode();
- var send = m.Context.Channel.SendMessageAsync($"#{token}\n```xl\n{message}```", false);
+ var send = m.Context.Channel.SendMessageAsync($"#{token}\n```xl\n{message}```");
var barInvoker = new BackgroundWorker();
barInvoker.DoWork += delegate
- {
- Thread.Sleep(time);
- Delete(token, m);
- };
+ {
+ Thread.Sleep(time);
+ Delete(token, m);
+ };
await send;
barInvoker.RunWorkerAsync();
@@ -39,35 +37,23 @@
Task.WaitAll(messagesAsync.ToArray());
var list = messagesAsync.ToEnumerable().ToList();
var messages = new List<IMessage>();
- foreach (var task in list)
- {
- messages.AddRange(task.ToList());
- }
-
- var test = messages.Where(x => x.Content.StartsWith($"#{token}\n") && x.Author.IsBot).Select(c=>c );
- var waiters = new List<Task>();
- foreach (var message in test)
- {
- waiters.Add((message as IUserMessage).DeleteAsync());
- }
- Task.WaitAll(waiters.ToArray());
+ foreach (var task in list) messages.AddRange(task.ToList());
+
+ var test = messages.Where(x => x.Content.StartsWith($"#{token}\n") && x.Author.IsBot).Select(c => c);
+ Task.WaitAll(test.Select(message => (message as IUserMessage)?.DeleteAsync()).ToArray());
}
public static async Task ReplyAsync(this ModuleBase m, IEnumerable<string> message, bool directMessage = false)
{
var sb = new StringBuilder();
- foreach (string re in message)
+ foreach (var re in message)
{
if (sb.Length + re.Length > 1798)
{
if (directMessage)
- {
await m.Context.User.SendMessageAsync("```xl\n" + sb + "\n```");
- }
else
- {
await m.Context.Channel.SendMessageAsync("```xl\n" + sb + "\n```");
- }
sb.Clear();
}
@@ -76,23 +62,18 @@
}
if (directMessage)
- {
await m.Context.User.SendMessageAsync("```xl\n" + sb + "\n```");
- }
else
- {
await m.Context.Channel.SendMessageAsync("```xl\n" + sb + "\n```");
- }
}
public static async Task ReplyAsync(this ModuleBase m, IEnumerable<string> message, TimeSpan time)
{
var sb = new StringBuilder();
- foreach (string re in message)
+ foreach (var re in message)
{
if (sb.Length + re.Length > 1798)
{
-
await m.ReplyTimedAsync(sb.ToString(), time);
@@ -105,15 +86,13 @@
await m.ReplyTimedAsync(sb.ToString(), TimeSpan.FromSeconds(90));
}
- public static async Task SendWebFile(this IMessageChannel channel, string url = "https://i.imgur.com/0iHEycJ.png")
+ public static async Task SendWebFile(this IMessageChannel channel,
+ string url = "https://i.imgur.com/0iHEycJ.png")
{
- if (client == null)
- {
- client = new WebClient();
- }
+ if (_client == null) _client = new WebClient();
- Stream stream = client.OpenRead(url);
+ var stream = _client.OpenRead(url);
await channel.SendFileAsync(stream, url.Split('/').Last());
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Auxiliary/CommandInfo.cs b/DiscoBot/Auxiliary/CommandInfo.cs
deleted file mode 100644
index dfed417..0000000
--- a/DiscoBot/Auxiliary/CommandInfo.cs
+++ /dev/null
@@ -1,32 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.Auxiliary
-{
- public struct CommandInfo
- {
- public CommandInfo(string name, string brief, string[] description, string scope)
- {
- this.Name = name;
- this.Scope = scope;
- this.Brief = brief;
- this.Description = description;
- }
-
- public string Name { get; }
-
- public string Scope { get; }
-
- public string Brief { get; }
-
- public string[] Description { get; }
-
- public string GetDescription()
- {
- return this.Description.Aggregate((s, c) => s + c);
- }
- }
-}
diff --git a/DiscoBot/Auxiliary/Dice.cs b/DiscoBot/Auxiliary/Dice.cs
index 0cd9656..f0f4def 100644
--- a/DiscoBot/Auxiliary/Dice.cs
+++ b/DiscoBot/Auxiliary/Dice.cs
@@ -1,44 +1,25 @@
-namespace DiscoBot.Auxiliary
-{
- using System;
- using System.Linq;
-
- using Discord.Commands;
+using System;
+namespace DiscoBot.Auxiliary
+{
public static class Dice // roll it!
{
- private static readonly System.Random Rnd = new System.Random();
+ private static readonly Random Rnd = new Random();
public static int Roll(int d = 20)
{
return Rnd.Next(d) + 1;
}
- public static int Roll(string input)
- {
- var strings = input.ToLower().Split(new[] { 'w', 'd' }, 2, StringSplitOptions.RemoveEmptyEntries).ToList();
- int count = Convert.ToInt32(strings[0]);
- int d = Convert.ToInt32(strings[0]);
-
- if (strings.Count != 2)
- {
- throw new ArgumentException($"{input}: erfüllt nicht die Formatvogaben( Anzahl d Augenzahl)");
- }
-
- return Roll(count, d);
- }
public static int Roll(int count, int d)
{
- if (d <= 0)
- {
- return 0;
- }
+ if (d <= 0) return 0;
- int sum = 0;
- for (int i = 0; i < Math.Abs(count); i++)
+ var sum = 0;
+ for (var i = 0; i < Math.Abs(count); i++)
{
- var roll = Dice.Roll(d);
+ var roll = Roll(d);
sum += roll;
}
@@ -47,4 +28,4 @@
return sum;
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Auxiliary/Extensions.cs b/DiscoBot/Auxiliary/Extensions.cs
deleted file mode 100644
index fad5dd8..0000000
--- a/DiscoBot/Auxiliary/Extensions.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-namespace DiscoBot.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)
- {
- string temp = str;
- for(int i = str.Length; i < length; i++)
- {
- temp += " ";
- }
- return temp;
- }
-
-
-
- //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)
- {
- string temp = "";
- for (int i = str.Length; i < length; i++)
- {
- temp += " ";
- }
- return temp + str;
- }
- }
-
-}
diff --git a/DiscoBot/Auxiliary/Permissions.cs b/DiscoBot/Auxiliary/Permissions.cs
new file mode 100644
index 0000000..3ec4a2e
--- /dev/null
+++ b/DiscoBot/Auxiliary/Permissions.cs
@@ -0,0 +1,32 @@
+using System.Collections.Generic;
+using System.Linq;
+using Discord.Commands;
+using Discord.WebSocket;
+
+namespace DiscoBot.Auxiliary
+{
+ public static class Permissions
+ {
+ public static bool Check(ICommandContext c, string role)
+ {
+ return ((SocketGuildUser) c.User).Roles.ToList().Exists(v => v.Name.Equals(role));
+ }
+
+ public static bool Check(ICommandContext c, IEnumerable<string> roles)
+ {
+ return roles.Any(role => ((SocketGuildUser) c.User).Roles.ToList().Exists(v => v.Name.Equals(role)));
+ }
+
+ public static bool Test(ICommandContext c, string role)
+ {
+ if (Check(c, role)) return true;
+ c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait();
+ return false;
+ }
+
+ public static void Test(ICommandContext c, string[] roles)
+ {
+ if (!Check(c, roles)) c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait();
+ }
+ }
+} \ No newline at end of file
diff --git a/DiscoBot/Auxiliary/RandomMisc.cs b/DiscoBot/Auxiliary/RandomMisc.cs
index 7ba625e..205b3a7 100644
--- a/DiscoBot/Auxiliary/RandomMisc.cs
+++ b/DiscoBot/Auxiliary/RandomMisc.cs
@@ -1,52 +1,36 @@
-namespace DiscoBot.Auxiliary
-{
- using System;
- using System.Linq;
- using System.Text;
+using System;
+using System.Linq;
+using System.Text;
+namespace DiscoBot.Auxiliary
+{
public static class RandomMisc
{
- private static readonly Random Rand = new Random();
-
- // use: 4w6 +4
public static string Roll(string input)
{
var output = new StringBuilder();
var strings = input.Split('w', 'd').ToList();
- int count = Convert.ToInt32(strings[0]);
+ var count = Convert.ToInt32(strings[0]);
strings = strings[1].Split(' ').ToList();
- int d = Convert.ToInt32(strings[0]);
+ var d = Convert.ToInt32(strings[0]);
if (strings.Count > 0)
{
}
- int sum = 0;
- for (int i = 0; i < count; i++)
+ var sum = 0;
+ for (var i = 0; i < count; i++)
{
var roll = Dice.Roll(d);
sum += roll;
output.Append("[" + roll + "] ");
}
-
- if (strings.Count > 1)
- {
- sum += Convert.ToInt32(strings[1]);
- output.Append("sum: " + sum);
- }
- return output.ToString();
- }
+ if (strings.Count <= 1) return output.ToString();
+ sum += Convert.ToInt32(strings[1]);
+ output.Append("sum: " + sum);
- public static double Random(double stdDev = 1, double mean = 0)
- {
- double u1 = Rand.NextDouble(); // uniform(0,1) random doubles
- double u2 = Rand.NextDouble();
- double randStdNormal = Math.Sqrt(-2.0 * Math.Log(u1)) *
- Math.Sin(2.0 * Math.PI * u2); // random normal(0,1)
- double randNormal =
- mean + stdDev * randStdNormal; // random normal(mean,stdDev^2)
- return randNormal;
+ return output.ToString();
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Auxiliary/SpellCorrect.cs b/DiscoBot/Auxiliary/SpellCorrect.cs
index 01cce62..c4bd4bf 100644
--- a/DiscoBot/Auxiliary/SpellCorrect.cs
+++ b/DiscoBot/Auxiliary/SpellCorrect.cs
@@ -1,9 +1,8 @@
-namespace DiscoBot.Auxiliary
-{
- using System;
- using System.Diagnostics;
- using System.Linq;
+using System;
+using System.Diagnostics;
+namespace DiscoBot.Auxiliary
+{
public class SpellCorrect : StringComparer
{
public const int ErrorThreshold = 94100;
@@ -15,44 +14,25 @@
public static int CompareEasy(string x, string y)
{
- if (string.IsNullOrEmpty(x))
- {
- throw new ArgumentException("message", nameof(x));
- }
+ if (string.IsNullOrEmpty(x)) throw new ArgumentException("message", nameof(x));
- if (string.IsNullOrEmpty(y))
- {
- throw new ArgumentException("message", nameof(y));
- }
+ if (string.IsNullOrEmpty(y)) throw new ArgumentException("message", nameof(y));
- if (x.Equals(y))
- {
- return 0;
- }
+ if (x.Equals(y)) return 0;
x = x.ToLower();
y = y.ToLower();
- if (x.Equals(y))
- {
- return 1;
- }
+ if (x.Equals(y)) return 1;
var subs = y.Split(' ', '/');
- int score = subs.Count();
- foreach (string s in subs)
- {
+ var score = subs.Length;
+ foreach (var s in subs)
if (s.Equals(x))
- {
score--;
- }
- }
- if (score < subs.Count())
- {
- return score + 1;
- }
+ if (score < subs.Length) return score + 1;
- return 100000 - (int)(CompareExact(x, y) * 1000.0);
+ return 100000 - (int) (CompareExact(x, y) * 1000.0);
/*if (y.Contains(x))
return 6;*/
}
@@ -70,78 +50,56 @@
public static double CompareExact(string s, string q)
{
-
s = s.ToLower();
q = q.ToLower();
int i, j;
- const double Match = 3.0;
- const double Gap = -2.0;
- const double Mismatch = -2.0;
+ const double match = 3.0;
+ const double gap = -2.0;
+ const double mismatch = -2.0;
double decay;
- double[,] matrix = new double[s.Length + 1, q.Length + 1];
- double max = 0.0;
+ var matrix = new double[s.Length + 1, q.Length + 1];
+ var max = 0.0;
matrix[0, 0] = 0.0;
-
+
for (i = 1; i < s.Length; i++)
- {
- // matrix[i, 0] = 0.0;
- matrix[i, 0] = i * Gap;
- }
+ // matrix[i, 0] = 0.0;
+ matrix[i, 0] = i * gap;
- for (i = 1; i < q.Length; i++)
- {
- matrix[0, i] = 0.0;
- }
+ for (i = 1; i < q.Length; i++) matrix[0, i] = 0.0;
for (i = 1; i <= s.Length; i++)
+ for (j = 1; j <= q.Length; j++)
{
- for (j = 1; j <= q.Length; j++)
- {
- decay = j / (double)(s.Length * 1000);
- double add = s[i - 1] == q[j - 1] ? (Match - decay) : Mismatch;
- double score = matrix[i - 1, j - 1] + add;
+ decay = j / (double) (s.Length * 1000);
+ 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 (i > 1 && j > 1)
+ if (s[i - 1] == q[j - 2] && s[i - 2] == q[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;
- }
- }
+ add = 3 / 2.0 * match - decay;
+ if (score < matrix[i - 2, j - 2] + add) score = matrix[i - 2, j - 2] + add;
}
-
- // if (score < 0)
- // {
- // score = 0;
- // }
- if (max < score && i == s.Length)
- {
- max = score;
- }
+ // if (score < 0)
+ // {
+ // score = 0;
+ // }
+
+ if (max < score && i == s.Length) max = score;
- matrix[i, j] = score;
- }
+ matrix[i, j] = score;
}
return max;
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Auxiliary/TalentEnumerableExtension.cs b/DiscoBot/Auxiliary/TalentEnumerableExtension.cs
deleted file mode 100644
index df01de3..0000000
--- a/DiscoBot/Auxiliary/TalentEnumerableExtension.cs
+++ /dev/null
@@ -1,102 +0,0 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using DSALib;
-
-
-namespace DiscoBot.Auxiliary
-{
- using DiscoBot.Audio;
- using DiscoBot.DSA_Game.Characters;
-
-
- public static class TalentEnumerableExtension
- {
- public static string ProbenTest(this IEnumerable<Talent> List, Character c, string talent, int erschwernis = 0)
- {
- var output = new StringBuilder();
- var sc = new SpellCorrect();
- var tTalent = List.OrderBy(x => sc.Compare(talent, x.Name)).First();
-
- if (sc.Compare(talent, tTalent.Name) > SpellCorrect.ErrorThreshold)
- {
- try
- {
- SoundEffects.Play("Stupid");
- }
- catch { }
- return $"{c.Name} kann nicht {talent}...";
- }
-
- var props = tTalent.GetEigenschaften(); // get the required properties
- int tap = tTalent.Value; // get taw
- var werte = props.Select(p => c.Eigenschaften[c.PropTable[p]]).ToList();
-
- output.AppendFormat(
- "{0} würfelt: {1} \n{2} - {3} taw:{4} {5} \n",
- c.Name,
- tTalent.Name,
- tTalent.Probe,
- string.Join("/", werte),
- tTalent.Value,
- erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
-
- output.Append(" ");
- tap -= erschwernis;
- int gesamtErschwernis = tap;
- if (gesamtErschwernis < 0)
- {
- tap = 0;
- for (int i = 0; i <= 2; i++)
- {
- // foreach property, dice and tap
- int temp = Dice.Roll();
- int eigenschaft = c.Eigenschaften[c.PropTable[props[i]]];
-
- if (eigenschaft + gesamtErschwernis < temp)
- {
- tap -= temp - (eigenschaft + gesamtErschwernis);
- }
-
- output.Append($"[{temp}]"); // add to string
- }
-
- if (tap >= 0)
- {
- tap = 1;
- }
- }
- else
- {
- for (int i = 0; i <= 2; i++)
- {
- // foreach property, dice and tap
- int temp = Dice.Roll();
- int eigenschaft = c.Eigenschaften[c.PropTable[props[i]]];
-
- if (eigenschaft < temp)
- {
- tap -= temp - eigenschaft;
- }
-
- output.Append($"[{temp}]"); // add to string
- }
- }
-
- tap = (tap == 0) ? 1 : tap;
-
- if (tap < 0)
- {
- try
- {
- SoundEffects.Play("Wrong");
- }
- catch { }
- }
-
- output.AppendFormat(" tap: {0,2}", tap);
-
- return output.ToString(); // return output
- }
- }
-}
diff --git a/DiscoBot/Commands/CommandTypes.cs b/DiscoBot/Commands/CommandTypes.cs
deleted file mode 100644
index c1d0954..0000000
--- a/DiscoBot/Commands/CommandTypes.cs
+++ /dev/null
@@ -1,13 +0,0 @@
-namespace DiscoBot.Commands
-{
- public enum CommandTypes
- {
- Talent,
- Eigenschaft,
- Angriff,
- Parade,
- Fernkampf,
- KeinChar,
- Zauber
- }
-}
diff --git a/DiscoBot/Commands/FileHandler.cs b/DiscoBot/Commands/FileHandler.cs
index 0b87b15..17928c8 100644
--- a/DiscoBot/Commands/FileHandler.cs
+++ b/DiscoBot/Commands/FileHandler.cs
@@ -1,45 +1,25 @@
-namespace DiscoBot.Commands
-{
- using System;
- using System.Linq;
- using System.Net;
- using System.Threading.Tasks;
-
- using DiscoBot.DSA_Game;
- using DiscoBot.DSA_Game.Characters;
-
- using Discord.Commands;
- using DSALib;
+using System;
+using System.Linq;
+using System.Threading.Tasks;
+using Discord.Commands;
+namespace DiscoBot.Commands
+{
public class FileHandler : ModuleBase
{
//[Command("send"), Summary("fügt Helden hinzu")]
public async Task AddChar()
{
- var msg = this.Context.Message;
- if (msg.Attachments == null)
- {
- throw new ArgumentException("Es wurde keine Datei angehängt");
- }
+ var msg = Context.Message;
+ if (msg.Attachments == null) throw new ArgumentException("Es wurde keine Datei angehängt");
var attachments = msg.Attachments.ToList();
if (!attachments.Any(x => x.Filename.EndsWith(".xml")))
- {
throw new ArgumentException("Es wurde kein xml Held mitgeschickt");
- }
foreach (var attachment in attachments.Where(x => x.Filename.EndsWith(".xml")))
- {
- using (var client = new WebClient())
- {
- client.DownloadFile(attachment.Url, "helden\\" + attachment.Filename);
- }
-
- Dsa.Chars.Add(new Character("helden\\" + attachment.Filename));
- (Dsa.Chars.Last() as Character)?.Talente.Select(x => new Talent(x.Name, x.Probe, 0))
- .Where(c => !Dsa.Talente.Exists(v => v.Name.Equals(c.Name))).ToList().ForEach(v => Dsa.Talente.Add(v));
- }
+ throw new NotImplementedException("send File to Server");
}
}
} \ No newline at end of file
diff --git a/DiscoBot/Commands/Gm.cs b/DiscoBot/Commands/Gm.cs
deleted file mode 100644
index 483e9d2..0000000
--- a/DiscoBot/Commands/Gm.cs
+++ /dev/null
@@ -1,187 +0,0 @@
-using DiscoBot.DSA_Game.Characters;
-
-namespace DiscoBot.Commands
-{
- using System.Linq;
- using System.Threading.Tasks;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game;
-
- using Discord.Commands;
- using DSALib.Characters;
-
- public class Iam : ModuleBase
- {
-
- //[Command("Iam"), Summary("Wechselt den Character")]
- [Alias("iam", "I_am", "i_am", "IchBin", "ichbin", "Ichbin", "Ich_bin", "ich_bin", "Ich", "ich", "I", "i")]
- public Task Change_Character(params string[] givenName) // use fancy parameters
- {
- string res;
- string name;
-
- if (givenName.Length == 0 || (givenName.Length == 1 && (givenName[0].ToLower().Equals("bin") || givenName[0].ToLower().Equals("am"))))
- {
- res = " \nDu bist " + Dsa.Session.Relation[this.Context.User.Username] + "!\n \n";
-
- return this.ReplyAsync("```xl\n" + res + "\n```");
- }
-
- if (givenName.Length > 1 && (givenName[0].ToLower().Equals("bin") || givenName[0].ToLower().Equals("am")) )
- {
- name = givenName.Skip(1).Aggregate((s, c) => s + c); // (Skip(1)) don't use the first element; Aggregate: take source s and do operation s = s+c for all elements
- }
- else
- {
- name = givenName.Aggregate((s, c) => s + c);
- }
-
- if (name.ToLower().Equals("man") || name.ToLower().Equals("help"))
- {
- return this.ReplyAsync("```xl\n" + Help.Get_Specific_Help("ich bin") + "\n```");
-
- }
-
- var character = Dsa.Chars.OrderBy(x => SpellCorrect.CompareEasy(name, x.Name)).First(); // usage of compareEasy
-
- Dsa.Session.Relation[this.Context.User.Username] = character.Name;
- res = " \nWillkommen " + character.Name + "!\n \n";
-
-
- return this.ReplyAsync("```xl\n" + res + "\n```");
- }
- }
-
-
- public class Gm : ModuleBase
- {
- public static string CheckCommand(string name, CommandTypes command, string waffe, int erschwernis = 0)
- {
- var comp = new SpellCorrect();
- var chr = Dsa.Chars.OrderBy(x => comp.Compare(name, x.Name)).First();
-
- switch (command)
- {
- case CommandTypes.Talent:
- return chr.TestTalent(waffe, erschwernis);
- case CommandTypes.Eigenschaft:
- return chr.TestEigenschaft(waffe, erschwernis);
- case CommandTypes.Angriff:
- return chr.Angriff(waffe, erschwernis);
- case CommandTypes.Parade:
- return chr.Parade(waffe, erschwernis);
- case CommandTypes.Fernkampf:
- return chr.Fernkampf(waffe, erschwernis);
- case CommandTypes.Zauber:
- return chr.TestZauber(waffe, erschwernis);
- }
-
- return $"{name} verwendet {waffe}";
- }
-
- //[Command("gm"), Summary("Führt eine probe aus")]
- [Alias("GM", "as", "As", "als")]
- public async Task ProbeAsync([Summary("Fernkampfwaffe")] string name, string command, string cmdText = "", int modifier = 0)
- {
- if (!Permissions.Test(this.Context, "Meister")) return;
-
- command = command.ToLower();
-
- string res;
- string temp = string.Empty;
- ICharacter cha = Dsa.Chars.OrderBy(x =>
- SpellCorrect.CompareEasy(name, x.Name)).First();
- switch (command)
- {
- case "le":
- case "leben":
- case "lp":
- LE le = new LE();
- temp = string.Empty;
-
- if (modifier != 0)
- {
- temp = modifier.ToString();
- }
-
- res = cha.get_LE_Text(cmdText.Trim() + temp);
-
- break;
- case "ae":
- case "asp":
- case "astral":
- AE ae = new AE();
- temp = string.Empty;
-
- if (modifier != 0)
- {
- temp = modifier.ToString();
- }
-
- res = cha.get_AE_Text(cmdText.Trim() + temp);
-
- break;
- default:
- res = this.Test(name, command, cmdText, modifier);
- break;
- }
-
-
- if (Dsa.GeneralContext != null && Dsa.GeneralContext.Channel.Id != this.Context.Channel.Id)
- {
- await Dsa.GeneralContext.Channel.SendMessageAsync("```xl\n" + res + "\n```");
- }
-
- await this.ReplyAsync("```xl\n" + res + "\n```");
- }
-
- private string Test(string name, string command, string waffe, int erschwernis = 0)
- {
- string res;
- switch (command.ToLower())
- {
- case "f":
- case "fern":
- case "fernkampf":
- res = CheckCommand(name, CommandTypes.Fernkampf, waffe, erschwernis);
- break;
- case "t":
- case "ta":
- case "talent":
- case "talente":
- res = CheckCommand(name, CommandTypes.Talent, waffe, erschwernis);
- break;
- case "e":
- case "ei":
- case "eigenschaft":
- res = CheckCommand(name, CommandTypes.Eigenschaft, waffe, erschwernis);
- break;
- case "z":
- case "za":
- case "zauber":
- case "magie":
- case "m":
- res = CheckCommand(name, CommandTypes.Talent, waffe, erschwernis);
- break;
- case "a":
- case "at":
- case "an":
- case "angrif":
- case "angriff":
- res = CheckCommand(name, CommandTypes.Angriff, waffe, erschwernis);
- break;
- case "p":
- case "pa":
- case "parade":
- res = CheckCommand(name, CommandTypes.Parade, waffe, erschwernis);
- break;
- default:
- res = $"Kommando {command} nicht gefunden";
- break;
- }
-
- return res;
- }
- }
-}
diff --git a/DiscoBot/Commands/HeldList.cs b/DiscoBot/Commands/HeldList.cs
deleted file mode 100644
index a8f26e0..0000000
--- a/DiscoBot/Commands/HeldList.cs
+++ /dev/null
@@ -1,191 +0,0 @@
-namespace DiscoBot.Commands
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- using DiscoBot.Audio;
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game;
- using DiscoBot.DSA_Game.Characters;
-
- using Discord.Commands;
-
- public class Held : ModuleBase
- {
- //[Command("held"), Summary("gibt Heldenwerte aus")]
- [Alias("Held", "Wert", "Werte", "werte", "char", "Char")]
- public async Task ListAsync([Summary("Werte")] params string[] prop_list)
- {
- var res = new List<string>();
-
- var character = ((Character)Dsa.Chars.Find(x => x.Name.Equals(Dsa.Session.Relation[this.Context.User.Username])));
-
- int first_column_width = 18;
-
- int persist = 0;
-
- if (prop_list.Length == 0 || prop_list[0].ToLower().StartsWith("all") || prop_list[0].ToLower().StartsWith("brief") || prop_list[0].ToLower().StartsWith("zettel"))
- {
- persist = 1;
-
- res.Add(character.Name + ":\n");
- //Eigenschaften
- res.AddRange(
- character.Eigenschaften.Take(9).Select(s => s.Key + ":\t " + s.Value));
- res.Add("");
- //LE/AE
- res.Add("LE:\t " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
- if (character.Astralpunkte_Basis > 0)
- {
- res.Add("AE:\t " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis);
- }
- res.Add("");
- //Kampfwerte
- res.Add("".AddSpaces(first_column_width) + " AT/PA");
- res.AddRange(
- character.Kampftalente.Select(s => s.Name.AddSpaces(first_column_width) + " " + s.At.ToString().AddSpacesAtHead(2) + "/" + s.Pa.ToString().AddSpacesAtHead(2)));
- res.Add("");
- //Fernkampf
- res.Add("".AddSpaces(first_column_width) + " FK");
- res.AddRange(
- character.Talente.Where(x => x.IstFernkampftalent()).Select(s => s.Name.AddSpaces(first_column_width) + " " + (character.Eigenschaften["fk"] + s.Value).ToString().AddSpacesAtHead(2)));
- res.Add("");
- //Vorteile
- res.AddRange(
- character.Vorteile
- .Select(s => s.Name + "\t " + s.Value));
- res.Add("");
- //Talente
- res.AddRange(
- character.Talente.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
- res.Add("");
- //evtl Zauber
- if (character.Zauber.Count > 0)
- {
- res.AddRange(
- character.Zauber.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
- }
-
- }
- else if (prop_list[0].ToLower().StartsWith("man") || prop_list[0].ToLower().StartsWith("help") || prop_list[0].ToLower().StartsWith("hilf"))
- {
- await this.ReplyAsync("```xl\n" + Help.Get_Specific_Help("Held") + "\n```");
- return;
- }
- else
- {
-
- res.Add(character.Name + ":\n");
-
- foreach (string prop in prop_list)
- {
-
- switch (prop.ToLower())
- {
- case "e":
- case "eig":
- case "eigenschaft":
- case "eigenschaften":
- res.AddRange(
- character.Eigenschaften.Take(8).Select(s => s.Key + ":\t " + s.Value));
- break;
- case "stat":
- case "stats":
- res.AddRange(
- character.Eigenschaften.Take(9).Select(s => s.Key + ":\t " + s.Value));
- res.Add("");
- res.Add("LE:\t " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
- if (character.Astralpunkte_Basis > 0)
- {
- res.Add("AE:\t " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis);
- }
- break;
- case "le":
- res.Add("LE:\t " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
- break;
- case "ae":
- res.Add("AE:\t " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis);
- break;
- case "t":
- case "ta":
- case "talent":
- case "talente":
- res.AddRange(
- character.Talente.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
- break;
- case "zauber":
- case "z":
- res.AddRange(
- character.Zauber.Select(s => (s.Name.AddSpaces(first_column_width) + " " + s.Value).AddSpaces(first_column_width + 5) + " " + s.Probe));
- break;
- case "w":
- case "waffe":
- case "waffen":
- case "kampf":
- case "kampfwert":
- case "kampfwerte":
- res.Add("".AddSpaces(first_column_width) + " AT/PA");
- res.AddRange(
- character.Kampftalente.Select(s => s.Name.AddSpaces(first_column_width) + " " + s.At.ToString().AddSpacesAtHead(2) + "/" + s.Pa.ToString().AddSpacesAtHead(2)));
- break;
- case "f":
- case "fern":
- res.Add("".AddSpaces(first_column_width) + " FK");
- res.AddRange(
- character.Talente.Where(x => x.IstFernkampftalent()).Select(s => s.Name.AddSpaces(first_column_width) + " " + (character.Eigenschaften["fk"] + s.Value).ToString().AddSpacesAtHead(2)));
- break;
- case "v":
- case "vt":
- case "vor":
- case "vorteil":
- case "vorteile":
- case "nachteil":
- case "nachteile":
- res.AddRange(
- character.Vorteile
- .Select(s => s.Name + "\t " + s.Value));
- break;
-
- default:
- res.Add($"Kommando {prop} nicht gefunden");
- break;
- }
-
- res.Add("");
- }
-
- }
-
-
- //var sb = new StringBuilder();
- //foreach (string re in res)
- //{
- // if (sb.Length + re.Length > 1798)
- // {
- // if (persist == 1)
- // {
- // await this.ReplyAsync("```xl\n" + sb.ToString() + "\n```");
- // }
- // else
- // {
- // await this.ReplyTimedAsync(sb.ToString(), TimeSpan.FromSeconds(90));
- // }
- // sb.Clear();
- //}
-
- //sb.AppendLine(re);
- //}
- if (persist == 1)
- {
- await this.ReplyAsync(res, true);
- }
- else
- {
- await this.ReplyAsync(res, TimeSpan.FromSeconds(90));
- }
- }
- }
-}
diff --git a/DiscoBot/Commands/Help.cs b/DiscoBot/Commands/Help.cs
deleted file mode 100644
index 4c378c9..0000000
--- a/DiscoBot/Commands/Help.cs
+++ /dev/null
@@ -1,99 +0,0 @@
-using System.Linq;
-
-namespace DiscoBot.Commands
-{
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Security.Cryptography;
- using System.Threading.Tasks;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game;
-
- using Discord.Commands;
-
- using Newtonsoft.Json;
-
- using CommandInfo = DiscoBot.Auxiliary.CommandInfo;
-
- public class Help : ModuleBase
- {
- static Help()
- {
- /*TextReader stream = new StreamReader(@"..\..\Help.json"); // Load command-description file
- var reader = new JsonTextReader(stream); // create stream reader
-
- reader.Read(); // step into structure, until the array starts
- reader.Read();
- reader.Read();
-
- try
- {
- var test = new JsonSerializer().Deserialize<List<CommandInfo>>(reader); // Deserialize Data and create CommandInfo Struct
-
- Commands.AddRange(test); // Add new CommandInfos to List
- }
- catch (Exception e)
- {
- // ignored
- }*/
- }
-
- //public static List<CommandInfo> Commands { get; } = new List<CommandInfo>();
-
-
- public static string Get_Specific_Help(string command)
- {
- // return command specific help
- var com = DSA_Game.Save.Properties.CommandInfos.OrderBy(x => SpellCorrect.CompareEasy(x.Name, command.ToLower())).First(); // get best fit command
- return com.GetDescription();
- }
-
- public static string Get_Generic_Help()
- {
- string res = "";
- foreach (var com in DSA_Game.Save.Properties.CommandInfos)
- {
- int first_column_width = 8;
- res += ("!" + com.Name + ": ").AddSpaces(first_column_width) + com.Brief;
-
- if (com.Description.Length > 1)
- {
- res += "\n" + "".AddSpaces(first_column_width) + "(\"!man " + com.Name + "\" gibt genauere Informationen)";
- }
-
- res += "\n\n";
- }
- return res;
- }
-/*
-
- //[Command("help"), Summary("prints the help menu.")]
- [Alias("Help", "man", "Man", "Hilfe", "hilfe", "h")]
- public async Task ShowHelpAsync(params string[] command_list)
- {
- var command = "";
- if (command_list.Length > 0) {
- command = command_list.Aggregate((s, c) => s + " " + c);
- }
-
- if (command.Equals(string.Empty)) // return generic Help
- {
- string res = Get_Generic_Help();
-
- //await this.ReplyAsync("```\n[hilfreiche Erklärungen]\nAuflistung aller Commands mit !list commands\n```");
- await this.ReplyAsync("```xl\n" + res +"\n```");
- return;
- }
-
-
-
- // return command specific help
- //var com = Commands.OrderBy(x => SpellCorrect.CompareEasy(x.Name, command.ToLower())).First(); // get best fit command
-
- //await this.ReplyAsync("```xl\n" + com.GetDescription() + "\n```");
- await this.ReplyAsync("```xl\n" + Get_Specific_Help(command) + "\n```");
- }*/
- }
-}
diff --git a/DiscoBot/Commands/LebenUndAstral.cs b/DiscoBot/Commands/LebenUndAstral.cs
deleted file mode 100644
index 2406c70..0000000
--- a/DiscoBot/Commands/LebenUndAstral.cs
+++ /dev/null
@@ -1,198 +0,0 @@
-namespace DiscoBot.Commands
-{
- using System;
- using System.Linq;
- using System.Threading.Tasks;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game;
- using DiscoBot.DSA_Game.Characters;
-
- using Discord.Commands;
- using DSALib.Characters;
-
- public class LE : ModuleBase
- {
- //[Command("LE"), Summary("Ändert aktuellen Lebenspunktestand")]
- [Alias("le", "leben", "LP", "lp", "Le", "Lp")]
-
- public async Task LEAsync([Summary("LE Modifier")] string prop = "", string s = "")
- {
- //This is the string that will be printed
- string res = "";
-
- if (prop.ToLower().Equals("help") || prop.ToLower().Equals("man"))
- {
- await this.ReplyAsync("```xl\n" + Help.Get_Specific_Help("LE") + "\n```");
- return;
- }
-
- //In case the input is badly formated
- prop = prop.Trim() + s.Trim();
-
-
- //Get the actual text
- res += Dsa.Chars.OrderBy(x => SpellCorrect.CompareEasy(Dsa.Session.Relation[this.Context.User.Username], x.Name)).First().get_LE_Text(prop);
-
-
- await this.ReplyAsync("```xl\n" + res + "\n```");
- }
- }
-
- public class AE : ModuleBase
- {
- //[Command("AE"), Summary("Ändert aktuellen Astralpunktestand")]
- [Alias("ae", "astral", "ASP", "Asp", "asp", "Astral")]
-
- public async Task AEAsync([Summary("AE Modifier")] string prop = "", string s = "")
- {
- //This is the string that will be printed
- string res = "";
-
- if (prop.ToLower().Equals("help") || prop.ToLower().Equals("man"))
- {
- await this.ReplyAsync("```xl\n" + Help.Get_Specific_Help("AE") + "\n```");
- return;
- }
-
- //Incase the input is badly formated
- prop = prop.Trim() + s.Trim();
-
-
- //Get the actual text
- res += Dsa.Chars.OrderBy(x => SpellCorrect.CompareEasy(Dsa.Session.Relation[this.Context.User.Username], x.Name)).First().get_AE_Text(prop);
-
-
-
- await this.ReplyAsync("```xl\n" + res + "\n```");
- }
- }
-
- public static class StatExtension
- {
- public static string get_LE_Text(this ICharacter c, string prop)
- {
- string res = "";
- var comp = new SpellCorrect();
- var character = c;
-
- res += (character.Name + ":\n");
-
- //If there is actual input we process it
- if (prop.Length > 0)
- {
- res += "LE: ";
- res += character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis + " -> ";
-
- // Apply a change to current value
- if (prop.StartsWith("+") || prop.StartsWith("-"))
- {
- //Allow overflowing the max
- if (prop.StartsWith("++"))
- {
- character.Lebenspunkte_Aktuell = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop.Substring(1, prop.Length - 1));
- }
- else
- {
- int temp = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop) - character.Lebenspunkte_Basis;
- //Stop from overflow overflow
- if (temp > 0 && prop.StartsWith("+"))
- {
- character.Lebenspunkte_Aktuell = (character.Lebenspunkte_Basis > character.Lebenspunkte_Aktuell) ? character.Lebenspunkte_Basis : character.Lebenspunkte_Aktuell;
- res += " Maximale Lebenspunkte sind erreicht ";
- }
- //Simply apply change
- else
- {
- character.Lebenspunkte_Aktuell = character.Lebenspunkte_Aktuell + Convert.ToInt32(prop);
- }
- }
-
- res += character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis;
- }
- else
- {
- // Set to new value regardless of original
- character.Lebenspunkte_Aktuell = Convert.ToInt32(prop);
-
- res += character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis;
- }
- }
- //If no value is passed, the curent value is displayed
- else
- {
- res += ("LE: " + character.Lebenspunkte_Aktuell + "/" + character.Lebenspunkte_Basis);
- }
-
- return res;
- }
- public static string get_AE_Text(this ICharacter c, string prop)
- {
- string res = "";
- var comp = new SpellCorrect();
- var character = c;
-
- res += (character.Name + ":\n");
-
- //If there is actual input we process it
- if (prop.Length > 0)
- {
-
- res += "AE: ";
- res += character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis + " -> ";
-
- // Apply a change to current value
- if (prop.StartsWith("+") || prop.StartsWith("-"))
- {
- //Allow overflowing the max
- if (prop.StartsWith("++"))
- {
- character.Astralpunkte_Aktuell = character.Astralpunkte_Aktuell + Convert.ToInt32(prop.Substring(1, prop.Length - 1));
- }
- else
- {
- int temp = character.Astralpunkte_Aktuell + Convert.ToInt32(prop) - character.Astralpunkte_Basis;
- //Stop from overflow overflow
- if (temp > 0 && prop.StartsWith("+"))
- {
- character.Astralpunkte_Aktuell = (character.Astralpunkte_Basis > character.Astralpunkte_Aktuell) ? character.Astralpunkte_Basis : character.Astralpunkte_Aktuell;
- res += " Maximale Astralpunkte sind erreicht ";
- }
- //Simply apply change
- else
- {
- character.Astralpunkte_Aktuell = character.Astralpunkte_Aktuell + Convert.ToInt32(prop);
- }
- }
-
- if (character.Astralpunkte_Aktuell < 0)
- {
- res += "Nicht genügend Astralpunkte! ";
- character.Astralpunkte_Aktuell = 0;
- }
-
- res += character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis;
-
- }
- //Set to new value regardless of original
- 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
- {
- res += ("AE: " + character.Astralpunkte_Aktuell + "/" + character.Astralpunkte_Basis);
- }
-
-
- return res;
- }
- }
-}
-
-
-
diff --git a/DiscoBot/Commands/List.cs b/DiscoBot/Commands/List.cs
deleted file mode 100644
index e77362e..0000000
--- a/DiscoBot/Commands/List.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-namespace DiscoBot.Commands
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- using DiscoBot.Audio;
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game;
- using DiscoBot.DSA_Game.Characters;
-
- using Discord.Commands;
-
- public class List : ModuleBase
- {
- //[Command("list"), Summary("gibt eine Auflistung aus")]
- public async Task ListAsync([Summary("Aktion")] string prop)
- {
- var res = new List<string>();
-
- int persist = 0;
-
- switch (prop.ToLower())
- {
- case "man":
- case "help":
- await this.ReplyAsync("```xl\n" + Help.Get_Specific_Help("List") + "\n```");
- return;
- // break;
- case "chars":
- res.AddRange(Dsa.Chars.Select(x => x.Name));
- break;
- case "commands":
- // res.AddRange(Help.Commands.Select(x => x.Name));
- res.Add(Help.Get_Generic_Help());
- break;
- case "play":
- case "sound":
- case "sounds":
- res.AddRange(
- Enum.GetNames(typeof(Sound)));
- break;
-
- default:
- res.Add($"Kommando {prop} nicht gefunden");
- break;
- }
-
-
- if (persist == 1)
- {
- await this.ReplyAsync(res);
- }
- else
- {
- await this.ReplyAsync(res, TimeSpan.FromSeconds(90));
- }
- }
- }
-}
diff --git a/DiscoBot/Commands/MiscCommands.cs b/DiscoBot/Commands/MiscCommands.cs
index 53bc42c..2bc2fad 100644
--- a/DiscoBot/Commands/MiscCommands.cs
+++ b/DiscoBot/Commands/MiscCommands.cs
@@ -1,153 +1,110 @@
using System;
using System.Collections.Generic;
-using System.Runtime.Remoting.Contexts;
+using System.IO;
+using System.Linq;
using System.Text;
-
+using System.Threading.Tasks;
using DiscoBot.Auxiliary;
-
using Discord;
using Discord.Commands;
-using Discord.WebSocket;
namespace DiscoBot.Commands
{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Net.Mime;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game;
-
- using Discord;
- using Discord.Commands;
-
public class MiscCommands : ModuleBase
{
- [Command("r"), Summary("Würfelt ")]
+ [Command("r")]
+ [Summary("Würfelt ")]
[Alias("R", "Roll", "roll", "Würfle")]
- public Task RollAsync([Remainder, Summary("Weapon")] string roll)
+ public Task RollAsync([Remainder] [Summary("Weapon")] string roll)
{
//return this.ReplyAsync("```xl\n" + new Auxiliary.Calculator.StringSolver(roll).Solve() + "\n```");
- return this.ReplyAsync("```xl\n" + RandomMisc.Roll(roll) + "\n```");
- }
-
- [Command("rd"), Summary("Würfel Dennis ")]
- public Task RollDennisAsync([Remainder, Summary("Weapon")] string roll)
- {
- return this.ReplyAsync("```xl\n" + new Auxiliary.Calculator.StringSolver(roll).Solve() + "\n```");
+ return ReplyAsync("```xl\n" + RandomMisc.Roll(roll) + "\n```");
}
- [Command("general"), Summary("Set General ")]
- public Task SetGeneralAsync([Remainder, Summary("Set General")] int i = 0)
- {
- Dsa.GeneralContext = this.Context;
- return this.Context.Channel.SendMessageAsync($"```xl\n Der Dachs hat in '{this.Context.Channel.Name}' ein Zuhause gefunden. Gm Nachrichten werden nun auch in diesem Channel gepostet. \n```");
- }
- [Command("say"), Summary("Echos a message.")]
+ [Command("say")]
+ [Summary("Echos a message.")]
[Alias("s")]
- public Task SayAsync([Remainder, Summary("The text to echo")] string echo)
+ public Task SayAsync([Remainder] [Summary("The text to echo")]
+ string echo)
{
- return this.ReplyAsync(echo);
+ return ReplyAsync(echo);
}
- [Command("liebe"), Summary("Echos a message.")]
+ [Command("liebe")]
+ [Summary("Echos a message.")]
[Alias("Liebe", "<3", "love")]
public async Task LoveAsync()
{
- Random rand = new Random();
- var user = Context.Channel.GetUsersAsync().ToList().Result.ToList().First().Where(x=>x.Status!= UserStatus.Offline).OrderBy(x => rand.Next()).First();
- await this.ReplyAsync(":heart: :heart: :heart: Verteilt die Liebe! :heart: :heart: :heart: \n Besondere Liebe geht an " + user.Username);
+ var rand = new Random();
+ var user = Context.Channel.GetUsersAsync().ToList().Result.ToList().First()
+ .Where(x => x.Status != UserStatus.Offline).OrderBy(x => rand.Next()).First();
+ await ReplyAsync(
+ ":heart: :heart: :heart: Verteilt die Liebe! :heart: :heart: :heart: \n Besondere Liebe geht an " +
+ user.Username);
//await this.ReplyAsync("!liebe");
}
- [Command("maul"), Summary("Echos a message.")]
+ [Command("maul")]
+ [Summary("Echos a message.")]
public Task MaulAsync()
{
- return this.ReplyAsync("Maul...? Du meintest doch sicher Maulwürfe oder? \n:heart: :heart: :heart: \nGanz viel Liebe für Maulwürfe !\n:heart: :heart: :heart:");
-
+ return ReplyAsync(
+ "Maul...? Du meintest doch sicher Maulwürfe oder? \n:heart: :heart: :heart: \nGanz viel Liebe für Maulwürfe !\n:heart: :heart: :heart:");
}
- [Command("report"), Summary("Report a Tweet")]
- public async Task ReportAsync([Remainder, Summary("Link")] string link)
- {
- var content = new System.Net.Http.StringContent(link);
-
- using (HttpClient client = new HttpClient())
- {
- var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
- }
- await this.ReplyAsync($"Dein report wurde hinzugefügt");
- }
-
- [Command("match"), Summary("Tinder.")]
- [Alias("mach","pass", "passt")]
+ [Command("match")]
+ [Summary("Tinder.")]
+ [Alias("mach", "pass", "passt")]
public Task TinderAsync(string s1, string s2)
{
+ var rand = new Random((s1 + s2).GetHashCode());
- var sc = new SpellCorrect();
- var rand = new System.Random((s1+s2).GetHashCode());
-
- var wert = Math.Log10(Math.Floor(1000.0 * (SpellCorrect.CompareExact(s1, s2) + rand.NextDouble() * 10.0)) / 1000.0);
- wert = ((wert * 100.0) < 100.0 ? wert * 100.0 : 100.0 - wert);
+ var wert = Math.Log10(Math.Floor(1000.0 * (SpellCorrect.CompareExact(s1, s2) + rand.NextDouble() * 10.0)) /
+ 1000.0);
+ wert = wert * 100.0 < 100.0 ? wert * 100.0 : 100.0 - wert;
wert = wert < 0 ? -wert : wert;
- return this.ReplyAsync($"Ihr passt zu {Math.Floor(100.0 * wert )/ 100.0}% zusammen");
-
+ return ReplyAsync($"Ihr passt zu {Math.Floor(100.0 * wert) / 100.0}% zusammen");
}
- [Command("reddit"), Summary("Reddit.")]
+ [Command("reddit")]
+ [Summary("Reddit.")]
public Task RedditAsync()
{
- return this.ReplyAsync($"Ein Archiv der Vergangenen Aktionen findet man hier: https://www.reddit.com/r/ReconquistaInternet/");
-
+ return ReplyAsync(
+ "Ein Archiv der Vergangenen Aktionen findet man hier: https://www.reddit.com/r/ReconquistaInternet/");
}
- [Command("compare"), Summary("Echos a message.")]
+ [Command("compare")]
+ [Summary("Echos a message.")]
public async Task KickAsync()
{
//await this.Context.Guild.DownloadUsersAsync();
- var users = Context.Guild.GetUsersAsync(CacheMode.AllowDownload);
+ var users = Context.Guild.GetUsersAsync();
var test = File.ReadAllLines("RG.txt");
await users;
var us = users.Result.Select(x => x.Username);
-
+
var lines = test.Where(x => !x.Equals(string.Empty)).ToList();
-
+
var sc = new SpellCorrect();
var res = new List<string>();
- foreach (string line in lines)
+ foreach (var line in lines)
{
var best = us.OrderBy(user => sc.Compare(user, line)).First();
double fit = sc.Compare(best, line);
- if (fit < SpellCorrect.ErrorThreshold - 20000)
- {
- if (fit.Equals(0))
- {
- res.Add($"@\t{best} !!! => {line}");
- }
- else
- {
- res.Add($"-\t{best} hat Ähnlichkeit mit: {line}");
- }
- }
+ if (!(fit < SpellCorrect.ErrorThreshold - 20000)) continue;
+ res.Add(fit.Equals(0) ? $"@\t{best} !!! => {line}" : $"-\t{best} hat Ähnlichkeit mit: {line}");
}
var sb = new StringBuilder();
- foreach (string re in res)
+ foreach (var re in res)
{
if (sb.Length + re.Length > 1798)
{
@@ -158,47 +115,43 @@ namespace DiscoBot.Commands
sb.AppendLine(re);
}
- if(Permissions.Check(this.Context, new []{"Admin", "Mod"}))
- await this.ReplyTimedAsync(sb.ToString(), TimeSpan.FromSeconds(90));
+ if (Permissions.Check(Context, new[] {"Admin", "Mod"}))
+ await this.ReplyTimedAsync(sb.ToString(), TimeSpan.FromSeconds(90));
//await this.ReplyAsync($"{count} Duplikate gefunden");
-
}
- [Command("clear"), Summary("Cleans up messages.")]
+ [Command("clear")]
+ [Summary("Cleans up messages.")]
public async Task DeleteAsync(int count)
{
var messagesAsync = Context.Channel.GetMessagesAsync(count);
- Task.WaitAll(messagesAsync.ToArray());
- var list = messagesAsync.ToEnumerable().ToList();
- var messages = new List<IMessage>();
- foreach (var task in list)
+ if (messagesAsync != null)
{
- messages.AddRange(task.ToList());
- }
+ Task.WaitAll(messagesAsync.ToArray());
+ var list = messagesAsync.ToEnumerable().ToList();
+ var messages = new List<IMessage>();
+ foreach (var task in list) messages.AddRange(task.ToList());
- if (Permissions.Check(Context, new[] { "Admin", "Mod", "Meister" }))
- {
-
- var waiters = new List<Task>();
- foreach (var message in messages)
+ if (Permissions.Check(Context, new[] {"Admin", "Mod", "Meister"}))
{
- waiters.Add((message as IUserMessage).DeleteAsync());
- }
+ var waiters = new List<Task>();
+ foreach (var message in messages) waiters.Add(((IUserMessage) message).DeleteAsync());
- Task.WaitAll(waiters.ToArray());
+ Task.WaitAll(waiters.ToArray());
+ }
}
-
}
- [Command("check"), Summary("Echos a message.")]
+ [Command("check")]
+ [Summary("Echos a message.")]
[Alias("Check")]
public async Task CheckAsync(string quarry)
{
- var perm = new List<string> { "Admin", "Mod", "Privatpolizei" };
+ var perm = new List<string> {"Admin", "Mod", "Privatpolizei"};
- Permissions.Test(this.Context, perm.ToArray());
+ Permissions.Test(Context, perm.ToArray());
var test = File.ReadAllLines("RG.txt");
@@ -210,38 +163,27 @@ namespace DiscoBot.Commands
var fit = sc.Compare(count, quarry);
- string Antwort;
+ string antwort;
- if (fit < SpellCorrect.ErrorThreshold - 20000)
- {
- Antwort= $"```xl\nAuf anderem Server Match gefunden: {count}";
- }
- else
- {
- Antwort = $"```xl\nAuf anderem Server Kein Match gefunden: {quarry}";
- }
+ antwort = fit < SpellCorrect.ErrorThreshold - 20000
+ ? $"```xl\nAuf anderem Server Match gefunden: {count}"
+ : $"```xl\nAuf anderem Server Kein Match gefunden: {quarry}";
- var users = Context.Guild.GetUsersAsync(CacheMode.AllowDownload);
+ var users = Context.Guild.GetUsersAsync();
await users;
var us = users.Result.Select(x => x.Username);
-
+
sc = new SpellCorrect();
count = us.OrderBy(line => sc.Compare(quarry, line)).First();
fit = sc.Compare(count, quarry);
- if (fit < SpellCorrect.ErrorThreshold - 20000)
- {
- Antwort = Antwort + $"\nAuf unserem Server Match gefunden: {count}\n```";
- }
- else
- {
- Antwort = Antwort + $"\nAuf unserem Server Kein Match gefunden: {quarry} \n```";
- }
-
- await ReplyAsync(Antwort);
+ antwort = fit < SpellCorrect.ErrorThreshold - 20000
+ ? $"{antwort}\nAuf unserem Server Match gefunden: {count}\n```"
+ : $"{antwort}\nAuf unserem Server Kein Match gefunden: {quarry} \n```";
+ await ReplyAsync(antwort);
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Commands/NpcCommands.cs b/DiscoBot/Commands/NpcCommands.cs
deleted file mode 100644
index b314494..0000000
--- a/DiscoBot/Commands/NpcCommands.cs
+++ /dev/null
@@ -1,39 +0,0 @@
-namespace DiscoBot.Commands
-{
- using System;
- using System.Linq;
- using System.Threading.Tasks;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.Characters;
- using DiscoBot.DSA_Game;
- using DiscoBot.DSA_Game.Characters;
-
- using Discord.Commands;
-
- public class NpcCommands : ModuleBase
- {
- //[Command("npc"), Summary("Erstellt ein NPC")]
- [Alias("Npc", "NPc", "NPC", "nPC")]
- public Task RandomAsync([Summary("Create Random")] string npcName, int mean = 9, int stDv = 1)
- {
- Dsa.Chars.Add(new Npc(npcName, mean, stDv));
- return this.ReplyAsync($"{npcName} wurde zufällig generiert");
- }
-
- //[Command("npc"), Summary("Erstellt ein NPC")]
- [Alias("Npc", "NPc", "NPC", "nPC")]
- public Task CopyAsync([Summary("Create Copy")] string npcName, string source, int stDv = 1)
- {
- if (Dsa.Chars.Exists(x => x.Name.Equals(npcName)))
- {
- throw new Exception("Char gibt es schon");
- }
-
- var comp = new SpellCorrect();
- var chr = Dsa.Chars.OrderBy(x => comp.Compare(x.Name, source)).First();
- Dsa.Chars.Add(new Character(chr as Character, npcName, stDv));
- return this.ReplyAsync($"{npcName} wurde als variierte Kopie von {source} erstellt");
- }
- }
-} \ No newline at end of file
diff --git a/DiscoBot/Commands/ProbenTest.cs b/DiscoBot/Commands/ProbenTest.cs
deleted file mode 100644
index 77a10ad..0000000
--- a/DiscoBot/Commands/ProbenTest.cs
+++ /dev/null
@@ -1,91 +0,0 @@
-namespace DiscoBot.Commands
-{
- using System.Threading.Tasks;
-
- using DiscoBot.DSA_Game;
-
- using Discord.Commands;
-
- public class ProbenTest : ModuleBase
- {
- //[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)
- {
- string res;
- try
- {
- res = Gm.CheckCommand(
- Dsa.Session.Relation[this.Context.User.Username],
- CommandTypes.Talent,
- talent,
- erschwernis);
- }
- catch
- {
- res = Gm.CheckCommand(
- Dsa.Session.Relation["Tardis"],
- CommandTypes.Talent,
- talent,
- erschwernis);
- }
-
- return this.ReplyAsync("```xl\n" + res + "\n```");
- }
-
- //[Command("Zauber"), Summary("Würfelt ein Zauberprobe")]
- [Alias("Z", "zauber", "z")]
- public Task ZauberAsync([Summary("Zaubername")] string zauber, int erschwernis = 0)
- {
- string res;
- try
- {
- res = Gm.CheckCommand(
- Dsa.Session.Relation[this.Context.User.Username],
- CommandTypes.Zauber,
- zauber,
- erschwernis);
- }
- catch
- {
- res = Gm.CheckCommand(
- Dsa.Session.Relation["Tardis"],
- CommandTypes.Zauber,
- zauber,
- erschwernis);
- }
-
- return this.ReplyAsync("```xl\n" + res + "\n```");
- }
-
- //[Command("e"), Summary("Würfelt eine Eigenschaftsprobe")]
- [Alias("E", "Eigenschaft", "eigenschaft", "eigen")]
- public Task EigenschaftAsync([Summary("Eigenschaftskürzel und Erschwernis")] string talent, int erschwernis = 0)
- {
- var chr = Dsa.Chars.Find(x => x.Name.Equals(Dsa.Session.Relation[this.Context.User.Username]));
- string res = chr.TestEigenschaft(talent, erschwernis);
- return this.ReplyAsync("```xl\n" + res + "\n```");
- }
-
- //[Command("a"), Summary("Würfelt ein Angriff")]
- [Alias("A", "At", "at", "Angriff", "angriff", "attackiere_mit", "attacke", "Attacke")]
- public Task AngriffAsync([Summary("Weapon")] string weapon, int erschwernis = 0)
- {
- return this.ReplyAsync("```xl\n" + Dsa.Chars.Find(x => x.Name.Equals(Dsa.Session.Relation[this.Context.User.Username])).Angriff(weapon, erschwernis) + "\n```");
- }
-
- //[Command("p"), Summary("Würfelt eine Parade Probe")]
- [Alias("P", "Parade", "parade", "pariere_mit")]
- public Task ParadeAsync([Summary("Parade Weapon")] string talent, int erschwernis = 0)
- {
- return this.ReplyAsync("```xl\n" + Dsa.Chars.Find(x => x.Name.Equals(Dsa.Session.Relation[this.Context.User.Username])).Parade(talent, erschwernis) + "\n```");
- }
-
- //[Command("f"), Summary("Führt eine Fernkampfprobe aus")]
- [Alias("F", "fern", "Fern", "Schuss", "schuss", "fernkampf", "Fernkampf", "schieße", "schieße_mit")]
- public Task FernkampfAsync([Summary("Fernkampfwaffe")] string waffe, int erschwernis = 0)
- {
- return this.ReplyAsync("```xl\n" + Dsa.Chars.Find(x => x.Name.Equals(Dsa.Session.Relation[this.Context.User.Username])).Fernkampf(waffe, erschwernis) + "\n```");
- }
- }
-}
diff --git a/DiscoBot/DSA_Game/Characters/Character.cs b/DiscoBot/DSA_Game/Characters/Character.cs
deleted file mode 100644
index 81c11fc..0000000
--- a/DiscoBot/DSA_Game/Characters/Character.cs
+++ /dev/null
@@ -1,303 +0,0 @@
-using DSALib;
-using DSALib.Characters;
-
-namespace DiscoBot.DSA_Game.Characters
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Xml;
-
- using DiscoBot.Audio;
- using DiscoBot.Auxiliary;
-
- public class Character : Being, ICharacter
- {
- public Character()
- {
- this.PropTable.Add("MU", "Mut"); // routing
- this.PropTable.Add("KL", "Klugheit");
- this.PropTable.Add("IN", "Intuition");
- this.PropTable.Add("CH", "Charisma");
- this.PropTable.Add("FF", "Fingerfertigkeit");
- this.PropTable.Add("GE", "Gewandtheit");
- this.PropTable.Add("KO", "Konstitution");
- this.PropTable.Add("KK", "Körperkraft");
-
- }
-
- public Character(string path) : this()
- {
- this.Load(path); // load
- this.Post_process(); // calculate derived values
- }
-
- public Character(Character c, string name, int stDv = 2) : this()
- {
- this.Name = name;
- foreach (var i in c.Eigenschaften)
- {
- this.Eigenschaften.Add(i.Key, i.Value + (int)Math.Round(RandomMisc.Random(stDv)));
- }
-
- foreach (var i in c.Vorteile)
- {
- this.Vorteile.Add(new Vorteil(i.Name, i.Value + (int)Math.Round(RandomMisc.Random(stDv))));
- }
-
- foreach (var i in c.Talente)
- {
- this.Talente.Add(new Talent(i.Name, i.Probe, i.Value + (int)Math.Round(RandomMisc.Random(stDv))));
- }
-
- foreach (var i in c.Zauber)
- {
- this.Zauber.Add(new Zauber(i.Name, i.Probe, i.Value + (int)Math.Round(RandomMisc.Random(stDv)), i.Complexity, i.Representation));
- }
-
- foreach (var i in c.Kampftalente)
- {
- this.Kampftalente.Add(new KampfTalent(i.Name, i.At + (int)Math.Round(RandomMisc.Random(stDv)), i.Pa + (int)Math.Round(RandomMisc.Random(stDv))));
- }
-
- this.Post_process(); // calculate derived values
- }
-
- public Dictionary<string, int> Eigenschaften { get; set; } = new Dictionary<string, int>(); // char properties
-
- public List<Talent> Talente { get; set; } = new List<Talent>(); // list of talent objects (talents)
-
- public List<Zauber> Zauber { get; set; } = new List<Zauber>(); // list of spell objects
-
- public List<KampfTalent> Kampftalente { get; set; } = new List<KampfTalent>(); // list of combat objects
-
- public List<Vorteil> Vorteile { get; set; } = new List<Vorteil>();
-
- public Dictionary<string, string> PropTable { get; set; } = new Dictionary<string, string>(); // -> Körperkraft
-
- public string TestTalent(string talent, int erschwernis = 0) // Talentprobe
- {
- return this.Talente.ProbenTest(this, talent, erschwernis);
- }
-
- public string TestZauber(string zauber, int erschwernis = 0) // Talentprobe
- {
- return this.Zauber.ProbenTest(this, zauber, erschwernis);
- }
-
- public string TestEigenschaft(string eigenschaft, int erschwernis = 0)
- {
- var output = new StringBuilder();
- var prop = this.PropTable[eigenschaft.ToUpper()];
- int tap = this.Eigenschaften[prop];
- output.AppendFormat(
- "{0}-Eigenschaftsprobe ew:{1} {2} \n",
- prop,
- tap,
- erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
- int roll = Dice.Roll();
- output.Append($"Gewürfelt: {roll} übrig: {tap - roll - erschwernis}");
- return output.ToString();
- }
-
- public string Angriff(string talent, int erschwernis = 0) // pretty self explanatory
- {
- var output = new StringBuilder();
- var sc = new SpellCorrect();
- var attack = this.Kampftalente.OrderBy(x => sc.Compare(talent, x.Name)).First();
- if (sc.Compare(talent, attack.Name) > SpellCorrect.ErrorThreshold)
- {
- try
- {
- SoundEffects.Play("Wrong");
- }
- catch { }
-
- return $"{this.Name} kann nicht mit der Waffenart {talent} umgehen...";
- }
-
- int tap = attack.At;
- output.AppendFormat(
- "{0}-Angriff taw:{1} {2} \n",
- attack.Name,
- tap,
- erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
-
- int temp = Dice.Roll();
- output.Append(temp - erschwernis);
- return output.ToString();
- }
-
- public string Parade(string talent, int erschwernis = 0)
- {
- var output = new StringBuilder();
- var sc = new SpellCorrect();
- var attack = this.Kampftalente.OrderBy(x => sc.Compare(talent, x.Name)).First();
-
- if (sc.Compare(talent, attack.Name) > SpellCorrect.ErrorThreshold)
- {
- try
- {
- SoundEffects.Play("Wrong");
- }
- catch { }
- return $"{this.Name} kann nicht mit der Waffenart {talent} umgehen...";
- }
-
- int tap = attack.Pa;
- output.AppendFormat(
- "{0}-Parade taw:{1} {2}\n",
- attack.Name,
- tap,
- erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
-
- int temp = Dice.Roll();
- output.Append(temp - erschwernis);
- return output.ToString();
- }
-
- public string Fernkampf(string talent, int erschwernis = 0)
- {
- var output = new StringBuilder();
- var sc = new SpellCorrect();
- int fk = this.Eigenschaften["fk"];
- var attack = this.Talente.OrderBy(x => sc.Compare(talent, x.Name)).First();
- if (sc.Compare(talent, attack.Name) > SpellCorrect.ErrorThreshold)
- {
- try
- {
- SoundEffects.Play("Wrong");
- }
- catch { }
- return $"{this.Name} kann nicht mit der Waffenart {talent} umgehen...";
- }
-
- int tap = attack.Value;
- output.AppendFormat(
- "{0} taw:{1} {2} \n",
- attack.Name,
- tap,
- erschwernis.Equals(0) ? string.Empty : "Erschwernis: " + erschwernis);
- tap -= erschwernis;
- int temp = Dice.Roll();
- tap -= temp > fk ? temp - fk : 0;
- output.Append($"W20: {temp} tap: {tap}");
- return output.ToString();
- }
-
- private void Post_process()
- {
- var LE_Wert = this.Eigenschaften["Lebensenergie"];
- var AE_Wert = this.Eigenschaften.First(s => s.Key.Contains("Astralenergie")).Value;
-
- //var KL_Wert = this.Eigenschaften.First(s => s.Key.Contains("Klugheit")).Value;
- var MU_Wert = this.Eigenschaften.First(s => s.Key.Contains("Mut")).Value;
- var IN_Wert = this.Eigenschaften.First(s => s.Key.Contains("Intuition")).Value;
- var CH_Wert = this.Eigenschaften.First(s => s.Key.Contains("Charisma")).Value;
- var KK_Wert = this.Eigenschaften["Körperkraft"];
- var KO__Wert = this.Eigenschaften["Konstitution"];
-
- this.Astralpunkte_Basis = 0;
-
- this.Ausdauer_Basis = 0;
-
- this.Lebenspunkte_Basis = LE_Wert + (int)(KO__Wert + (KK_Wert / 2.0) + 0.5);
-
- if (this.Vorteile.Exists(x => x.Name.ToLower().Contains("zauberer")))
- {
- this.Astralpunkte_Basis = AE_Wert + (int)((MU_Wert + IN_Wert + CH_Wert) / 2.0 + 0.5);
- }
-
- this.Lebenspunkte_Aktuell = this.Lebenspunkte_Basis;
- this.Astralpunkte_Aktuell = this.Astralpunkte_Basis;
- this.Ausdauer_Aktuell = this.Ausdauer_Basis;
-
- }
-
-
- private void Load(string path)
- {
- var reader = new XmlTextReader(path);
- while (reader.Read())
- {
- // read until he hits keywords
- if (reader.NodeType != XmlNodeType.Element)
- {
- continue;
- }
-
- switch (reader.Name)
- {
- case "Wesen":
- reader.Skip();
- break;
- case "held":
- this.Name = reader.GetAttribute("name"); // name
- break;
- case "eigenschaft":
- this.Eigenschaften.Add(
- reader.GetAttribute("name") ?? throw new InvalidOperationException(),
- Convert.ToInt32(reader.GetAttribute("value")) + Convert.ToInt32(reader.GetAttribute("mod")));
- break;
- case "vt":
- reader.Read();
- while (reader.Name.Equals("vorteil"))
- {
- try
- {
- this.Vorteile.Add(new Vorteil(
- reader.GetAttribute("name"),
- // Convert.ToInt32(reader.GetAttribute("value"))));
- reader.GetAttribute("value")));
- }
- catch
- {
- this.Vorteile.Add(new Vorteil(reader.GetAttribute("name")));
- }
-
- reader.Read();
- }
-
- break;
- case "talentliste":
- reader.Read();
- while (reader.Name.Equals("talent"))
- {
- this.Talente.Add(
- new Talent(
- reader.GetAttribute("name"),
- reader.GetAttribute("probe")?.Remove(0, 2).Trim(')'),
- Convert.ToInt32(reader.GetAttribute("value"))));
- reader.Read();
- }
-
- break;
- case "zauberliste":
- reader.Read();
- while (reader.Name.Equals("zauber"))
- {
- this.Zauber.Add(
- new Zauber(
- reader.GetAttribute("name"),
- reader.GetAttribute("probe")?.Remove(0, 2).Trim(')'),
- Convert.ToInt32(reader.GetAttribute("value")),
- reader.GetAttribute("k").ToCharArray()[0],
- reader.GetAttribute("repraesentation")));
- reader.Read();
- }
-
- break;
- case "kampfwerte":
- string atName = reader.GetAttribute("name");
- reader.Read();
- int at = Convert.ToInt32(reader.GetAttribute("value"));
- reader.Read();
- int pa = Convert.ToInt32(reader.GetAttribute("value"));
- this.Kampftalente.Add(new KampfTalent(atName, at, pa));
- break;
- }
- }
- }
- }
-} \ No newline at end of file
diff --git a/DiscoBot/DSA_Game/Characters/NPC.cs b/DiscoBot/DSA_Game/Characters/NPC.cs
deleted file mode 100644
index b1b8e82..0000000
--- a/DiscoBot/DSA_Game/Characters/NPC.cs
+++ /dev/null
@@ -1,112 +0,0 @@
-namespace DiscoBot.Characters
-{
- using System;
-
- using DiscoBot.Auxiliary;
- using DiscoBot.DSA_Game.Characters;
- using DSALib.Characters;
-
- public class Npc : Being, ICharacter
- {
- private readonly int mean, stDv;
-
- public Npc(string name, int mean, int stDv)
- {
- this.mean = mean;
- this.stDv = stDv;
- this.Name = name;
- }
-
- public string TestTalent(string talent, int tap = 3)
- {
- for (int i = 0; i <= 2; i++)
- {
- // foreach property, dice and tap
- int temp = Dice.Roll();
- int eigenschaft = (int)Math.Round(RandomMisc.Random(this.stDv, this.mean));
-
- if (eigenschaft < temp)
- {
- tap -= temp - eigenschaft;
- }
- }
-
- if (tap >= 0)
- {
- return $"{this.Name} vollführt {talent} erfolgreich";
- }
-
-
- return $"{this.Name} scheitert an {talent}";
- }
-
- public string TestEigenschaft(string eigenschaft, int erschwernis = 0)
- {
- int temp = Dice.Roll();
- int prop = (int)Math.Round(RandomMisc.Random(this.stDv, this.stDv));
-
- if (temp + erschwernis < prop)
- {
- return $"{this.Name} vollführt {eigenschaft} erfolgreich";
- }
-
- return $"{this.Name} scheitert an {eigenschaft}";
- }
-
- public string Angriff(string waffe, int erschwernis = 0)
- {
- int temp = Dice.Roll();
-
- if (temp == 1)
- {
- return $"{this.Name} greift kritisch mit {waffe} an";
- }
-
- if (temp < erschwernis)
- {
- return $"{this.Name} greift mit {waffe} an";
- }
-
- return $"{this.Name} haut mit {waffe} daneben";
- }
-
- public string Parade(string waffe, int erschwernis = 0)
- {
- int temp = Dice.Roll();
-
- if (temp == 1)
- {
- return $"{this.Name} pariert mit {waffe} meisterlich";
- }
-
- if (temp < erschwernis)
- {
- return $"{this.Name} pariert mit {waffe} an";
- }
-
- return $"{this.Name} schafft es nicht mit {waffe} zu parieren";
- }
-
- public string Fernkampf(string waffe, int erschwernis = 0)
- {
- int temp = Dice.Roll();
-
- if (temp == 1)
- {
- return $"{this.Name} trifft kritisch mit {waffe}";
- }
-
- if (temp < erschwernis)
- {
- return $"{this.Name} greift mit {waffe} an";
- }
-
- return $"{this.Name} schießt mit {waffe} daneben";
- }
-
- public string TestZauber(string zauber, int erschwernis)
- {
- return TestTalent(zauber, erschwernis);
- }
- }
-}
diff --git a/DiscoBot/DSA_Game/Characters/SaveChar.cs b/DiscoBot/DSA_Game/Characters/SaveChar.cs
deleted file mode 100644
index 272f516..0000000
--- a/DiscoBot/DSA_Game/Characters/SaveChar.cs
+++ /dev/null
@@ -1,45 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.DSA_Game.Characters
-{
- using Discord;
- using DSALib.Characters;
-
- public class SaveChar
- {
- public string Name { get; set; }
-
- public int Lebenspunkte_Aktuell { get; set; }
-
- public int Ausdauer_Aktuell { get; set; }
-
- public int Astralpunkte_Aktuell { get; set; }
-
- public static SaveChar FromICharacter(ICharacter c)
- {
- return new SaveChar
- {
- Astralpunkte_Aktuell = c.Astralpunkte_Aktuell,
- Ausdauer_Aktuell = c.Ausdauer_Aktuell,
- Lebenspunkte_Aktuell = c.Lebenspunkte_Aktuell,
- Name = c.Name
- };
- }
- }
-
-
- 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;
- c.Name = s.Name;
- }
- }
-}
diff --git a/DiscoBot/DSA_Game/Dsa.cs b/DiscoBot/DSA_Game/Dsa.cs
deleted file mode 100644
index fd60c9a..0000000
--- a/DiscoBot/DSA_Game/Dsa.cs
+++ /dev/null
@@ -1,72 +0,0 @@
-using DSALib;
-using DSALib.Characters;
-
-namespace DiscoBot.DSA_Game
-{
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
-
- using DiscoBot.Audio;
- using DiscoBot.Commands;
- using DiscoBot.DSA_Game.Characters;
- using DiscoBot.DSA_Game.Save;
-
- using Discord.Commands;
-
- public static class Dsa
- {
- private static Session s_session;
-
- public static ICommandContext GeneralContext { get; set; }
-
- public static AudioService Service { get; set; }
-
- public static List<ICharacter> Chars { get; set; } = new List<ICharacter>(); // list of all characters
-
- public static List<Talent> Talente { get; set; } = new List<Talent>();
-
- public static Session Session
- {
- get
- {
- s_session.Chars = Chars.Select(x => SaveChar.FromICharacter(x)).ToList();
- return s_session;
- }
-
- set
- {
- s_session = value;
- foreach (var x in value.Chars)
- {
- Chars.Find(c => c.Name.Equals(x.Name)).Update(x);
- }
- }
- }
-
- public static void Startup()
- {
- //new DiscoBot.Auxiliary.Calculator.StringSolver("1d100 - (1d200 + 1) * -50000").Solve();
- /*Session = new Session();*/
- // relation.Add("Papo", "Pump aus der Gosse");
- foreach (var filename in Directory.GetFiles("helden", "*.xml"))
- {
- Chars.Add(new Character(filename));
- (Chars.Last() as Character)?.Talente.Select(x => new Talent(x.Name, x.Probe, 0))
- .Where(c => !Talente.Exists(v => v.Name.Equals(c.Name))).ToList().ForEach(v => Talente.Add(v));
- }
-
- Properties.Deserialize();
- Properties.Serialize();
-
- Talente = Talente.OrderBy(x => x.Name).ToList();
- Session = new Session
- {
- Chars = Chars.Select(x => SaveChar.FromICharacter(x)).ToList(),
- GeneralContext = GeneralContext
- };
- Session.Save();
- }
- }
-} \ No newline at end of file
diff --git a/DiscoBot/DSA_Game/Save/Properties.cs b/DiscoBot/DSA_Game/Save/Properties.cs
deleted file mode 100644
index 67d30b0..0000000
--- a/DiscoBot/DSA_Game/Save/Properties.cs
+++ /dev/null
@@ -1,88 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.DSA_Game.Save
-{
- using System.Collections;
- using System.IO;
- using System.Reflection;
- using System.Runtime.CompilerServices;
-
- using DiscoBot.Audio;
- using DiscoBot.Auxiliary;
- using DiscoBot.Commands;
-
- using Discord;
-
- using Newtonsoft.Json;
-
- public static class Properties
- {
- private static Dictionary<string, object> objects;
-
- static Properties()
- {
- objects = new Dictionary<string, object>();
- /*this.objects.Add("Sounds", new List<Sound>());
- this.objects.Add("CommandInfos", new List<CommandInfo>());*/
- }
-
- public static List<CommandInfo> CommandInfos { get => objects["CommandInfo"] as List<CommandInfo>; set => objects["CommandInfo"] = value; } // use Properties.Commandinfos to access the abstract Object array
-
- public static List<Sound> Sounds { get => objects["Sound"] as List<Sound>; set => objects["Sound"] = value; }
-
- public static void Deserialize(string path = @"..\..\Properties")
- {
-
- var files = Directory.GetFiles(path, "*.json");
-
- foreach (string file in files)
- {
- try
- {
- string name = file.Split('\\').Last().Split('.')[0].Replace('-', '.');
- string data = File.ReadAllText(file);
- Type type = Type.GetType(name);
- if (data.StartsWith("["))
- {
- type = typeof(List<>).MakeGenericType(type);
- }
-
- var o = JsonConvert.DeserializeObject(data, type);
- objects.Add(name.Split('.').Last(), o);
- }
- catch (Exception e)
- {
- // ignored
- var log = new LogMessage(LogSeverity.Warning, "Properties", $"Laden von Save-File {file} fehlgeschlagen.", e);
- Console.WriteLine(log);
- }
-
- }
-
- }
-
- public static void Serialize(string path = @"..\..\Properties\")
- {
- try
- {
- foreach (var o in objects)
- {
- string assembly = o.Value is IList list ? ((IList)list)[0]?.GetType().FullName : o.Value.GetType().FullName;
-
- var name = path + assembly.Replace('.', '-') + ".json";
- File.WriteAllText(name, JsonConvert.SerializeObject(o.Value, Formatting.Indented)); // Deserialize Data and create CommandInfo Struct
- }
- }
- catch (Exception e)
- {
- // ignored
- var log = new LogMessage(LogSeverity.Warning, "Properties", $"Speichern von Save-File fehlgeschlagen.", e);
- Console.WriteLine(log);
- }
- }
- }
-}
diff --git a/DiscoBot/DSA_Game/Save/SaveCommand.cs b/DiscoBot/DSA_Game/Save/SaveCommand.cs
deleted file mode 100644
index 1f160ec..0000000
--- a/DiscoBot/DSA_Game/Save/SaveCommand.cs
+++ /dev/null
@@ -1,82 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.DSA_Game.Save
-{
- using System.Diagnostics;
- using System.IO;
- using System.Net;
- using System.Net.Http;
-
- using DiscoBot.Auxiliary;
-
- using Discord.Commands;
-
- public class SaveCommand : ModuleBase
- {
- [Command("load"), Summary("Load Session")]
- [Alias("session")]
- public async Task LoadSessionAsync([Remainder, Summary("Session Name")] string name = "")
- {
- if (name.Equals("?") || name.Equals(string.Empty))
- {
- await this.ReplyAsync($"Gespeicherte Sessions:");
- await this.ReplyAsync(this.ListSessions());
- return;
- }
-
- var path = DSA_Game.Save.Session.DirectoryPath + @"\" + name;
-
- var files = Directory.GetFiles(path);
- var session = files.OrderByDescending(x => Convert.ToInt32(x.Split('-').Last().Split('.').First())).First();
- Dsa.Session = Session.Load(session);
-
- await this.ReplyAsync($"{name} wurde geladen");
- }
-
- [Command("save", RunMode = RunMode.Async), Summary("Save Session")]
- public async Task SessionSaveAsync([Remainder, Summary("Session Name")] string name = "")
- {
- //var sendFile = this.Context.Channel.SendWebFile("https://cdn.discordapp.com/attachments/377123019673567232/465615882048110603/giphy.gif");
-
- if (name.Equals("?") || name.Equals(string.Empty))
- {
- await this.ReplyAsync($"Gespeicherte Sessions:");
- await this.ReplyAsync(this.ListSessions());
- return;
- }
-
- var path = DSA_Game.Save.Session.DirectoryPath + @"\" + name;
- if (Directory.Exists(path))
- {
- var files = Directory.GetFiles(path);
- int current = files.Max(x => Convert.ToInt32(x.Split('-').Last().Split('.').First()));
- Dsa.Session.SessionName = name;
- Dsa.Session.Save(path + "\\" + name + $"-{++current}.json");
- }
- else
- {
- Directory.CreateDirectory(path);
- Dsa.Session.SessionName = name;
- Dsa.Session.Save(path + "\\" + name + $"-0.json");
- }
-
- await this.ReplyAsync($"{name} wurde gespeichert");
- //await sendFile;
- }
-
- private string[] ListSessions()
- {
- string[] dirs = Directory.GetDirectories(Session.DirectoryPath).OrderByDescending(x => new DirectoryInfo(x).LastAccessTime.Ticks).ToArray();
- for (int i = 0; i < dirs.Length; i++)
- {
- dirs[i] += "; " + new DirectoryInfo(dirs[i]).LastAccessTime;
- }
-
- return dirs;
- }
- }
-}
diff --git a/DiscoBot/DSA_Game/Save/Session.cs b/DiscoBot/DSA_Game/Save/Session.cs
deleted file mode 100644
index 578fa50..0000000
--- a/DiscoBot/DSA_Game/Save/Session.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.DSA_Game.Save
-{
- using System.IO;
- using System.Runtime.CompilerServices;
-
- using DiscoBot.DSA_Game.Characters;
-
- using Discord;
- using Discord.Commands;
-
- using Newtonsoft.Json;
-
- public class Session
- {
- public static string DirectoryPath { get; set; } = @"..\..\sessions";
-
- public ICommandContext GeneralContext { get; set; }
-
- public Dictionary<string, string> Relation { get; set; } = new Dictionary<string, string>(); // dictionary to match the char
-
- public List<SaveChar> Chars { get; set; } = new List<SaveChar>(); // list of all characters
-
- public string SessionName { get; set; }
-
- public static Session Load(string path = @"..\..\session.json")
- {
- try
- {
- return JsonConvert.DeserializeObject<Session>(File.ReadAllText(path)); // Deserialize Data and create Session Object
- }
- catch (Exception e)
- {
- // ignored
- var log = new LogMessage(LogSeverity.Warning, "Properties", $"Laden von Save-File {path} fehlgeschlagen.", e);
- Console.WriteLine(log);
- return null;
- }
- }
-
- public void Save(string path = @"..\..\session.json")
- {
- try
- {
- File.WriteAllText(path, JsonConvert.SerializeObject(this, Formatting.Indented)); // Deserialize Data and create CommandInfo Struct
- }
- catch (Exception e)
- {
- var log = new LogMessage(LogSeverity.Warning, "Properties", $"Speichern von Save-File {path} fehlgeschlagen.", e);
- Console.WriteLine(log);
- // ignored
- }
- }
- }
-}
diff --git a/DiscoBot/DiscoBot.csproj b/DiscoBot/DiscoBot.csproj
index d25a5e9..28f81a8 100644
--- a/DiscoBot/DiscoBot.csproj
+++ b/DiscoBot/DiscoBot.csproj
@@ -97,38 +97,14 @@
<Compile Include="Audio\AudioModule.cs" />
<Compile Include="Audio\AudioService.cs" />
<Compile Include="Audio\Sound.cs" />
- <Compile Include="Auxiliary\Calculator\Argument.cs" />
- <Compile Include="Auxiliary\Calculator\ISolvable.cs" />
- <Compile Include="Auxiliary\Calculator\Operator.cs" />
- <Compile Include="Auxiliary\Calculator\Ops.cs" />
- <Compile Include="Auxiliary\Calculator\StringSolver.cs" />
- <Compile Include="Auxiliary\CommandInfo.cs" />
- <Compile Include="Auxiliary\Extensions.cs" />
- <Compile Include="DSA_Game\Characters\Character.cs" />
- <Compile Include="DSA_Game\Characters\NPC.cs" />
- <Compile Include="DSA_Game\Characters\SaveChar.cs" />
- <Compile Include="Commands\Help.cs" />
+ <Compile Include="Auxiliary\CommandExtension.cs" />
<Compile Include="Auxiliary\Dice.cs" />
- <Compile Include="Auxiliary\TalentEnumerableExtension.cs" />
- <Compile Include="Commands\LebenUndAstral.cs" />
- <Compile Include="Commands\HeldList.cs" />
- <Compile Include="Audio\Soundeffects.cs" />
- <Compile Include="ToRework\Permissions.cs" />
+ <Compile Include="Auxiliary\Permissions.cs" />
<Compile Include="Commands\MiscCommands.cs" />
<Compile Include="Auxiliary\SpellCorrect.cs" />
- <Compile Include="DSA_Game\Save\Properties.cs" />
- <Compile Include="DSA_Game\Save\SaveCommand.cs" />
- <Compile Include="DSA_Game\Save\Session.cs" />
- <Compile Include="ToRework\CommandExtension.cs" />
- <Compile Include="Commands\CommandTypes.cs" />
<Compile Include="Commands\FileHandler.cs" />
- <Compile Include="Commands\Gm.cs" />
- <Compile Include="Commands\List.cs" />
- <Compile Include="Commands\NpcCommands.cs" />
- <Compile Include="Commands\ProbenTest.cs" />
<Compile Include="Audio\Voice.cs" />
<Compile Include="Auxiliary\RandomMisc.cs" />
- <Compile Include="DSA_Game\Dsa.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Settings.Designer.cs">
@@ -152,6 +128,9 @@
<Name>DSALib</Name>
</ProjectReference>
</ItemGroup>
+ <ItemGroup>
+ <Folder Include="ToRework" />
+ </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets" Condition="Exists('..\packages\NETStandard.Library.2.0.3\build\netstandard2.0\NETStandard.Library.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
diff --git a/DiscoBot/Program.cs b/DiscoBot/Program.cs
index 5dc69c1..6ddac5d 100644
--- a/DiscoBot/Program.cs
+++ b/DiscoBot/Program.cs
@@ -1,123 +1,105 @@
using System;
+using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
-
+using DiscoBot.Audio;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
-using Microsoft.Extensions.DependencyInjection;
-
namespace DiscoBot
{
- using System.IO;
-
- using DiscoBot.Audio;
- using DiscoBot.DSA_Game;
-
public class Program
{
- private CommandService commands;
private DiscordSocketClient client;
+ private CommandService commands;
private IServiceProvider services;
- public static void Main(string[] args) => new Program().StartAsync().GetAwaiter().GetResult();
+ public static void Main(string[] args)
+ {
+ new Program().StartAsync().GetAwaiter().GetResult();
+ }
public async Task StartAsync()
{
- Dsa.Startup();
-
- this.client = new DiscordSocketClient();
- this.commands = new CommandService();
-
+ client = new DiscordSocketClient();
+ commands = new CommandService();
- string token = File.ReadAllText("Token");
+ var token = File.ReadAllText("Token");
//Properties.Settings.Default.Token;
-
+
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
- await this.InstallCommandsAsync();
+ await InstallCommandsAsync();
+
+ await client.LoginAsync(TokenType.Bot, token);
+ await client.StartAsync();
- await this.client.LoginAsync(TokenType.Bot, token);
- await this.client.StartAsync();
-
await Task.Delay(-1);
}
public Task InstallCommandsAsync()
{
// Hook the MessageReceived Event into our Command Handler
- this.client.MessageReceived += this.HandleCommandAsync;
-
+ client.MessageReceived += HandleCommandAsync;
+
// Discover all of the commands in this assembly and load them.
- return this.commands.AddModulesAsync(Assembly.GetEntryAssembly());
+ return commands.AddModulesAsync(Assembly.GetEntryAssembly());
}
public async Task HandleCommandAsync(SocketMessage messageParam)
{
// Don't process the command if it was a System Message
- if (!(messageParam is SocketUserMessage message))
- {
- return;
- }
+ if (!(messageParam is SocketUserMessage message)) return;
// Create a number to track where the prefix ends and the command begins
- int argPos = 0;
+ var argPos = 0;
// Determine if the message is a command, based on if it starts with '!' or a mention prefix
- if (!(message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(this.client.CurrentUser, ref argPos)))
- {
- return;
- }
+ if (!(message.HasCharPrefix('!', ref argPos) ||
+ message.HasMentionPrefix(client.CurrentUser, ref argPos))) return;
+
-
// Create a Command Context
- var context = new CommandContext(this.client, message);
-
+ var context = new CommandContext(client, message);
+
// Execute the command. (result does not indicate a return value,
// rather an object stating if the command executed successfully)
- var result = await this.commands.ExecuteAsync(context, argPos, this.services);
+ var result = await commands.ExecuteAsync(context, argPos, services);
if (result.Error == CommandError.UnknownCommand)
- {
- await context.Channel.SendMessageAsync(SendCommand(message.Author.Username, message.Content, "https://localhost:44365/api/Commands"));
- }
- else if (!result.IsSuccess)
- {
- await context.Channel.SendMessageAsync(result.ErrorReason);
- }
+ await context.Channel.SendMessageAsync(SendCommand(message.Author.Username, message.Content,
+ "https://kobert.dev/api/dsa/commands"));
+ else if (!result.IsSuccess) await context.Channel.SendMessageAsync(result.ErrorReason);
}
- private string SendCommand(string name, string command, string url)
+ private static string SendCommand(string name, string command, string url)
{
- var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
+ var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
- command = command.Remove(0,1);
- var args = command.Split(new []{' '}, StringSplitOptions.RemoveEmptyEntries);
+ command = command.Remove(0, 1);
+ var args = command.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
+
+ var content = string.Empty;
+ if (args.Length > 1) content = "\"" + args.Skip(1).Aggregate((s, n) => s + "\", \"" + n) + "\"";
- string content = string.Empty;
- if (args.Length > 1)
- {
- content = "\"" + args.Skip(1).Aggregate((s, n) => ( s + "\", \"" + n)) + "\"";
- }
+ var json = "{\"Name\":\"" + name + "\"," +
+ "\"CmdIdentifier\":\"" + args.First() + "\"," +
+ "\"CmdTexts\": [" + content + "] }";
- string json = "{\"Name\":\"" + name + "\"," +
- "\"CmdIdentifier\":\"" + args.First() + "\"," +
- "\"CmdTexts\": ["+ content+"] }";
-
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
- var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
+ var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
return streamReader.ReadToEnd();
@@ -130,4 +112,4 @@ namespace DiscoBot
Voice.Client.StopAsync();
}
}
-}
+} \ No newline at end of file
diff --git a/DiscoBot/Properties/AssemblyInfo.cs b/DiscoBot/Properties/AssemblyInfo.cs
index 1ff6b8f..b0c2901 100644
--- a/DiscoBot/Properties/AssemblyInfo.cs
+++ b/DiscoBot/Properties/AssemblyInfo.cs
@@ -1,5 +1,4 @@
using System.Reflection;
-using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
@@ -33,4 +32,4 @@ using System.Runtime.InteropServices;
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file
diff --git a/DiscoBot/ToRework/Permissions.cs b/DiscoBot/ToRework/Permissions.cs
deleted file mode 100644
index 4d73146..0000000
--- a/DiscoBot/ToRework/Permissions.cs
+++ /dev/null
@@ -1,43 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace DiscoBot.Auxiliary
-{
- using Discord.Commands;
- using Discord.WebSocket;
-
- public static class Permissions
- {
- public static bool Check(ICommandContext c, string role)
- {
- return ((SocketGuildUser)c.User).Roles.ToList().Exists(v => v.Name.Equals(role));
- }
-
- public static bool Check(ICommandContext c, string[] roles)
- {
- return roles.Any(role => ((SocketGuildUser)c.User).Roles.ToList().Exists(v => v.Name.Equals(role)));
- }
-
- public static bool Test(ICommandContext c, string role)
- {
- if (!Check(c, role))
- {
- c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait();
- return false;
- }
-
- return true;
- }
-
- public static void Test(ICommandContext c, string[] roles)
- {
- if (!Check(c, roles))
- {
- c.Channel.SendMessageAsync("```xl\n Keine ausreichenden Berechtigungen\n```").Wait();
- }
- }
- }
-}
diff --git a/FireBase/ExceptionEventArgs.cs b/FireBase/ExceptionEventArgs.cs
index f1c7fac..09c205a 100644
--- a/FireBase/ExceptionEventArgs.cs
+++ b/FireBase/ExceptionEventArgs.cs
@@ -1,21 +1,21 @@
-namespace Firebase.Database
-{
- using System;
+using System;
+namespace Firebase.Database
+{
/// <summary>
- /// Event args holding the <see cref="Exception"/> object.
+ /// Event args holding the <see cref="Exception" /> object.
/// </summary>
public class ExceptionEventArgs<T> : EventArgs where T : Exception
{
public readonly T Exception;
/// <summary>
- /// Initializes a new instance of the <see cref="ExceptionEventArgs"/> class.
+ /// Initializes a new instance of the <see cref="ExceptionEventArgs" /> class.
/// </summary>
/// <param name="exception"> The exception. </param>
public ExceptionEventArgs(T exception)
{
- this.Exception = exception;
+ Exception = exception;
}
}
@@ -25,4 +25,4 @@
{
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Extensions/ObservableExtensions.cs b/FireBase/Extensions/ObservableExtensions.cs
index 12cd5f3..0a672d7 100644
--- a/FireBase/Extensions/ObservableExtensions.cs
+++ b/FireBase/Extensions/ObservableExtensions.cs
@@ -1,40 +1,41 @@
-namespace Firebase.Database.Extensions
-{
- using System;
- using System.Reactive.Linq;
+using System;
+using System.Reactive.Linq;
+namespace Firebase.Database.Extensions
+{
public static class ObservableExtensions
{
/// <summary>
- /// Returns a cold observable which retries (re-subscribes to) the source observable on error until it successfully terminates.
+ /// Returns a cold observable which retries (re-subscribes to) the source observable on error until it successfully
+ /// terminates.
/// </summary>
/// <param name="source">The source observable.</param>
/// <param name="dueTime">How long to wait between attempts.</param>
/// <param name="retryOnError">A predicate determining for which exceptions to retry. Defaults to all</param>
/// <returns>
- /// A cold observable which retries (re-subscribes to) the source observable on error up to the
- /// specified number of times or until it successfully terminates.
+ /// A cold observable which retries (re-subscribes to) the source observable on error up to the
+ /// specified number of times or until it successfully terminates.
/// </returns>
public static IObservable<T> RetryAfterDelay<T, TException>(
this IObservable<T> source,
TimeSpan dueTime,
Func<TException, bool> retryOnError)
- where TException: Exception
+ where TException : Exception
{
- int attempt = 0;
+ var attempt = 0;
return Observable.Defer(() =>
- {
- return ((++attempt == 1) ? source : source.DelaySubscription(dueTime))
- .Select(item => new Tuple<bool, T, Exception>(true, item, null))
- .Catch<Tuple<bool, T, Exception>, TException>(e => retryOnError(e)
- ? Observable.Throw<Tuple<bool, T, Exception>>(e)
- : Observable.Return(new Tuple<bool, T, Exception>(false, default(T), e)));
- })
- .Retry()
- .SelectMany(t => t.Item1
- ? Observable.Return(t.Item2)
- : Observable.Throw<T>(t.Item3));
+ {
+ return (++attempt == 1 ? source : source.DelaySubscription(dueTime))
+ .Select(item => new Tuple<bool, T, Exception>(true, item, null))
+ .Catch<Tuple<bool, T, Exception>, TException>(e => retryOnError(e)
+ ? Observable.Throw<Tuple<bool, T, Exception>>(e)
+ : Observable.Return(new Tuple<bool, T, Exception>(false, default(T), e)));
+ })
+ .Retry()
+ .SelectMany(t => t.Item1
+ ? Observable.Return(t.Item2)
+ : Observable.Throw<T>(t.Item3));
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Extensions/TaskExtensions.cs b/FireBase/Extensions/TaskExtensions.cs
index 26bbde6..c955b3a 100644
--- a/FireBase/Extensions/TaskExtensions.cs
+++ b/FireBase/Extensions/TaskExtensions.cs
@@ -1,12 +1,12 @@
-namespace Firebase.Database.Extensions
-{
- using System;
- using System.Threading.Tasks;
+using System;
+using System.Threading.Tasks;
+namespace Firebase.Database.Extensions
+{
public static class TaskExtensions
{
/// <summary>
- /// Instead of unwrapping <see cref="AggregateException"/> it throws it as it is.
+ /// Instead of unwrapping <see cref="AggregateException" /> it throws it as it is.
/// </summary>
public static async Task WithAggregateException(this Task source)
{
@@ -20,4 +20,4 @@
}
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/FirebaseClient.cs b/FireBase/FirebaseClient.cs
index a237c8d..3079f3b 100644
--- a/FireBase/FirebaseClient.cs
+++ b/FireBase/FirebaseClient.cs
@@ -1,57 +1,49 @@
+using System;
using System.Net.Http;
+using System.Runtime.CompilerServices;
+using Firebase.Database.Query;
-[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Firebase.Database.Tests")]
+[assembly: InternalsVisibleTo("Firebase.Database.Tests")]
namespace Firebase.Database
{
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
-
- using Firebase.Database.Offline;
- using Firebase.Database.Query;
-
/// <summary>
- /// Firebase client which acts as an entry point to the online database.
+ /// Firebase client which acts as an entry point to the online database.
/// </summary>
public class FirebaseClient : IDisposable
{
+ private readonly string baseUrl;
internal readonly HttpClient HttpClient;
internal readonly FirebaseOptions Options;
- private readonly string baseUrl;
-
/// <summary>
- /// Initializes a new instance of the <see cref="FirebaseClient"/> class.
+ /// Initializes a new instance of the <see cref="FirebaseClient" /> class.
/// </summary>
/// <param name="baseUrl"> The base url. </param>
- /// <param name="offlineDatabaseFactory"> Offline database. </param>
+ /// <param name="offlineDatabaseFactory"> Offline database. </param>
public FirebaseClient(string baseUrl, FirebaseOptions options = null)
{
- this.HttpClient = new HttpClient();
- this.Options = options ?? new FirebaseOptions();
+ HttpClient = new HttpClient();
+ Options = options ?? new FirebaseOptions();
this.baseUrl = baseUrl;
- if (!this.baseUrl.EndsWith("/"))
- {
- this.baseUrl += "/";
- }
+ if (!this.baseUrl.EndsWith("/")) this.baseUrl += "/";
+ }
+
+ public void Dispose()
+ {
+ HttpClient?.Dispose();
}
/// <summary>
- /// Queries for a child of the data root.
+ /// Queries for a child of the data root.
/// </summary>
/// <param name="resourceName"> Name of the child. </param>
- /// <returns> <see cref="ChildQuery"/>. </returns>
+ /// <returns> <see cref="ChildQuery" />. </returns>
public ChildQuery Child(string resourceName)
{
- return new ChildQuery(this, () => this.baseUrl + resourceName);
- }
-
- public void Dispose()
- {
- HttpClient?.Dispose();
+ return new ChildQuery(this, () => baseUrl + resourceName);
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/FirebaseException.cs b/FireBase/FirebaseException.cs
index e4b782b..cfc09d3 100644
--- a/FireBase/FirebaseException.cs
+++ b/FireBase/FirebaseException.cs
@@ -1,63 +1,53 @@
-namespace Firebase.Database
-{
- using System;
- using System.Net;
+using System;
+using System.Net;
+namespace Firebase.Database
+{
public class FirebaseException : Exception
{
public FirebaseException(string requestUrl, string requestData, string responseData, HttpStatusCode statusCode)
: base(GenerateExceptionMessage(requestUrl, requestData, responseData))
{
- this.RequestUrl = requestUrl;
- this.RequestData = requestData;
- this.ResponseData = responseData;
- this.StatusCode = statusCode;
+ RequestUrl = requestUrl;
+ RequestData = requestData;
+ ResponseData = responseData;
+ StatusCode = statusCode;
}
- public FirebaseException(string requestUrl, string requestData, string responseData, HttpStatusCode statusCode, Exception innerException)
+ public FirebaseException(string requestUrl, string requestData, string responseData, HttpStatusCode statusCode,
+ Exception innerException)
: base(GenerateExceptionMessage(requestUrl, requestData, responseData), innerException)
{
- this.RequestUrl = requestUrl;
- this.RequestData = requestData;
- this.ResponseData = responseData;
- this.StatusCode = statusCode;
+ RequestUrl = requestUrl;
+ RequestData = requestData;
+ ResponseData = responseData;
+ StatusCode = statusCode;
}
/// <summary>
- /// Post data passed to the authentication service.
+ /// Post data passed to the authentication service.
/// </summary>
- public string RequestData
- {
- get;
- }
+ public string RequestData { get; }
/// <summary>
- /// Original url of the request.
+ /// Original url of the request.
/// </summary>
- public string RequestUrl
- {
- get;
- }
+ public string RequestUrl { get; }
/// <summary>
- /// Response from the authentication service.
+ /// Response from the authentication service.
/// </summary>
- public string ResponseData
- {
- get;
- }
+ public string ResponseData { get; }
/// <summary>
- /// Status code of the response.
+ /// Status code of the response.
/// </summary>
- public HttpStatusCode StatusCode
- {
- get;
- }
+ public HttpStatusCode StatusCode { get; }
private static string GenerateExceptionMessage(string requestUrl, string requestData, string responseData)
{
- return $"Exception occured while processing the request.\nUrl: {requestUrl}\nRequest Data: {requestData}\nResponse: {responseData}";
+ return
+ $"Exception occured while processing the request.\nUrl: {requestUrl}\nRequest Data: {requestData}\nResponse: {responseData}";
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/FirebaseKeyGenerator.cs b/FireBase/FirebaseKeyGenerator.cs
index acad399..37beed5 100644
--- a/FireBase/FirebaseKeyGenerator.cs
+++ b/FireBase/FirebaseKeyGenerator.cs
@@ -1,13 +1,13 @@
+using System;
+using System.Text;
+
namespace Firebase.Database
{
- using System;
- using System.Text;
-
/// <summary>
- /// Offline key generator which mimics the official Firebase generators.
- /// Credit: https://github.com/bubbafat/FirebaseSharp/blob/master/src/FirebaseSharp.Portable/FireBasePushIdGenerator.cs
+ /// Offline key generator which mimics the official Firebase generators.
+ /// Credit: https://github.com/bubbafat/FirebaseSharp/blob/master/src/FirebaseSharp.Portable/FireBasePushIdGenerator.cs
/// </summary>
- public class FirebaseKeyGenerator
+ public class FirebaseKeyGenerator
{
// Modeled after base64 web-safe chars, but ordered by ASCII.
private const string PushCharsString = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
@@ -26,10 +26,11 @@ namespace Firebase.Database
}
/// <summary>
- /// Returns next firebase key based on current time.
+ /// Returns next firebase key based on current time.
/// </summary>
/// <returns>
- /// The <see cref="string"/>. </returns>
+ /// The <see cref="string" />.
+ /// </returns>
public static string Next()
{
// We generate 72-bits of randomness which get turned into 12 characters and
@@ -37,31 +38,25 @@ namespace Firebase.Database
// characters we generated because in the event of a collision, we'll use those same
// characters except "incremented" by one.
var id = new StringBuilder(20);
- var now = (long)(DateTimeOffset.Now - Epoch).TotalMilliseconds;
+ var now = (long) (DateTimeOffset.Now - Epoch).TotalMilliseconds;
var duplicateTime = now == lastPushTime;
lastPushTime = now;
var timeStampChars = new char[8];
- for (int i = 7; i >= 0; i--)
+ for (var i = 7; i >= 0; i--)
{
- var index = (int)(now % PushChars.Length);
+ var index = (int) (now % PushChars.Length);
timeStampChars[i] = PushChars[index];
- now = (long)Math.Floor((double)now / PushChars.Length);
+ now = (long) Math.Floor((double) now / PushChars.Length);
}
- if (now != 0)
- {
- throw new Exception("We should have converted the entire timestamp.");
- }
+ if (now != 0) throw new Exception("We should have converted the entire timestamp.");
id.Append(timeStampChars);
if (!duplicateTime)
{
- for (int i = 0; i < 12; i++)
- {
- lastRandChars[i] = (byte)random.Next(0, PushChars.Length);
- }
+ for (var i = 0; i < 12; i++) lastRandChars[i] = (byte) random.Next(0, PushChars.Length);
}
else
{
@@ -69,24 +64,16 @@ namespace Firebase.Database
// except incremented by 1.
var lastIndex = 11;
for (; lastIndex >= 0 && lastRandChars[lastIndex] == PushChars.Length - 1; lastIndex--)
- {
lastRandChars[lastIndex] = 0;
- }
lastRandChars[lastIndex]++;
}
- for (int i = 0; i < 12; i++)
- {
- id.Append(PushChars[lastRandChars[i]]);
- }
+ for (var i = 0; i < 12; i++) id.Append(PushChars[lastRandChars[i]]);
- if (id.Length != 20)
- {
- throw new Exception("Length should be 20.");
- }
+ if (id.Length != 20) throw new Exception("Length should be 20.");
return id.ToString();
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/FirebaseObject.cs b/FireBase/FirebaseObject.cs
index ea61893..2e0fd20 100644
--- a/FireBase/FirebaseObject.cs
+++ b/FireBase/FirebaseObject.cs
@@ -1,31 +1,27 @@
namespace Firebase.Database
{
/// <summary>
- /// Holds the object of type <typeparam name="T" /> along with its key.
+ /// Holds the object of type
+ /// <typeparam name="T" />
+ /// along with its key.
/// </summary>
- /// <typeparam name="T"> Type of the underlying object. </typeparam>
- public class FirebaseObject<T>
+ /// <typeparam name="T"> Type of the underlying object. </typeparam>
+ public class FirebaseObject<T>
{
internal FirebaseObject(string key, T obj)
{
- this.Key = key;
- this.Object = obj;
+ Key = key;
+ Object = obj;
}
/// <summary>
- /// Gets the key of <see cref="Object"/>.
+ /// Gets the key of <see cref="Object" />.
/// </summary>
- public string Key
- {
- get;
- }
+ public string Key { get; }
/// <summary>
- /// Gets the underlying object.
+ /// Gets the underlying object.
/// </summary>
- public T Object
- {
- get;
- }
+ public T Object { get; }
}
-}
+} \ No newline at end of file
diff --git a/FireBase/FirebaseOptions.cs b/FireBase/FirebaseOptions.cs
index 9905956..b4a5e51 100644
--- a/FireBase/FirebaseOptions.cs
+++ b/FireBase/FirebaseOptions.cs
@@ -1,76 +1,52 @@
-namespace Firebase.Database
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading.Tasks;
+using Firebase.Database.Offline;
+using Newtonsoft.Json;
+
+namespace Firebase.Database
{
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Threading.Tasks;
-
- using Firebase.Database.Offline;
-
- using Newtonsoft.Json;
-
public class FirebaseOptions
{
public FirebaseOptions()
{
- this.OfflineDatabaseFactory = (t, s) => new Dictionary<string, OfflineEntry>();
- this.SubscriptionStreamReaderFactory = s => new StreamReader(s);
- this.JsonSerializerSettings = new JsonSerializerSettings();
- this.SyncPeriod = TimeSpan.FromSeconds(10);
+ OfflineDatabaseFactory = (t, s) => new Dictionary<string, OfflineEntry>();
+ SubscriptionStreamReaderFactory = s => new StreamReader(s);
+ JsonSerializerSettings = new JsonSerializerSettings();
+ SyncPeriod = TimeSpan.FromSeconds(10);
}
/// <summary>
- /// Gets or sets the factory for Firebase offline database. Default is in-memory dictionary.
+ /// Gets or sets the factory for Firebase offline database. Default is in-memory dictionary.
/// </summary>
- public Func<Type, string, IDictionary<string, OfflineEntry>> OfflineDatabaseFactory
- {
- get;
- set;
- }
+ public Func<Type, string, IDictionary<string, OfflineEntry>> OfflineDatabaseFactory { get; set; }
/// <summary>
- /// Gets or sets the method for retrieving auth tokens. Default is null.
+ /// Gets or sets the method for retrieving auth tokens. Default is null.
/// </summary>
- public Func<Task<string>> AuthTokenAsyncFactory
- {
- get;
- set;
- }
+ public Func<Task<string>> AuthTokenAsyncFactory { get; set; }
/// <summary>
- /// Gets or sets the factory for <see cref="TextReader"/> used for reading online streams. Default is <see cref="StreamReader"/>.
+ /// Gets or sets the factory for <see cref="TextReader" /> used for reading online streams. Default is
+ /// <see cref="StreamReader" />.
/// </summary>
- public Func<Stream, TextReader> SubscriptionStreamReaderFactory
- {
- get;
- set;
- }
+ public Func<Stream, TextReader> SubscriptionStreamReaderFactory { get; set; }
/// <summary>
- /// Gets or sets the json serializer settings.
+ /// Gets or sets the json serializer settings.
/// </summary>
- public JsonSerializerSettings JsonSerializerSettings
- {
- get;
- set;
- }
+ public JsonSerializerSettings JsonSerializerSettings { get; set; }
/// <summary>
- /// Gets or sets the time between synchronization attempts for pulling and pushing offline entities. Default is 10 seconds.
+ /// Gets or sets the time between synchronization attempts for pulling and pushing offline entities. Default is 10
+ /// seconds.
/// </summary>
- public TimeSpan SyncPeriod
- {
- get;
- set;
- }
+ public TimeSpan SyncPeriod { get; set; }
/// <summary>
- /// Specify if token returned by factory will be used as "auth" url parameter or "access_token".
+ /// Specify if token returned by factory will be used as "auth" url parameter or "access_token".
/// </summary>
- public bool AsAccessToken
- {
- get;
- set;
- }
+ public bool AsAccessToken { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Http/HttpClientExtensions.cs b/FireBase/Http/HttpClientExtensions.cs
index 5d15c59..6582769 100644
--- a/FireBase/Http/HttpClientExtensions.cs
+++ b/FireBase/Http/HttpClientExtensions.cs
@@ -1,29 +1,29 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Threading.Tasks;
+using Newtonsoft.Json;
+
namespace Firebase.Database.Http
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Threading.Tasks;
-
- using Newtonsoft.Json;
- using System.Net;
-
/// <summary>
- /// The http client extensions for object deserializations.
+ /// The http client extensions for object deserializations.
/// </summary>
internal static class HttpClientExtensions
{
/// <summary>
- /// The get object collection async.
+ /// The get object collection async.
/// </summary>
/// <param name="client"> The client. </param>
- /// <param name="requestUri"> The request uri. </param>
- /// <param name="jsonSerializerSettings"> The specific JSON Serializer Settings. </param>
+ /// <param name="requestUri"> The request uri. </param>
+ /// <param name="jsonSerializerSettings"> The specific JSON Serializer Settings. </param>
/// <typeparam name="T"> The type of entities the collection should contain. </typeparam>
- /// <returns> The <see cref="Task"/>. </returns>
- public static async Task<IReadOnlyCollection<FirebaseObject<T>>> GetObjectCollectionAsync<T>(this HttpClient client, string requestUri,
+ /// <returns> The <see cref="Task" />. </returns>
+ public static async Task<IReadOnlyCollection<FirebaseObject<T>>> GetObjectCollectionAsync<T>(
+ this HttpClient client, string requestUri,
JsonSerializerSettings jsonSerializerSettings)
{
var responseData = string.Empty;
@@ -37,12 +37,10 @@ namespace Firebase.Database.Http
response.EnsureSuccessStatusCode();
- var dictionary = JsonConvert.DeserializeObject<Dictionary<string, T>>(responseData, jsonSerializerSettings);
+ var dictionary =
+ JsonConvert.DeserializeObject<Dictionary<string, T>>(responseData, jsonSerializerSettings);
- if (dictionary == null)
- {
- return new FirebaseObject<T>[0];
- }
+ if (dictionary == null) return new FirebaseObject<T>[0];
return dictionary.Select(item => new FirebaseObject<T>(item.Key, item.Value)).ToList();
}
@@ -93,11 +91,11 @@ namespace Firebase.Database.Http
}*/
/// <summary>
- /// The get object collection async.
+ /// The get object collection async.
/// </summary>
/// <param name="data"> The json data. </param>
/// <param name="elementType"> The type of entities the collection should contain. </param>
- /// <returns> The <see cref="Task"/>. </returns>
+ /// <returns> The <see cref="Task" />. </returns>
public static IEnumerable<FirebaseObject<object>> GetObjectCollection(this string data, Type elementType)
{
var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), elementType);
@@ -116,15 +114,10 @@ namespace Firebase.Database.Http
dictionary = JsonConvert.DeserializeObject(data, dictionaryType) as IDictionary;
}
- if (dictionary == null)
- {
- yield break;
- }
+ if (dictionary == null) yield break;
foreach (DictionaryEntry item in dictionary)
- {
- yield return new FirebaseObject<object>((string)item.Key, item.Value);
- }
+ yield return new FirebaseObject<object>((string) item.Key, item.Value);
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Http/PostResult.cs b/FireBase/Http/PostResult.cs
index 3f010d4..15a4894 100644
--- a/FireBase/Http/PostResult.cs
+++ b/FireBase/Http/PostResult.cs
@@ -1,17 +1,13 @@
namespace Firebase.Database.Http
{
/// <summary>
- /// Represents data returned after a successful POST to firebase server.
+ /// Represents data returned after a successful POST to firebase server.
/// </summary>
public class PostResult
{
/// <summary>
- /// Gets or sets the generated key after a successful post.
+ /// Gets or sets the generated key after a successful post.
/// </summary>
- public string Name
- {
- get;
- set;
- }
+ public string Name { get; set; }
}
-}
+} \ No newline at end of file
diff --git a/FireBase/ObservableExtensions.cs b/FireBase/ObservableExtensions.cs
index 37c3ef7..bc46261 100644
--- a/FireBase/ObservableExtensions.cs
+++ b/FireBase/ObservableExtensions.cs
@@ -1,21 +1,20 @@
-namespace Firebase.Database
-{
- using System;
- using System.Collections.ObjectModel;
-
- using Firebase.Database.Streaming;
+using System;
+using System.Collections.ObjectModel;
+using Firebase.Database.Streaming;
+namespace Firebase.Database
+{
/// <summary>
- /// Extensions for <see cref="IObservable{T}"/>.
+ /// Extensions for <see cref="IObservable{T}" />.
/// </summary>
public static class ObservableExtensions
{
/// <summary>
- /// Starts observing on given firebase observable and propagates event into an <see cref="ObservableCollection{T}"/>.
+ /// Starts observing on given firebase observable and propagates event into an <see cref="ObservableCollection{T}" />.
/// </summary>
/// <param name="observable"> The observable. </param>
/// <typeparam name="T"> Type of entity. </typeparam>
- /// <returns> The <see cref="ObservableCollection{T}"/>. </returns>
+ /// <returns> The <see cref="ObservableCollection{T}" />. </returns>
public static ObservableCollection<T> AsObservableCollection<T>(this IObservable<FirebaseEvent<T>> observable)
{
var collection = new ObservableCollection<T>();
@@ -25,10 +24,7 @@
if (f.EventType == FirebaseEventType.InsertOrUpdate)
{
var i = collection.IndexOf(f.Object);
- if (i >= 0)
- {
- collection.RemoveAt(i);
- }
+ if (i >= 0) collection.RemoveAt(i);
collection.Add(f.Object);
}
@@ -41,4 +37,4 @@
return collection;
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/ConcurrentOfflineDatabase.cs b/FireBase/Offline/ConcurrentOfflineDatabase.cs
index 226892d..1a9e607 100644
--- a/FireBase/Offline/ConcurrentOfflineDatabase.cs
+++ b/FireBase/Offline/ConcurrentOfflineDatabase.cs
@@ -1,207 +1,233 @@
-namespace Firebase.Database.Offline
+using System;
+using System.Collections;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using LiteDB;
+
+namespace Firebase.Database.Offline
{
- using System;
- using System.Collections;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
-
- using LiteDB;
-
/// <summary>
- /// The offline database.
+ /// The offline database.
/// </summary>
public class ConcurrentOfflineDatabase : IDictionary<string, OfflineEntry>
{
- private readonly LiteRepository db;
private readonly ConcurrentDictionary<string, OfflineEntry> ccache;
+ private readonly LiteRepository db;
/// <summary>
- /// Initializes a new instance of the <see cref="OfflineDatabase"/> class.
+ /// Initializes a new instance of the <see cref="OfflineDatabase" /> class.
/// </summary>
/// <param name="itemType"> The item type which is used to determine the database file name. </param>
/// <param name="filenameModifier"> Custom string which will get appended to the file name. </param>
public ConcurrentOfflineDatabase(Type itemType, string filenameModifier)
{
- var fullName = this.GetFileName(itemType.ToString());
- if(fullName.Length > 100)
- {
- fullName = fullName.Substring(0, 100);
- }
+ var fullName = GetFileName(itemType.ToString());
+ if (fullName.Length > 100) fullName = fullName.Substring(0, 100);
- BsonMapper mapper = BsonMapper.Global;
+ var mapper = BsonMapper.Global;
mapper.Entity<OfflineEntry>().Id(o => o.Key);
- string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- string filename = fullName + filenameModifier + ".db";
+ var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
+ var filename = fullName + filenameModifier + ".db";
var path = Path.Combine(root, filename);
- this.db = new LiteRepository(new LiteDatabase(path, mapper));
+ db = new LiteRepository(new LiteDatabase(path, mapper));
var cache = db.Database
.GetCollection<OfflineEntry>()
.FindAll()
.ToDictionary(o => o.Key, o => o);
- this.ccache = new ConcurrentDictionary<string, OfflineEntry>(cache);
-
+ ccache = new ConcurrentDictionary<string, OfflineEntry>(cache);
}
/// <summary>
- /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
+ /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
- /// <returns> The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns>
- public int Count => this.ccache.Count;
+ /// <returns> The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />. </returns>
+ public int Count => ccache.Count;
/// <summary>
- /// Gets a value indicating whether this is a read-only collection.
+ /// Gets a value indicating whether this is a read-only collection.
/// </summary>
public bool IsReadOnly => false;
/// <summary>
- /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the
+ /// <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
- /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns>
- public ICollection<string> Keys => this.ccache.Keys;
+ /// <returns>
+ /// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that
+ /// implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
+ /// </returns>
+ public ICollection<string> Keys => ccache.Keys;
/// <summary>
- /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the
+ /// <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
- /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns>
- public ICollection<OfflineEntry> Values => this.ccache.Values;
+ /// <returns>
+ /// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that
+ /// implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
+ /// </returns>
+ public ICollection<OfflineEntry> Values => ccache.Values;
/// <summary>
- /// Gets or sets the element with the specified key.
+ /// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key of the element to get or set.</param>
- /// <returns> The element with the specified key. </returns>
+ /// <returns> The element with the specified key. </returns>
public OfflineEntry this[string key]
{
- get
- {
- return this.ccache[key];
- }
+ get => ccache[key];
set
{
- this.ccache.AddOrUpdate(key, value, (k, existing) => value);
- this.db.Upsert(value);
+ ccache.AddOrUpdate(key, value, (k, existing) => value);
+ db.Upsert(value);
}
}
/// <summary>
- /// Returns an enumerator that iterates through the collection.
+ /// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns> An enumerator that can be used to iterate through the collection. </returns>
public IEnumerator<KeyValuePair<string, OfflineEntry>> GetEnumerator()
{
- return this.ccache.GetEnumerator();
+ return ccache.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
- return this.GetEnumerator();
+ return GetEnumerator();
}
/// <summary>
- /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
+ /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
- /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
+ /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
public void Add(KeyValuePair<string, OfflineEntry> item)
{
- this.Add(item.Key, item.Value);
+ Add(item.Key, item.Value);
}
/// <summary>
- /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
- /// </summary>
+ /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
+ /// </summary>
public void Clear()
{
- this.ccache.Clear();
- this.db.Delete<OfflineEntry>(Query.All());
+ ccache.Clear();
+ db.Delete<OfflineEntry>(LiteDB.Query.All());
}
/// <summary>
- /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
+ /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value.
/// </summary>
- /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
- /// <returns> True if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. </returns>
+ /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
+ /// <returns>
+ /// True if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />;
+ /// otherwise, false.
+ /// </returns>
public bool Contains(KeyValuePair<string, OfflineEntry> item)
{
- return this.ContainsKey(item.Key);
+ return ContainsKey(item.Key);
}
/// <summary>
- /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
+ /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an
+ /// <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
/// </summary>
- /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
- /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
+ /// <param name="array">
+ /// The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied
+ /// from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have
+ /// zero-based indexing.
+ /// </param>
+ /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
public void CopyTo(KeyValuePair<string, OfflineEntry>[] array, int arrayIndex)
{
- this.ccache.ToList().CopyTo(array, arrayIndex);
+ ccache.ToList().CopyTo(array, arrayIndex);
}
/// <summary>
- /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
+ /// Removes the first occurrence of a specific object from the
+ /// <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
- /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
- /// <returns> True if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns>
+ /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
+ /// <returns>
+ /// True if <paramref name="item" /> was successfully removed from the
+ /// <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if
+ /// <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />.
+ /// </returns>
public bool Remove(KeyValuePair<string, OfflineEntry> item)
{
- return this.Remove(item.Key);
+ return Remove(item.Key);
}
/// <summary>
- /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
+ /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the
+ /// specified key.
/// </summary>
- /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
- /// <returns> True if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. </returns>
+ /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2" />.</param>
+ /// <returns>
+ /// True if the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the key;
+ /// otherwise, false.
+ /// </returns>
public bool ContainsKey(string key)
{
- return this.ccache.ContainsKey(key);
+ return ccache.ContainsKey(key);
}
/// <summary>
- /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
public void Add(string key, OfflineEntry value)
{
- this.ccache.AddOrUpdate(key, value, (k, existing) => value);
- this.db.Upsert(value);
+ ccache.AddOrUpdate(key, value, (k, existing) => value);
+ db.Upsert(value);
}
/// <summary>
- /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
- /// <returns> True if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns>
+ /// <returns>
+ /// True if the element is successfully removed; otherwise, false. This method also returns false if
+ /// <paramref name="key" /> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2" />.
+ /// </returns>
public bool Remove(string key)
{
- this.ccache.TryRemove(key, out OfflineEntry _);
- return this.db.Delete<OfflineEntry>(key);
+ ccache.TryRemove(key, out _);
+ return db.Delete<OfflineEntry>(key);
}
/// <summary>
- /// Gets the value associated with the specified key.
- /// </summary>
- /// <param name="key">The key whose value to get.</param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param>
- /// <returns> True if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. </returns>
+ /// Gets the value associated with the specified key.
+ /// </summary>
+ /// <param name="key">The key whose value to get.</param>
+ /// <param name="value">
+ /// When this method returns, the value associated with the specified key, if the key is found;
+ /// otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed
+ /// uninitialized.
+ /// </param>
+ /// <returns>
+ /// True if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an
+ /// element with the specified key; otherwise, false.
+ /// </returns>
public bool TryGetValue(string key, out OfflineEntry value)
{
- return this.ccache.TryGetValue(key, out value);
+ return ccache.TryGetValue(key, out value);
}
private string GetFileName(string fileName)
{
- var invalidChars = new[] { '`', '[', ',', '=' };
- foreach(char c in invalidChars.Concat(System.IO.Path.GetInvalidFileNameChars()).Distinct())
- {
+ var invalidChars = new[] {'`', '[', ',', '='};
+ foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct())
fileName = fileName.Replace(c, '_');
- }
return fileName;
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/DatabaseExtensions.cs b/FireBase/Offline/DatabaseExtensions.cs
index 4b04314..e7c4074 100644
--- a/FireBase/Offline/DatabaseExtensions.cs
+++ b/FireBase/Offline/DatabaseExtensions.cs
@@ -1,83 +1,107 @@
-namespace Firebase.Database.Offline
-{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq.Expressions;
- using System.Reflection;
- using Firebase.Database.Query;
+using System;
+using System.Collections.Generic;
+using System.Linq.Expressions;
+using System.Reflection;
+using Firebase.Database.Query;
+namespace Firebase.Database.Offline
+{
public static class DatabaseExtensions
{
/// <summary>
- /// Create new instances of the <see cref="RealtimeDatabase{T}"/>.
+ /// Create new instances of the <see cref="RealtimeDatabase{T}" />.
/// </summary>
/// <typeparam name="T"> Type of elements. </typeparam>
/// <param name="filenameModifier"> Custom string which will get appended to the file name. </param>
/// <param name="elementRoot"> Optional custom root element of received json items. </param>
- /// <param name="streamingOptions"> Realtime streaming options. </param>
+ /// <param name="streamingOptions"> Realtime streaming options. </param>
/// <param name="initialPullStrategy"> Specifies what strategy should be used for initial pulling of server data. </param>
- /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. </param>
- /// <returns> The <see cref="RealtimeDatabase{T}"/>. </returns>
- public static RealtimeDatabase<T> AsRealtimeDatabase<T>(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true)
+ /// <param name="pushChanges">
+ /// Specifies whether changed items should actually be pushed to the server. It this is false,
+ /// then Put / Post / Delete will not affect server data.
+ /// </param>
+ /// <returns> The <see cref="RealtimeDatabase{T}" />. </returns>
+ public static RealtimeDatabase<T> AsRealtimeDatabase<T>(this ChildQuery query, string filenameModifier = "",
+ string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly,
+ InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true)
where T : class
{
- return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges);
+ return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory,
+ filenameModifier, streamingOptions, initialPullStrategy, pushChanges);
}
/// <summary>
- /// Create new instances of the <see cref="RealtimeDatabase{T}"/>.
+ /// Create new instances of the <see cref="RealtimeDatabase{T}" />.
/// </summary>
/// <typeparam name="T"> Type of elements. </typeparam>
- /// <typeparam name="TSetHandler"> Type of the custom <see cref="ISetHandler{T}"/> to use. </typeparam>
+ /// <typeparam name="TSetHandler"> Type of the custom <see cref="ISetHandler{T}" /> to use. </typeparam>
/// <param name="filenameModifier"> Custom string which will get appended to the file name. </param>
/// <param name="elementRoot"> Optional custom root element of received json items. </param>
- /// <param name="streamingOptions"> Realtime streaming options. </param>
+ /// <param name="streamingOptions"> Realtime streaming options. </param>
/// <param name="initialPullStrategy"> Specifies what strategy should be used for initial pulling of server data. </param>
- /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. </param>
- /// <returns> The <see cref="RealtimeDatabase{T}"/>. </returns>
- public static RealtimeDatabase<T> AsRealtimeDatabase<T, TSetHandler>(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true)
+ /// <param name="pushChanges">
+ /// Specifies whether changed items should actually be pushed to the server. It this is false,
+ /// then Put / Post / Delete will not affect server data.
+ /// </param>
+ /// <returns> The <see cref="RealtimeDatabase{T}" />. </returns>
+ public static RealtimeDatabase<T> AsRealtimeDatabase<T, TSetHandler>(this ChildQuery query,
+ string filenameModifier = "", string elementRoot = "",
+ StreamingOptions streamingOptions = StreamingOptions.LatestOnly,
+ InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true)
where T : class
where TSetHandler : ISetHandler<T>, new()
{
- return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges, Activator.CreateInstance<TSetHandler>());
+ return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory,
+ filenameModifier, streamingOptions, initialPullStrategy, pushChanges,
+ Activator.CreateInstance<TSetHandler>());
}
/// <summary>
- /// Overwrites existing object with given key leaving any missing properties intact in firebase.
+ /// Overwrites existing object with given key leaving any missing properties intact in firebase.
/// </summary>
/// <param name="key"> The key. </param>
/// <param name="obj"> The object to set. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
- public static void Patch<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, int priority = 1)
- where T: class
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
+ public static void Patch<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true,
+ int priority = 1)
+ where T : class
{
db.Set(key, obj, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority);
}
/// <summary>
- /// Overwrites existing object with given key.
+ /// Overwrites existing object with given key.
/// </summary>
/// <param name="key"> The key. </param>
/// <param name="obj"> The object to set. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
- public static void Put<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, int priority = 1)
- where T: class
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
+ public static void Put<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true,
+ int priority = 1)
+ where T : class
{
db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority);
}
/// <summary>
- /// Adds a new entity to the Database.
+ /// Adds a new entity to the Database.
/// </summary>
/// <param name="obj"> The object to add. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
/// <returns> The generated key for this object. </returns>
public static string Post<T>(this RealtimeDatabase<T> db, T obj, bool syncOnline = true, int priority = 1)
- where T: class
+ where T : class
{
var key = FirebaseKeyGenerator.Next();
@@ -87,19 +111,23 @@
}
/// <summary>
- /// Deletes the entity with the given key.
+ /// Deletes the entity with the given key.
/// </summary>
/// <param name="key"> The key. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
public static void Delete<T>(this RealtimeDatabase<T> 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);
}
/// <summary>
- /// Do a Put for a nested property specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>.
+ /// Do a Put for a nested property specified by <paramref name="propertyExpression" /> of an object with key
+ /// <paramref name="key" />.
/// </summary>
/// <typeparam name="T"> Type of the root elements. </typeparam>
/// <typeparam name="TProperty"> Type of the property being modified</typeparam>
@@ -108,15 +136,21 @@
/// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param>
/// <param name="value"> Value to put. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
- public static void Put<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1)
- where T: class
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
+ public static void Put<T, TProperty>(this RealtimeDatabase<T> db, string key,
+ Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true,
+ int priority = 1)
+ where T : class
{
db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority);
}
/// <summary>
- /// Do a Patch for a nested property specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>.
+ /// Do a Patch for a nested property specified by <paramref name="propertyExpression" /> of an object with key
+ /// <paramref name="key" />.
/// </summary>
/// <typeparam name="T"> Type of the root elements. </typeparam>
/// <typeparam name="TProperty"> Type of the property being modified</typeparam>
@@ -125,15 +159,21 @@
/// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param>
/// <param name="value"> Value to patch. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
- public static void Patch<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1)
- where T: class
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
+ public static void Patch<T, TProperty>(this RealtimeDatabase<T> db, string key,
+ Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true,
+ int priority = 1)
+ where T : class
{
db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority);
}
/// <summary>
- /// Delete a nested property specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>. This basically does a Put with null value.
+ /// Delete a nested property specified by <paramref name="propertyExpression" /> of an object with key
+ /// <paramref name="key" />. This basically does a Put with null value.
/// </summary>
/// <typeparam name="T"> Type of the root elements. </typeparam>
/// <typeparam name="TProperty"> Type of the property being modified</typeparam>
@@ -142,17 +182,22 @@
/// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param>
/// <param name="value"> Value to put. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
- public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, bool syncOnline = true, int priority = 1)
- where T: class
- where TProperty: class
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
+ public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key,
+ Expression<Func<T, TProperty>> propertyExpression, bool syncOnline = true, int priority = 1)
+ where T : class
+ where TProperty : class
{
db.Set(key, propertyExpression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority);
}
/// <summary>
- /// Post a new entity into the nested dictionary specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>.
- /// The key of the new entity is automatically generated.
+ /// Post a new entity into the nested dictionary specified by <paramref name="propertyExpression" /> of an object with
+ /// key <paramref name="key" />.
+ /// The key of the new entity is automatically generated.
/// </summary>
/// <typeparam name="T"> Type of the root elements. </typeparam>
/// <typeparam name="TSelector"> Type of the dictionary being modified</typeparam>
@@ -162,19 +207,28 @@
/// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param>
/// <param name="value"> Value to put. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
- public static void Post<T, TSelector, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TSelector>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1)
- where T: class
- where TSelector: IDictionary<string, TProperty>
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
+ public static void Post<T, TSelector, TProperty>(this RealtimeDatabase<T> db, string key,
+ Expression<Func<T, TSelector>> propertyExpression, TProperty value, bool syncOnline = true,
+ int priority = 1)
+ where T : class
+ where TSelector : IDictionary<string, TProperty>
{
var nextKey = FirebaseKeyGenerator.Next();
- var expression = Expression.Lambda<Func<T, TProperty>>(Expression.Call(propertyExpression.Body, typeof(TSelector).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(nextKey)), propertyExpression.Parameters);
+ var expression = Expression.Lambda<Func<T, TProperty>>(
+ Expression.Call(propertyExpression.Body,
+ typeof(TSelector).GetRuntimeMethod("get_Item", new[] {typeof(string)}),
+ Expression.Constant(nextKey)), propertyExpression.Parameters);
db.Set(key, expression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority);
}
/// <summary>
- /// Delete an entity with key <paramref name="dictionaryKey"/> in the nested dictionary specified by <paramref name="propertyExpression"/> of an object with key <paramref name="key"/>.
- /// The key of the new entity is automatically generated.
+ /// Delete an entity with key <paramref name="dictionaryKey" /> in the nested dictionary specified by
+ /// <paramref name="propertyExpression" /> of an object with key <paramref name="key" />.
+ /// The key of the new entity is automatically generated.
/// </summary>
/// <typeparam name="T"> Type of the root elements. </typeparam>
/// <typeparam name="TSelector"> Type of the dictionary being modified</typeparam>
@@ -184,12 +238,20 @@
/// <param name="propertyExpression"> Expression on the root element leading to target value to modify. </param>
/// <param name="dictionaryKey"> Key within the nested dictionary to delete. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
- public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, IDictionary<string, TProperty>>> propertyExpression, string dictionaryKey, bool syncOnline = true, int priority = 1)
- where T: class
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
+ public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key,
+ Expression<Func<T, IDictionary<string, TProperty>>> propertyExpression, string dictionaryKey,
+ bool syncOnline = true, int priority = 1)
+ where T : class
{
- var expression = Expression.Lambda<Func<T, TProperty>>(Expression.Call(propertyExpression.Body, typeof(IDictionary<string, TProperty>).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(dictionaryKey)), propertyExpression.Parameters);
+ var expression = Expression.Lambda<Func<T, TProperty>>(
+ Expression.Call(propertyExpression.Body,
+ typeof(IDictionary<string, TProperty>).GetRuntimeMethod("get_Item", new[] {typeof(string)}),
+ Expression.Constant(dictionaryKey)), propertyExpression.Parameters);
db.Set(key, expression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority);
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/ISetHandler.cs b/FireBase/Offline/ISetHandler.cs
index 477c36b..c04bd41 100644
--- a/FireBase/Offline/ISetHandler.cs
+++ b/FireBase/Offline/ISetHandler.cs
@@ -1,11 +1,10 @@
-namespace Firebase.Database.Offline
-{
- using Firebase.Database.Query;
-
- using System.Threading.Tasks;
+using System.Threading.Tasks;
+using Firebase.Database.Query;
+namespace Firebase.Database.Offline
+{
public interface ISetHandler<in T>
{
Task SetAsync(ChildQuery query, string key, OfflineEntry entry);
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/InitialPullStrategy.cs b/FireBase/Offline/InitialPullStrategy.cs
index 70f6b8c..ca2bebf 100644
--- a/FireBase/Offline/InitialPullStrategy.cs
+++ b/FireBase/Offline/InitialPullStrategy.cs
@@ -1,23 +1,23 @@
namespace Firebase.Database.Offline
{
/// <summary>
- /// Specifies the strategy for initial pull of server data.
+ /// Specifies the strategy for initial pull of server data.
/// </summary>
public enum InitialPullStrategy
{
/// <summary>
- /// Don't pull anything.
+ /// Don't pull anything.
/// </summary>
- None,
+ None,
/// <summary>
- /// Pull only what isn't already stored offline.
+ /// Pull only what isn't already stored offline.
/// </summary>
MissingOnly,
/// <summary>
- /// Pull everything that exists on the server.
+ /// Pull everything that exists on the server.
/// </summary>
- Everything,
+ Everything
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/Internals/MemberAccessVisitor.cs b/FireBase/Offline/Internals/MemberAccessVisitor.cs
index 1f7cb11..89a77da 100644
--- a/FireBase/Offline/Internals/MemberAccessVisitor.cs
+++ b/FireBase/Offline/Internals/MemberAccessVisitor.cs
@@ -1,51 +1,46 @@
-namespace Firebase.Database.Offline.Internals
-{
- using System.Collections.Generic;
- using System.Linq.Expressions;
- using System.Reflection;
-
- using Newtonsoft.Json;
+using System.Collections.Generic;
+using System.Linq.Expressions;
+using System.Reflection;
+using Newtonsoft.Json;
+namespace Firebase.Database.Offline.Internals
+{
public class MemberAccessVisitor : ExpressionVisitor
{
private readonly IList<string> propertyNames = new List<string>();
private bool wasDictionaryAccess;
- public IEnumerable<string> PropertyNames => this.propertyNames;
-
- public MemberAccessVisitor()
- {
- }
+ public IEnumerable<string> PropertyNames => propertyNames;
public override Expression Visit(Expression expr)
{
if (expr?.NodeType == ExpressionType.MemberAccess)
{
- if (this.wasDictionaryAccess)
+ if (wasDictionaryAccess)
{
- this.wasDictionaryAccess = false;
+ wasDictionaryAccess = false;
}
else
{
- var memberExpr = (MemberExpression)expr;
+ var memberExpr = (MemberExpression) expr;
var jsonAttr = memberExpr.Member.GetCustomAttribute<JsonPropertyAttribute>();
- this.propertyNames.Add(jsonAttr?.PropertyName ?? memberExpr.Member.Name);
+ propertyNames.Add(jsonAttr?.PropertyName ?? memberExpr.Member.Name);
}
}
else if (expr?.NodeType == ExpressionType.Call)
{
- var callExpr = (MethodCallExpression)expr;
+ var callExpr = (MethodCallExpression) expr;
if (callExpr.Method.Name == "get_Item" && callExpr.Arguments.Count == 1)
{
var e = Expression.Lambda(callExpr.Arguments[0]).Compile();
- this.propertyNames.Add(e.DynamicInvoke().ToString());
- this.wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess;
+ propertyNames.Add(e.DynamicInvoke().ToString());
+ wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess;
}
}
return base.Visit(expr);
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/OfflineCacheAdapter.cs b/FireBase/Offline/OfflineCacheAdapter.cs
index a3761a0..3153d1b 100644
--- a/FireBase/Offline/OfflineCacheAdapter.cs
+++ b/FireBase/Offline/OfflineCacheAdapter.cs
@@ -1,11 +1,11 @@
-namespace Firebase.Database.Offline
-{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
- internal class OfflineCacheAdapter<TKey, T> : IDictionary<string, T>, IDictionary
+namespace Firebase.Database.Offline
+{
+ internal class OfflineCacheAdapter<TKey, T> : IDictionary<string, T>, IDictionary
{
private readonly IDictionary<string, OfflineEntry> database;
@@ -19,66 +19,32 @@
throw new NotImplementedException();
}
- public int Count => this.database.Count;
-
public bool IsSynchronized { get; }
public object SyncRoot { get; }
- public bool IsReadOnly => this.database.IsReadOnly;
-
object IDictionary.this[object key]
{
- get
- {
- return this.database[key.ToString()].Deserialize<T>();
- }
+ get => database[key.ToString()].Deserialize<T>();
set
{
var keyString = key.ToString();
- if (this.database.ContainsKey(keyString))
- {
- this.database[keyString] = new OfflineEntry(keyString, value, this.database[keyString].Priority, this.database[keyString].SyncOptions);
- }
+ if (database.ContainsKey(keyString))
+ database[keyString] = new OfflineEntry(keyString, value, database[keyString].Priority,
+ database[keyString].SyncOptions);
else
- {
- this.database[keyString] = new OfflineEntry(keyString, value, 1, SyncOptions.None);
- }
+ database[keyString] = new OfflineEntry(keyString, value, 1, SyncOptions.None);
}
}
- public ICollection<string> Keys => this.database.Keys;
-
ICollection IDictionary.Values { get; }
ICollection IDictionary.Keys { get; }
- public ICollection<T> Values => this.database.Values.Select(o => o.Deserialize<T>()).ToList();
-
- public T this[string key]
- {
- get
- {
- return this.database[key].Deserialize<T>();
- }
-
- set
- {
- if (this.database.ContainsKey(key))
- {
- this.database[key] = new OfflineEntry(key, value, this.database[key].Priority, this.database[key].SyncOptions);
- }
- else
- {
- this.database[key] = new OfflineEntry(key, value, 1, SyncOptions.None);
- }
- }
- }
-
public bool Contains(object key)
{
- return this.ContainsKey(key.ToString());
+ return ContainsKey(key.ToString());
}
IDictionaryEnumerator IDictionary.GetEnumerator()
@@ -88,39 +54,60 @@
public void Remove(object key)
{
- this.Remove(key.ToString());
+ Remove(key.ToString());
}
public bool IsFixedSize => false;
- public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
+ public void Add(object key, object value)
{
- return this.database.Select(d => new KeyValuePair<string, T>(d.Key, d.Value.Deserialize<T>())).GetEnumerator();
+ Add(key.ToString(), (T) value);
}
- IEnumerator IEnumerable.GetEnumerator()
+ public int Count => database.Count;
+
+ public bool IsReadOnly => database.IsReadOnly;
+
+ public ICollection<string> Keys => database.Keys;
+
+ public ICollection<T> Values => database.Values.Select(o => o.Deserialize<T>()).ToList();
+
+ public T this[string key]
+ {
+ get => database[key].Deserialize<T>();
+
+ set
+ {
+ if (database.ContainsKey(key))
+ database[key] = new OfflineEntry(key, value, database[key].Priority, database[key].SyncOptions);
+ else
+ database[key] = new OfflineEntry(key, value, 1, SyncOptions.None);
+ }
+ }
+
+ public IEnumerator<KeyValuePair<string, T>> GetEnumerator()
{
- return this.GetEnumerator();
+ return database.Select(d => new KeyValuePair<string, T>(d.Key, d.Value.Deserialize<T>())).GetEnumerator();
}
- public void Add(KeyValuePair<string, T> item)
+ IEnumerator IEnumerable.GetEnumerator()
{
- this.Add(item.Key, item.Value);
+ return GetEnumerator();
}
- public void Add(object key, object value)
+ public void Add(KeyValuePair<string, T> item)
{
- this.Add(key.ToString(), (T)value);
+ Add(item.Key, item.Value);
}
public void Clear()
{
- this.database.Clear();
+ database.Clear();
}
public bool Contains(KeyValuePair<string, T> item)
{
- return this.ContainsKey(item.Key);
+ return ContainsKey(item.Key);
}
public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex)
@@ -130,29 +117,29 @@
public bool Remove(KeyValuePair<string, T> item)
{
- return this.database.Remove(item.Key);
+ return database.Remove(item.Key);
}
public void Add(string key, T value)
{
- this.database.Add(key, new OfflineEntry(key, value, 1, SyncOptions.None));
+ database.Add(key, new OfflineEntry(key, value, 1, SyncOptions.None));
}
public bool ContainsKey(string key)
{
- return this.database.ContainsKey(key);
+ return database.ContainsKey(key);
}
public bool Remove(string key)
{
- return this.database.Remove(key);
+ return database.Remove(key);
}
public bool TryGetValue(string key, out T value)
{
OfflineEntry val;
- if (this.database.TryGetValue(key, out val))
+ if (database.TryGetValue(key, out val))
{
value = val.Deserialize<T>();
return true;
@@ -162,4 +149,4 @@
return false;
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/OfflineDatabase.cs b/FireBase/Offline/OfflineDatabase.cs
index 9cebf9c..be0380b 100644
--- a/FireBase/Offline/OfflineDatabase.cs
+++ b/FireBase/Offline/OfflineDatabase.cs
@@ -1,201 +1,228 @@
-namespace Firebase.Database.Offline
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using LiteDB;
+
+namespace Firebase.Database.Offline
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
-
- using LiteDB;
-
/// <summary>
- /// The offline database.
+ /// The offline database.
/// </summary>
public class OfflineDatabase : IDictionary<string, OfflineEntry>
{
- private readonly LiteRepository db;
private readonly IDictionary<string, OfflineEntry> cache;
+ private readonly LiteRepository db;
/// <summary>
- /// Initializes a new instance of the <see cref="OfflineDatabase"/> class.
+ /// Initializes a new instance of the <see cref="OfflineDatabase" /> class.
/// </summary>
/// <param name="itemType"> The item type which is used to determine the database file name. </param>
/// <param name="filenameModifier"> Custom string which will get appended to the file name. </param>
public OfflineDatabase(Type itemType, string filenameModifier)
{
- var fullName = this.GetFileName(itemType.ToString());
- if(fullName.Length > 100)
- {
- fullName = fullName.Substring(0, 100);
- }
+ var fullName = GetFileName(itemType.ToString());
+ if (fullName.Length > 100) fullName = fullName.Substring(0, 100);
- BsonMapper mapper = BsonMapper.Global;
+ var mapper = BsonMapper.Global;
mapper.Entity<OfflineEntry>().Id(o => o.Key);
- string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
- string filename = fullName + filenameModifier + ".db";
+ var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
+ var filename = fullName + filenameModifier + ".db";
var path = Path.Combine(root, filename);
- this.db = new LiteRepository(new LiteDatabase(path, mapper));
+ db = new LiteRepository(new LiteDatabase(path, mapper));
- this.cache = db.Database.GetCollection<OfflineEntry>().FindAll()
+ cache = db.Database.GetCollection<OfflineEntry>().FindAll()
.ToDictionary(o => o.Key, o => o);
}
/// <summary>
- /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
+ /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
- /// <returns> The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns>
- public int Count => this.cache.Count;
+ /// <returns> The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />. </returns>
+ public int Count => cache.Count;
/// <summary>
- /// Gets a value indicating whether this is a read-only collection.
+ /// Gets a value indicating whether this is a read-only collection.
/// </summary>
- public bool IsReadOnly => this.cache.IsReadOnly;
+ public bool IsReadOnly => cache.IsReadOnly;
/// <summary>
- /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the
+ /// <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
- /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns>
- public ICollection<string> Keys => this.cache.Keys;
+ /// <returns>
+ /// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that
+ /// implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
+ /// </returns>
+ public ICollection<string> Keys => cache.Keys;
/// <summary>
- /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the
+ /// <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
- /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns>
- public ICollection<OfflineEntry> Values => this.cache.Values;
+ /// <returns>
+ /// An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that
+ /// implements <see cref="T:System.Collections.Generic.IDictionary`2" />.
+ /// </returns>
+ public ICollection<OfflineEntry> Values => cache.Values;
/// <summary>
- /// Gets or sets the element with the specified key.
+ /// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key of the element to get or set.</param>
- /// <returns> The element with the specified key. </returns>
+ /// <returns> The element with the specified key. </returns>
public OfflineEntry this[string key]
{
- get
- {
- return this.cache[key];
- }
+ get => cache[key];
set
{
- this.cache[key] = value;
- this.db.Upsert(value);
+ cache[key] = value;
+ db.Upsert(value);
}
}
/// <summary>
- /// Returns an enumerator that iterates through the collection.
+ /// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns> An enumerator that can be used to iterate through the collection. </returns>
public IEnumerator<KeyValuePair<string, OfflineEntry>> GetEnumerator()
{
- return this.cache.GetEnumerator();
+ return cache.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
- return this.GetEnumerator();
+ return GetEnumerator();
}
/// <summary>
- /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
+ /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
- /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
+ /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
public void Add(KeyValuePair<string, OfflineEntry> item)
{
- this.Add(item.Key, item.Value);
+ Add(item.Key, item.Value);
}
/// <summary>
- /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
- /// </summary>
+ /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />.
+ /// </summary>
public void Clear()
{
- this.cache.Clear();
- this.db.Delete<OfflineEntry>(Query.All());
+ cache.Clear();
+ db.Delete<OfflineEntry>(LiteDB.Query.All());
}
/// <summary>
- /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
+ /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value.
/// </summary>
- /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
- /// <returns> True if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. </returns>
+ /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
+ /// <returns>
+ /// True if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />;
+ /// otherwise, false.
+ /// </returns>
public bool Contains(KeyValuePair<string, OfflineEntry> item)
{
- return this.ContainsKey(item.Key);
+ return ContainsKey(item.Key);
}
/// <summary>
- /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
+ /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an
+ /// <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index.
/// </summary>
- /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
- /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
+ /// <param name="array">
+ /// The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied
+ /// from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have
+ /// zero-based indexing.
+ /// </param>
+ /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param>
public void CopyTo(KeyValuePair<string, OfflineEntry>[] array, int arrayIndex)
{
- this.cache.CopyTo(array, arrayIndex);
+ cache.CopyTo(array, arrayIndex);
}
/// <summary>
- /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
+ /// Removes the first occurrence of a specific object from the
+ /// <see cref="T:System.Collections.Generic.ICollection`1" />.
/// </summary>
- /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
- /// <returns> True if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns>
+ /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param>
+ /// <returns>
+ /// True if <paramref name="item" /> was successfully removed from the
+ /// <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if
+ /// <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />.
+ /// </returns>
public bool Remove(KeyValuePair<string, OfflineEntry> item)
{
- return this.Remove(item.Key);
+ return Remove(item.Key);
}
/// <summary>
- /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
+ /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the
+ /// specified key.
/// </summary>
- /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
- /// <returns> True if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. </returns>
+ /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2" />.</param>
+ /// <returns>
+ /// True if the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the key;
+ /// otherwise, false.
+ /// </returns>
public bool ContainsKey(string key)
{
- return this.cache.ContainsKey(key);
+ return cache.ContainsKey(key);
}
/// <summary>
- /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
public void Add(string key, OfflineEntry value)
{
- this.cache.Add(key, value);
- this.db.Insert(value);
+ cache.Add(key, value);
+ db.Insert(value);
}
/// <summary>
- /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
+ /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
- /// <returns> True if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns>
+ /// <returns>
+ /// True if the element is successfully removed; otherwise, false. This method also returns false if
+ /// <paramref name="key" /> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2" />.
+ /// </returns>
public bool Remove(string key)
{
- this.cache.Remove(key);
- return this.db.Delete<OfflineEntry>(key);
+ cache.Remove(key);
+ return db.Delete<OfflineEntry>(key);
}
/// <summary>
- /// Gets the value associated with the specified key.
- /// </summary>
- /// <param name="key">The key whose value to get.</param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param>
- /// <returns> True if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. </returns>
+ /// Gets the value associated with the specified key.
+ /// </summary>
+ /// <param name="key">The key whose value to get.</param>
+ /// <param name="value">
+ /// When this method returns, the value associated with the specified key, if the key is found;
+ /// otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed
+ /// uninitialized.
+ /// </param>
+ /// <returns>
+ /// True if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an
+ /// element with the specified key; otherwise, false.
+ /// </returns>
public bool TryGetValue(string key, out OfflineEntry value)
{
- return this.cache.TryGetValue(key, out value);
+ return cache.TryGetValue(key, out value);
}
private string GetFileName(string fileName)
{
- var invalidChars = new[] { '`', '[', ',', '=' };
- foreach(char c in invalidChars.Concat(System.IO.Path.GetInvalidFileNameChars()).Distinct())
- {
+ var invalidChars = new[] {'`', '[', ',', '='};
+ foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct())
fileName = fileName.Replace(c, '_');
- }
return fileName;
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/OfflineEntry.cs b/FireBase/Offline/OfflineEntry.cs
index 3b862cb..9feffa3 100644
--- a/FireBase/Offline/OfflineEntry.cs
+++ b/FireBase/Offline/OfflineEntry.cs
@@ -1,41 +1,47 @@
-namespace Firebase.Database.Offline
-{
- using System;
-
- using Newtonsoft.Json;
+using System;
+using Newtonsoft.Json;
+namespace Firebase.Database.Offline
+{
/// <summary>
- /// Represents an object stored in offline storage.
+ /// Represents an object stored in offline storage.
/// </summary>
public class OfflineEntry
{
private object dataInstance;
/// <summary>
- /// Initializes a new instance of the <see cref="OfflineEntry"/> class with an already serialized object.
+ /// Initializes a new instance of the <see cref="OfflineEntry" /> class with an already serialized object.
/// </summary>
/// <param name="key"> The key. </param>
/// <param name="obj"> The object. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
/// <param name="syncOptions"> The sync options. </param>
- public OfflineEntry(string key, object obj, string data, int priority, SyncOptions syncOptions, bool isPartial = false)
+ public OfflineEntry(string key, object obj, string data, int priority, SyncOptions syncOptions,
+ bool isPartial = false)
{
- this.Key = key;
- this.Priority = priority;
- this.Data = data;
- this.Timestamp = DateTime.UtcNow;
- this.SyncOptions = syncOptions;
- this.IsPartial = isPartial;
+ Key = key;
+ Priority = priority;
+ Data = data;
+ Timestamp = DateTime.UtcNow;
+ SyncOptions = syncOptions;
+ IsPartial = isPartial;
- this.dataInstance = obj;
+ dataInstance = obj;
}
/// <summary>
- /// Initializes a new instance of the <see cref="OfflineEntry"/> class.
+ /// Initializes a new instance of the <see cref="OfflineEntry" /> class.
/// </summary>
/// <param name="key"> The key. </param>
/// <param name="obj"> The object. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
/// <param name="syncOptions"> The sync options. </param>
public OfflineEntry(string key, object obj, int priority, SyncOptions syncOptions, bool isPartial = false)
: this(key, obj, JsonConvert.SerializeObject(obj), priority, syncOptions, isPartial)
@@ -43,74 +49,51 @@
}
/// <summary>
- /// Initializes a new instance of the <see cref="OfflineEntry"/> class.
+ /// Initializes a new instance of the <see cref="OfflineEntry" /> class.
/// </summary>
- public OfflineEntry()
+ public OfflineEntry()
{
}
/// <summary>
- /// Gets or sets the key of this entry.
+ /// Gets or sets the key of this entry.
/// </summary>
- public string Key
- {
- get;
- set;
- }
+ public string Key { get; set; }
/// <summary>
- /// Gets or sets the priority. Objects with higher priority will be synced first. Higher number indicates higher priority.
+ /// Gets or sets the priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
/// </summary>
- public int Priority
- {
- get;
- set;
- }
+ public int Priority { get; set; }
/// <summary>
- /// Gets or sets the timestamp when this entry was last touched.
+ /// Gets or sets the timestamp when this entry was last touched.
/// </summary>
- public DateTime Timestamp
- {
- get;
- set;
- }
+ public DateTime Timestamp { get; set; }
/// <summary>
- /// Gets or sets the <see cref="SyncOptions"/> which define what sync state this entry is in.
+ /// Gets or sets the <see cref="SyncOptions" /> which define what sync state this entry is in.
/// </summary>
- public SyncOptions SyncOptions
- {
- get;
- set;
- }
+ public SyncOptions SyncOptions { get; set; }
/// <summary>
- /// Gets or sets serialized JSON data.
+ /// Gets or sets serialized JSON data.
/// </summary>
- public string Data
- {
- get;
- set;
- }
+ public string Data { get; set; }
/// <summary>
- /// Specifies whether this is only a partial object.
+ /// Specifies whether this is only a partial object.
/// </summary>
- public bool IsPartial
- {
- get;
- set;
- }
+ public bool IsPartial { get; set; }
/// <summary>
- /// Deserializes <see cref="Data"/> into <typeparamref name="T"/>. The result is cached.
+ /// Deserializes <see cref="Data" /> into <typeparamref name="T" />. The result is cached.
/// </summary>
/// <typeparam name="T"> Type of object to deserialize into. </typeparam>
- /// <returns> Instance of <typeparamref name="T"/>. </returns>
+ /// <returns> Instance of <typeparamref name="T" />. </returns>
public T Deserialize<T>()
{
- return (T)(this.dataInstance ?? (this.dataInstance = JsonConvert.DeserializeObject<T>(this.Data)));
+ return (T) (dataInstance ?? (dataInstance = JsonConvert.DeserializeObject<T>(Data)));
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/RealtimeDatabase.cs b/FireBase/Offline/RealtimeDatabase.cs
index 61a7010..973db46 100644
--- a/FireBase/Offline/RealtimeDatabase.cs
+++ b/FireBase/Offline/RealtimeDatabase.cs
@@ -1,252 +1,265 @@
-namespace Firebase.Database.Offline
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Net;
+using System.Reactive.Disposables;
+using System.Reactive.Linq;
+using System.Reactive.Subjects;
+using System.Reactive.Threading.Tasks;
+using System.Reflection;
+using System.Threading;
+using System.Threading.Tasks;
+using Firebase.Database.Extensions;
+using Firebase.Database.Offline.Internals;
+using Firebase.Database.Query;
+using Firebase.Database.Streaming;
+using Newtonsoft.Json;
+
+namespace Firebase.Database.Offline
{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reactive.Linq;
- using System.Reactive.Subjects;
- using System.Threading;
- using System.Threading.Tasks;
-
- using Firebase.Database.Extensions;
- using Firebase.Database.Query;
- using Firebase.Database.Streaming;
- using System.Reactive.Threading.Tasks;
- using System.Linq.Expressions;
- using Internals;
- using Newtonsoft.Json;
- using System.Reflection;
- using System.Reactive.Disposables;
-
/// <summary>
- /// The real-time Database which synchronizes online and offline data.
+ /// The real-time Database which synchronizes online and offline data.
/// </summary>
/// <typeparam name="T"> Type of entities. </typeparam>
- public partial class RealtimeDatabase<T> : IDisposable where T : class
+ public class RealtimeDatabase<T> : IDisposable where T : class
{
private readonly ChildQuery childQuery;
private readonly string elementRoot;
- private readonly StreamingOptions streamingOptions;
- private readonly Subject<FirebaseEvent<T>> subject;
+ private readonly FirebaseCache<T> firebaseCache;
private readonly InitialPullStrategy initialPullStrategy;
private readonly bool pushChanges;
- private readonly FirebaseCache<T> firebaseCache;
+ private readonly StreamingOptions streamingOptions;
+ private readonly Subject<FirebaseEvent<T>> subject;
+ private FirebaseSubscription<T> firebaseSubscription;
private bool isSyncRunning;
private IObservable<FirebaseEvent<T>> observable;
- private FirebaseSubscription<T> firebaseSubscription;
/// <summary>
- /// Initializes a new instance of the <see cref="RealtimeDatabase{T}"/> class.
+ /// Initializes a new instance of the <see cref="RealtimeDatabase{T}" /> class.
/// </summary>
/// <param name="childQuery"> The child query. </param>
/// <param name="elementRoot"> The element Root. </param>
/// <param name="offlineDatabaseFactory"> The offline database factory. </param>
/// <param name="filenameModifier"> Custom string which will get appended to the file name. </param>
/// <param name="streamChanges"> Specifies whether changes should be streamed from the server. </param>
- /// <param name="pullEverythingOnStart"> Specifies if everything should be pull from the online storage on start. It only makes sense when <see cref="streamChanges"/> is set to true. </param>
- /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. If this is false, then Put / Post / Delete will not affect server data. </param>
- public RealtimeDatabase(ChildQuery childQuery, string elementRoot, Func<Type, string, IDictionary<string, OfflineEntry>> offlineDatabaseFactory, string filenameModifier, StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, ISetHandler<T> setHandler = null)
+ /// <param name="pullEverythingOnStart">
+ /// Specifies if everything should be pull from the online storage on start. It only
+ /// makes sense when <see cref="streamChanges" /> is set to true.
+ /// </param>
+ /// <param name="pushChanges">
+ /// Specifies whether changed items should actually be pushed to the server. If this is false,
+ /// then Put / Post / Delete will not affect server data.
+ /// </param>
+ public RealtimeDatabase(ChildQuery childQuery, string elementRoot,
+ Func<Type, string, IDictionary<string, OfflineEntry>> offlineDatabaseFactory, string filenameModifier,
+ StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges,
+ ISetHandler<T> setHandler = null)
{
this.childQuery = childQuery;
this.elementRoot = elementRoot;
this.streamingOptions = streamingOptions;
this.initialPullStrategy = initialPullStrategy;
this.pushChanges = pushChanges;
- this.Database = offlineDatabaseFactory(typeof(T), filenameModifier);
- this.firebaseCache = new FirebaseCache<T>(new OfflineCacheAdapter<string, T>(this.Database));
- this.subject = new Subject<FirebaseEvent<T>>();
+ Database = offlineDatabaseFactory(typeof(T), filenameModifier);
+ firebaseCache = new FirebaseCache<T>(new OfflineCacheAdapter<string, T>(Database));
+ subject = new Subject<FirebaseEvent<T>>();
- this.PutHandler = setHandler ?? new SetHandler<T>();
+ PutHandler = setHandler ?? new SetHandler<T>();
- this.isSyncRunning = true;
- Task.Factory.StartNew(this.SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
+ isSyncRunning = true;
+ Task.Factory.StartNew(SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning,
+ TaskScheduler.Default);
}
/// <summary>
- /// Event raised whenever an exception is thrown in the synchronization thread. Exception thrown in there are swallowed, so this event is the only way to get to them.
+ /// Gets the backing Database.
/// </summary>
- public event EventHandler<ExceptionEventArgs> SyncExceptionThrown;
+ public IDictionary<string, OfflineEntry> Database { get; }
- /// <summary>
- /// Gets the backing Database.
- /// </summary>
- public IDictionary<string, OfflineEntry> Database
- {
- get;
- private set;
- }
+ public ISetHandler<T> PutHandler { private get; set; }
- public ISetHandler<T> PutHandler
+ public void Dispose()
{
- private get;
- set;
+ subject.OnCompleted();
+ firebaseSubscription?.Dispose();
}
/// <summary>
- /// Overwrites existing object with given key.
+ /// Event raised whenever an exception is thrown in the synchronization thread. Exception thrown in there are
+ /// swallowed, so this event is the only way to get to them.
+ /// </summary>
+ public event EventHandler<ExceptionEventArgs> SyncExceptionThrown;
+
+ /// <summary>
+ /// Overwrites existing object with given key.
/// </summary>
/// <param name="key"> The key. </param>
/// <param name="obj"> The object to set. </param>
/// <param name="syncOnline"> Indicates whether the item should be synced online. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1)
{
- this.SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions));
+ SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions));
}
- public void Set<TProperty>(string key, Expression<Func<T, TProperty>> propertyExpression, object value, SyncOptions syncOptions, int priority = 1)
+ public void Set<TProperty>(string key, Expression<Func<T, TProperty>> propertyExpression, object value,
+ SyncOptions syncOptions, int priority = 1)
{
- var fullKey = this.GenerateFullKey(key, propertyExpression, syncOptions);
+ var fullKey = GenerateFullKey(key, propertyExpression, syncOptions);
var serializedObject = JsonConvert.SerializeObject(value).Trim('"', '\\');
if (fullKey.Item3)
{
if (typeof(TProperty) != typeof(string) || value == null)
- {
// don't escape non-string primitives and null;
serializedObject = $"{{ \"{fullKey.Item2}\" : {serializedObject} }}";
- }
else
- {
serializedObject = $"{{ \"{fullKey.Item2}\" : \"{serializedObject}\" }}";
- }
}
- var setObject = this.firebaseCache.PushData("/" + fullKey.Item1, serializedObject).First();
+ var setObject = firebaseCache.PushData("/" + fullKey.Item1, serializedObject).First();
- if (!this.Database.ContainsKey(key) || this.Database[key].SyncOptions != SyncOptions.Patch && this.Database[key].SyncOptions != SyncOptions.Put)
- {
- this.Database[fullKey.Item1] = new OfflineEntry(fullKey.Item1, value, serializedObject, priority, syncOptions, true);
- }
+ if (!Database.ContainsKey(key) || Database[key].SyncOptions != SyncOptions.Patch &&
+ Database[key].SyncOptions != SyncOptions.Put)
+ Database[fullKey.Item1] =
+ new OfflineEntry(fullKey.Item1, value, serializedObject, priority, syncOptions, true);
- this.subject.OnNext(new FirebaseEvent<T>(key, setObject.Object, setObject == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline));
+ subject.OnNext(new FirebaseEvent<T>(key, setObject.Object,
+ setObject == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate,
+ FirebaseEventSource.Offline));
}
/// <summary>
- /// Fetches an object with the given key and adds it to the Database.
+ /// Fetches an object with the given key and adds it to the Database.
/// </summary>
/// <param name="key"> The key. </param>
- /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param>
+ /// <param name="priority">
+ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher
+ /// priority.
+ /// </param>
public void Pull(string key, int priority = 1)
{
- if (!this.Database.ContainsKey(key))
- {
- this.Database[key] = new OfflineEntry(key, null, priority, SyncOptions.Pull);
- }
- else if (this.Database[key].SyncOptions == SyncOptions.None)
- {
+ if (!Database.ContainsKey(key))
+ Database[key] = new OfflineEntry(key, null, priority, SyncOptions.Pull);
+ else if (Database[key].SyncOptions == SyncOptions.None)
// pull only if push isn't pending
- this.Database[key].SyncOptions = SyncOptions.Pull;
- }
+ Database[key].SyncOptions = SyncOptions.Pull;
}
/// <summary>
- /// Fetches everything from the remote database.
+ /// Fetches everything from the remote database.
/// </summary>
public async Task PullAsync()
{
- var existingEntries = await this.childQuery
+ var existingEntries = await childQuery
.OnceAsync<T>()
.ToObservable()
.RetryAfterDelay<IReadOnlyCollection<FirebaseObject<T>>, FirebaseException>(
- this.childQuery.Client.Options.SyncPeriod,
- ex => ex.StatusCode == System.Net.HttpStatusCode.OK) // OK implies the request couldn't complete due to network error.
- .Select(e => this.ResetDatabaseFromInitial(e, false))
+ childQuery.Client.Options.SyncPeriod,
+ ex => ex.StatusCode ==
+ HttpStatusCode
+ .OK) // OK implies the request couldn't complete due to network error.
+ .Select(e => ResetDatabaseFromInitial(e, false))
.SelectMany(e => e)
- .Do(e =>
+ .Do(e =>
{
- this.Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None);
- this.subject.OnNext(new FirebaseEvent<T>(e.Key, e.Object, FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePull));
+ Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None);
+ subject.OnNext(new FirebaseEvent<T>(e.Key, e.Object, FirebaseEventType.InsertOrUpdate,
+ FirebaseEventSource.OnlinePull));
})
.ToList();
// Remove items not stored online
- foreach (var item in this.Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList())
+ foreach (var item in Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList())
{
- this.Database.Remove(item);
- this.subject.OnNext(new FirebaseEvent<T>(item, null, FirebaseEventType.Delete, FirebaseEventSource.OnlinePull));
+ Database.Remove(item);
+ subject.OnNext(new FirebaseEvent<T>(item, null, FirebaseEventType.Delete,
+ FirebaseEventSource.OnlinePull));
}
}
/// <summary>
- /// Retrieves all offline items currently stored in local database.
+ /// Retrieves all offline items currently stored in local database.
/// </summary>
public IEnumerable<FirebaseObject<T>> Once()
{
- return this.Database
+ return Database
.Where(kvp => !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial)
.Select(kvp => new FirebaseObject<T>(kvp.Key, kvp.Value.Deserialize<T>()))
.ToList();
}
- /// <summary>
- /// Starts observing the real-time Database. Events will be fired both when change is done locally and remotely.
- /// </summary>
- /// <returns> Stream of <see cref="FirebaseEvent{T}"/>. </returns>
+ /// <summary>
+ /// Starts observing the real-time Database. Events will be fired both when change is done locally and remotely.
+ /// </summary>
+ /// <returns> Stream of <see cref="FirebaseEvent{T}" />. </returns>
public IObservable<FirebaseEvent<T>> AsObservable()
{
- if (!this.isSyncRunning)
+ if (!isSyncRunning)
{
- this.isSyncRunning = true;
- Task.Factory.StartNew(this.SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
+ isSyncRunning = true;
+ Task.Factory.StartNew(SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning,
+ TaskScheduler.Default);
}
- if (this.observable == null)
+ if (observable == null)
{
var initialData = Observable.Return(FirebaseEvent<T>.Empty(FirebaseEventSource.Offline));
- if(this.Database.TryGetValue(this.elementRoot, out OfflineEntry oe))
- {
+ if (Database.TryGetValue(elementRoot, out var oe))
initialData = Observable.Return(oe)
- .Where(offlineEntry => !string.IsNullOrEmpty(offlineEntry.Data) && offlineEntry.Data != "null" && !offlineEntry.IsPartial)
- .Select(offlineEntry => new FirebaseEvent<T>(offlineEntry.Key, offlineEntry.Deserialize<T>(), FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline));
- }
- else if(this.Database.Count > 0)
- {
- initialData = this.Database
- .Where(kvp => !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial)
- .Select(kvp => new FirebaseEvent<T>(kvp.Key, kvp.Value.Deserialize<T>(), FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline))
+ .Where(offlineEntry =>
+ !string.IsNullOrEmpty(offlineEntry.Data) && offlineEntry.Data != "null" &&
+ !offlineEntry.IsPartial)
+ .Select(offlineEntry => new FirebaseEvent<T>(offlineEntry.Key, offlineEntry.Deserialize<T>(),
+ FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline));
+ else if (Database.Count > 0)
+ initialData = Database
+ .Where(kvp =>
+ !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial)
+ .Select(kvp => new FirebaseEvent<T>(kvp.Key, kvp.Value.Deserialize<T>(),
+ FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline))
.ToList()
.ToObservable();
- }
- this.observable = initialData
- .Merge(this.subject)
- .Merge(this.GetInitialPullObservable()
- .RetryAfterDelay<IReadOnlyCollection<FirebaseObject<T>>, FirebaseException>(
- this.childQuery.Client.Options.SyncPeriod,
- ex => ex.StatusCode == System.Net.HttpStatusCode.OK) // OK implies the request couldn't complete due to network error.
- .Select(e => this.ResetDatabaseFromInitial(e))
- .SelectMany(e => e)
- .Do(this.SetObjectFromInitialPull)
- .Select(e => new FirebaseEvent<T>(e.Key, e.Object, e.Object == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlineInitial))
- .Concat(Observable.Create<FirebaseEvent<T>>(observer => this.InitializeStreamingSubscription(observer))))
- .Do(next => { }, e => this.observable = null, () => this.observable = null)
+ observable = initialData
+ .Merge(subject)
+ .Merge(GetInitialPullObservable()
+ .RetryAfterDelay<IReadOnlyCollection<FirebaseObject<T>>, FirebaseException>(
+ childQuery.Client.Options.SyncPeriod,
+ ex => ex.StatusCode ==
+ HttpStatusCode
+ .OK) // OK implies the request couldn't complete due to network error.
+ .Select(e => ResetDatabaseFromInitial(e))
+ .SelectMany(e => e)
+ .Do(SetObjectFromInitialPull)
+ .Select(e => new FirebaseEvent<T>(e.Key, e.Object,
+ e.Object == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate,
+ FirebaseEventSource.OnlineInitial))
+ .Concat(Observable.Create<FirebaseEvent<T>>(observer =>
+ InitializeStreamingSubscription(observer))))
+ .Do(next => { }, e => observable = null, () => observable = null)
.Replay()
.RefCount();
}
- return this.observable;
- }
-
- public void Dispose()
- {
- this.subject.OnCompleted();
- this.firebaseSubscription?.Dispose();
+ return observable;
}
- private IReadOnlyCollection<FirebaseObject<T>> ResetDatabaseFromInitial(IReadOnlyCollection<FirebaseObject<T>> collection, bool onlyWhenInitialEverything = true)
+ private IReadOnlyCollection<FirebaseObject<T>> ResetDatabaseFromInitial(
+ IReadOnlyCollection<FirebaseObject<T>> collection, bool onlyWhenInitialEverything = true)
{
- if (onlyWhenInitialEverything && this.initialPullStrategy != InitialPullStrategy.Everything)
- {
- return collection;
- }
+ if (onlyWhenInitialEverything && initialPullStrategy != InitialPullStrategy.Everything) return collection;
// items which are in local db, but not in the online collection
- var extra = this.Once()
- .Select(f => f.Key)
- .Except(collection.Select(c => c.Key))
- .Select(k => new FirebaseObject<T>(k, null));
+ var extra = Once()
+ .Select(f => f.Key)
+ .Except(collection.Select(c => c.Key))
+ .Select(k => new FirebaseObject<T>(k, null));
return collection.Concat(extra).ToList();
}
@@ -257,101 +270,101 @@
// and the InitialPullStrategy != Everything
// this attempts to deal with scenario when you are offline, have local changes and go online
// in this case having the InitialPullStrategy set to everything would basically purge all local changes
- if (!this.Database.ContainsKey(e.Key) || this.Database[e.Key].SyncOptions == SyncOptions.None || this.Database[e.Key].SyncOptions == SyncOptions.Pull || this.initialPullStrategy != InitialPullStrategy.Everything)
- {
- this.Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None);
- }
+ if (!Database.ContainsKey(e.Key) || Database[e.Key].SyncOptions == SyncOptions.None ||
+ Database[e.Key].SyncOptions == SyncOptions.Pull ||
+ initialPullStrategy != InitialPullStrategy.Everything)
+ Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None);
}
private IObservable<IReadOnlyCollection<FirebaseObject<T>>> GetInitialPullObservable()
{
FirebaseQuery query;
- switch (this.initialPullStrategy)
+ switch (initialPullStrategy)
{
case InitialPullStrategy.MissingOnly:
- query = this.childQuery.OrderByKey().StartAt(() => this.GetLatestKey());
+ query = childQuery.OrderByKey().StartAt(() => GetLatestKey());
break;
case InitialPullStrategy.Everything:
- query = this.childQuery;
+ query = childQuery;
break;
case InitialPullStrategy.None:
default:
return Observable.Empty<IReadOnlyCollection<FirebaseEvent<T>>>();
}
- if (string.IsNullOrWhiteSpace(this.elementRoot))
- {
+ if (string.IsNullOrWhiteSpace(elementRoot))
return Observable.Defer(() => query.OnceAsync<T>().ToObservable());
- }
-
+
// there is an element root, which indicates the target location is not a collection but a single element
- return Observable.Defer(async () => Observable.Return(await query.OnceSingleAsync<T>()).Select(e => new[] { new FirebaseObject<T>(this.elementRoot, e) }));
+ return Observable.Defer(async () =>
+ Observable.Return(await query.OnceSingleAsync<T>())
+ .Select(e => new[] {new FirebaseObject<T>(elementRoot, e)}));
}
private IDisposable InitializeStreamingSubscription(IObserver<FirebaseEvent<T>> observer)
{
- var completeDisposable = Disposable.Create(() => this.isSyncRunning = false);
+ var completeDisposable = Disposable.Create(() => isSyncRunning = false);
- switch (this.streamingOptions)
+ switch (streamingOptions)
{
case StreamingOptions.LatestOnly:
// stream since the latest key
- var queryLatest = this.childQuery.OrderByKey().StartAt(() => this.GetLatestKey());
- this.firebaseSubscription = new FirebaseSubscription<T>(observer, queryLatest, this.elementRoot, this.firebaseCache);
- this.firebaseSubscription.ExceptionThrown += this.StreamingExceptionThrown;
+ var queryLatest = childQuery.OrderByKey().StartAt(() => GetLatestKey());
+ firebaseSubscription =
+ new FirebaseSubscription<T>(observer, queryLatest, elementRoot, firebaseCache);
+ firebaseSubscription.ExceptionThrown += StreamingExceptionThrown;
- return new CompositeDisposable(this.firebaseSubscription.Run(), completeDisposable);
+ return new CompositeDisposable(firebaseSubscription.Run(), completeDisposable);
case StreamingOptions.Everything:
// stream everything
- var queryAll = this.childQuery;
- this.firebaseSubscription = new FirebaseSubscription<T>(observer, queryAll, this.elementRoot, this.firebaseCache);
- this.firebaseSubscription.ExceptionThrown += this.StreamingExceptionThrown;
+ var queryAll = childQuery;
+ firebaseSubscription = new FirebaseSubscription<T>(observer, queryAll, elementRoot, firebaseCache);
+ firebaseSubscription.ExceptionThrown += StreamingExceptionThrown;
- return new CompositeDisposable(this.firebaseSubscription.Run(), completeDisposable);
- default:
- break;
+ return new CompositeDisposable(firebaseSubscription.Run(), completeDisposable);
}
return completeDisposable;
}
- private void SetAndRaise(string key, OfflineEntry obj, FirebaseEventSource eventSource = FirebaseEventSource.Offline)
+ private void SetAndRaise(string key, OfflineEntry obj,
+ FirebaseEventSource eventSource = FirebaseEventSource.Offline)
{
- this.Database[key] = obj;
- this.subject.OnNext(new FirebaseEvent<T>(key, obj?.Deserialize<T>(), string.IsNullOrEmpty(obj?.Data) || obj?.Data == "null" ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, eventSource));
+ Database[key] = obj;
+ subject.OnNext(new FirebaseEvent<T>(key, obj?.Deserialize<T>(),
+ string.IsNullOrEmpty(obj?.Data) || obj?.Data == "null"
+ ? FirebaseEventType.Delete
+ : FirebaseEventType.InsertOrUpdate, eventSource));
}
private async void SynchronizeThread()
{
- while (this.isSyncRunning)
+ while (isSyncRunning)
{
try
{
- var validEntries = this.Database.Where(e => e.Value != null);
- await this.PullEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Pull));
+ var validEntries = Database.Where(e => e.Value != null);
+ await PullEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Pull));
- if (this.pushChanges)
- {
- await this.PushEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Put || kvp.Value.SyncOptions == SyncOptions.Patch));
- }
+ if (pushChanges)
+ await PushEntriesAsync(validEntries.Where(kvp =>
+ kvp.Value.SyncOptions == SyncOptions.Put || kvp.Value.SyncOptions == SyncOptions.Patch));
}
catch (Exception ex)
{
- this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
+ SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
}
- await Task.Delay(this.childQuery.Client.Options.SyncPeriod);
+ await Task.Delay(childQuery.Client.Options.SyncPeriod);
}
}
private string GetLatestKey()
{
- var key = this.Database.OrderBy(o => o.Key, StringComparer.Ordinal).LastOrDefault().Key ?? string.Empty;
+ var key = Database.OrderBy(o => o.Key, StringComparer.Ordinal).LastOrDefault().Key ?? string.Empty;
if (!string.IsNullOrWhiteSpace(key))
- {
- key = key.Substring(0, key.Length - 1) + (char)(key[key.Length - 1] + 1);
- }
+ key = key.Substring(0, key.Length - 1) + (char) (key[key.Length - 1] + 1);
return key;
}
@@ -362,10 +375,11 @@
foreach (var group in groups)
{
- var tasks = group.OrderBy(kvp => kvp.Value.IsPartial).Select(kvp =>
- kvp.Value.IsPartial ?
- this.ResetSyncAfterPush(this.PutHandler.SetAsync(this.childQuery, kvp.Key, kvp.Value), kvp.Key) :
- this.ResetSyncAfterPush(this.PutHandler.SetAsync(this.childQuery, kvp.Key, kvp.Value), kvp.Key, kvp.Value.Deserialize<T>()));
+ 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<T>()));
try
{
@@ -373,7 +387,7 @@
}
catch (Exception ex)
{
- this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
+ SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
}
}
}
@@ -384,15 +398,18 @@
foreach (var group in taskGroups)
{
- var tasks = group.Select(pair => this.ResetAfterPull(this.childQuery.Child(pair.Key == this.elementRoot ? string.Empty : pair.Key).OnceSingleAsync<T>(), pair.Key, pair.Value));
+ var tasks = group.Select(pair =>
+ ResetAfterPull(
+ childQuery.Child(pair.Key == elementRoot ? string.Empty : pair.Key).OnceSingleAsync<T>(),
+ pair.Key, pair.Value));
try
- {
+ {
await Task.WhenAll(tasks).WithAggregateException();
}
catch (Exception ex)
{
- this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
+ SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
}
}
}
@@ -400,46 +417,48 @@
private async Task ResetAfterPull(Task<T> task, string key, OfflineEntry entry)
{
await task;
- this.SetAndRaise(key, new OfflineEntry(key, task.Result, entry.Priority, SyncOptions.None), FirebaseEventSource.OnlinePull);
+ SetAndRaise(key, new OfflineEntry(key, task.Result, entry.Priority, SyncOptions.None),
+ FirebaseEventSource.OnlinePull);
}
private async Task ResetSyncAfterPush(Task task, string key, T obj)
{
- await this.ResetSyncAfterPush(task, key);
+ await ResetSyncAfterPush(task, key);
- if (this.streamingOptions == StreamingOptions.None)
- {
- this.subject.OnNext(new FirebaseEvent<T>(key, obj, obj == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePush));
- }
+ if (streamingOptions == StreamingOptions.None)
+ subject.OnNext(new FirebaseEvent<T>(key, obj,
+ obj == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate,
+ FirebaseEventSource.OnlinePush));
}
private async Task ResetSyncAfterPush(Task task, string key)
{
await task;
- this.ResetSyncOptions(key);
+ ResetSyncOptions(key);
}
private void ResetSyncOptions(string key)
{
- var item = this.Database[key];
+ var item = Database[key];
if (item.IsPartial)
{
- this.Database.Remove(key);
+ Database.Remove(key);
}
else
{
item.SyncOptions = SyncOptions.None;
- this.Database[key] = item;
+ Database[key] = item;
}
}
private void StreamingExceptionThrown(object sender, ExceptionEventArgs<FirebaseException> e)
{
- this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception));
+ SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception));
}
- private Tuple<string, string, bool> GenerateFullKey<TProperty>(string key, Expression<Func<T, TProperty>> propertyGetter, SyncOptions syncOptions)
+ private Tuple<string, string, bool> GenerateFullKey<TProperty>(string key,
+ Expression<Func<T, TProperty>> propertyGetter, SyncOptions syncOptions)
{
var visitor = new MemberAccessVisitor();
visitor.Visit(propertyGetter);
@@ -447,13 +466,14 @@
var prefix = key == string.Empty ? string.Empty : key + "/";
// primitive types
- if (syncOptions == SyncOptions.Patch && (propertyType.IsPrimitive || Nullable.GetUnderlyingType(typeof(TProperty)) != null || typeof(TProperty) == typeof(string)))
- {
- return Tuple.Create(prefix + string.Join("/", visitor.PropertyNames.Skip(1).Reverse()), visitor.PropertyNames.First(), true);
- }
-
- return Tuple.Create(prefix + string.Join("/", visitor.PropertyNames.Reverse()), visitor.PropertyNames.First(), false);
+ if (syncOptions == SyncOptions.Patch && (propertyType.IsPrimitive ||
+ Nullable.GetUnderlyingType(typeof(TProperty)) != null ||
+ typeof(TProperty) == typeof(string)))
+ return Tuple.Create(prefix + string.Join("/", visitor.PropertyNames.Skip(1).Reverse()),
+ visitor.PropertyNames.First(), true);
+
+ return Tuple.Create(prefix + string.Join("/", visitor.PropertyNames.Reverse()),
+ visitor.PropertyNames.First(), false);
}
-
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/SetHandler.cs b/FireBase/Offline/SetHandler.cs
index 1efa7b6..6314c3c 100644
--- a/FireBase/Offline/SetHandler.cs
+++ b/FireBase/Offline/SetHandler.cs
@@ -1,9 +1,8 @@
-namespace Firebase.Database.Offline
-{
- using Firebase.Database.Query;
-
- using System.Threading.Tasks;
+using System.Threading.Tasks;
+using Firebase.Database.Query;
+namespace Firebase.Database.Offline
+{
public class SetHandler<T> : ISetHandler<T>
{
public virtual async Task SetAsync(ChildQuery query, string key, OfflineEntry entry)
@@ -11,14 +10,10 @@
using (var child = query.Child(key))
{
if (entry.SyncOptions == SyncOptions.Put)
- {
await child.PutAsync(entry.Data);
- }
else
- {
await child.PatchAsync(entry.Data);
- }
}
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/StreamingOptions.cs b/FireBase/Offline/StreamingOptions.cs
index 9ed4e54..a420cbb 100644
--- a/FireBase/Offline/StreamingOptions.cs
+++ b/FireBase/Offline/StreamingOptions.cs
@@ -3,19 +3,21 @@
public enum StreamingOptions
{
/// <summary>
- /// No realtime streaming.
+ /// No realtime streaming.
/// </summary>
None,
/// <summary>
- /// Streaming of only new items - not the existing ones.
+ /// Streaming of only new items - not the existing ones.
/// </summary>
LatestOnly,
/// <summary>
- /// Streaming of all items. This will also pull all existing items on start, so be mindful about the number of items in your DB.
- /// When used, consider not setting the <see cref="InitialPullStrategy"/> to <see cref="InitialPullStrategy.Everything"/> because you would pointlessly pull everything twice.
+ /// Streaming of all items. This will also pull all existing items on start, so be mindful about the number of items in
+ /// your DB.
+ /// When used, consider not setting the <see cref="InitialPullStrategy" /> to
+ /// <see cref="InitialPullStrategy.Everything" /> because you would pointlessly pull everything twice.
/// </summary>
Everything
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Offline/SyncOptions.cs b/FireBase/Offline/SyncOptions.cs
index b2f382a..ca68d0a 100644
--- a/FireBase/Offline/SyncOptions.cs
+++ b/FireBase/Offline/SyncOptions.cs
@@ -1,28 +1,28 @@
namespace Firebase.Database.Offline
{
/// <summary>
- /// Specifies type of sync requested for given data.
+ /// Specifies type of sync requested for given data.
/// </summary>
public enum SyncOptions
{
/// <summary>
- /// No sync needed for given data.
+ /// No sync needed for given data.
/// </summary>
None,
/// <summary>
- /// Data should be pulled from firebase.
+ /// Data should be pulled from firebase.
/// </summary>
Pull,
/// <summary>
- /// Data should be put to firebase.
+ /// Data should be put to firebase.
/// </summary>
Put,
/// <summary>
- /// Data should be patched in firebase.
+ /// Data should be patched in firebase.
/// </summary>
Patch
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/AuthQuery.cs b/FireBase/Query/AuthQuery.cs
index 8a8d3e8..2cfda3c 100644
--- a/FireBase/Query/AuthQuery.cs
+++ b/FireBase/Query/AuthQuery.cs
@@ -1,33 +1,34 @@
+using System;
+
namespace Firebase.Database.Query
{
- using System;
-
/// <summary>
- /// Represents an auth parameter in firebase query, e.g. "?auth=xyz".
+ /// Represents an auth parameter in firebase query, e.g. "?auth=xyz".
/// </summary>
public class AuthQuery : ParameterQuery
{
private readonly Func<string> tokenFactory;
/// <summary>
- /// Initializes a new instance of the <see cref="AuthQuery"/> class.
+ /// Initializes a new instance of the <see cref="AuthQuery" /> class.
/// </summary>
- /// <param name="parent"> The parent. </param>
+ /// <param name="parent"> The parent. </param>
/// <param name="tokenFactory"> The authentication token factory. </param>
/// <param name="client"> The owner. </param>
- public AuthQuery(FirebaseQuery parent, Func<string> tokenFactory, FirebaseClient client) : base(parent, () => client.Options.AsAccessToken ? "access_token" : "auth", client)
+ public AuthQuery(FirebaseQuery parent, Func<string> tokenFactory, FirebaseClient client) : base(parent,
+ () => client.Options.AsAccessToken ? "access_token" : "auth", client)
{
this.tokenFactory = tokenFactory;
}
/// <summary>
- /// Build the url parameter value of this child.
+ /// Build the url parameter value of this child.
/// </summary>
/// <param name="child"> The child of this child. </param>
- /// <returns> The <see cref="string"/>. </returns>
+ /// <returns> The <see cref="string" />. </returns>
protected override string BuildUrlParameter(FirebaseQuery child)
{
- return this.tokenFactory();
+ return tokenFactory();
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/ChildQuery.cs b/FireBase/Query/ChildQuery.cs
index 1696ea8..014fe09 100644
--- a/FireBase/Query/ChildQuery.cs
+++ b/FireBase/Query/ChildQuery.cs
@@ -1,16 +1,16 @@
+using System;
+
namespace Firebase.Database.Query
{
- using System;
-
/// <summary>
- /// Firebase query which references the child of current node.
+ /// Firebase query which references the child of current node.
/// </summary>
public class ChildQuery : FirebaseQuery
{
private readonly Func<string> pathFactory;
/// <summary>
- /// Initializes a new instance of the <see cref="ChildQuery"/> class.
+ /// Initializes a new instance of the <see cref="ChildQuery" /> class.
/// </summary>
/// <param name="parent"> The parent. </param>
/// <param name="pathFactory"> The path to the child node. </param>
@@ -22,7 +22,7 @@ namespace Firebase.Database.Query
}
/// <summary>
- /// Initializes a new instance of the <see cref="ChildQuery"/> class.
+ /// Initializes a new instance of the <see cref="ChildQuery" /> class.
/// </summary>
/// <param name="client"> The client. </param>
/// <param name="pathFactory"> The path to the child node. </param>
@@ -32,25 +32,19 @@ namespace Firebase.Database.Query
}
/// <summary>
- /// Build the url segment of this child.
+ /// Build the url segment of this child.
/// </summary>
/// <param name="child"> The child of this child. </param>
- /// <returns> The <see cref="string"/>. </returns>
+ /// <returns> The <see cref="string" />. </returns>
protected override string BuildUrlSegment(FirebaseQuery child)
{
- var s = this.pathFactory();
+ var s = pathFactory();
- if (s != string.Empty && !s.EndsWith("/"))
- {
- s += '/';
- }
+ if (s != string.Empty && !s.EndsWith("/")) s += '/';
- if (!(child is ChildQuery))
- {
- return s + ".json";
- }
+ if (!(child is ChildQuery)) return s + ".json";
return s;
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/FilterQuery.cs b/FireBase/Query/FilterQuery.cs
index f9f6271..3434d1d 100644
--- a/FireBase/Query/FilterQuery.cs
+++ b/FireBase/Query/FilterQuery.cs
@@ -1,81 +1,77 @@
-namespace Firebase.Database.Query
-{
- using System;
- using System.Globalization;
+using System;
+using System.Globalization;
+namespace Firebase.Database.Query
+{
/// <summary>
- /// Represents a firebase filtering query, e.g. "?LimitToLast=10".
+ /// Represents a firebase filtering query, e.g. "?LimitToLast=10".
/// </summary>
- public class FilterQuery : ParameterQuery
+ public class FilterQuery : ParameterQuery
{
- private readonly Func<string> valueFactory;
- private readonly Func<double> doubleValueFactory;
private readonly Func<bool> boolValueFactory;
+ private readonly Func<double> doubleValueFactory;
+ private readonly Func<string> valueFactory;
/// <summary>
- /// Initializes a new instance of the <see cref="FilterQuery"/> class.
+ /// Initializes a new instance of the <see cref="FilterQuery" /> class.
/// </summary>
/// <param name="parent"> The parent. </param>
/// <param name="filterFactory"> The filter. </param>
/// <param name="valueFactory"> The value for filter. </param>
- /// <param name="client"> The owning client. </param>
- public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<string> valueFactory, FirebaseClient client)
+ /// <param name="client"> The owning client. </param>
+ public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<string> valueFactory,
+ FirebaseClient client)
: base(parent, filterFactory, client)
{
this.valueFactory = valueFactory;
}
/// <summary>
- /// Initializes a new instance of the <see cref="FilterQuery"/> class.
+ /// Initializes a new instance of the <see cref="FilterQuery" /> class.
/// </summary>
/// <param name="parent"> The parent. </param>
/// <param name="filterFactory"> The filter. </param>
/// <param name="valueFactory"> The value for filter. </param>
/// <param name="client"> The owning client. </param>
- public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<double> valueFactory, FirebaseClient client)
+ public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<double> valueFactory,
+ FirebaseClient client)
: base(parent, filterFactory, client)
{
- this.doubleValueFactory = valueFactory;
+ doubleValueFactory = valueFactory;
}
/// <summary>
- /// Initializes a new instance of the <see cref="FilterQuery"/> class.
+ /// Initializes a new instance of the <see cref="FilterQuery" /> class.
/// </summary>
/// <param name="parent"> The parent. </param>
/// <param name="filterFactory"> The filter. </param>
/// <param name="valueFactory"> The value for filter. </param>
/// <param name="client"> The owning client. </param>
- public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<bool> valueFactory, FirebaseClient client)
+ public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<bool> valueFactory,
+ FirebaseClient client)
: base(parent, filterFactory, client)
{
- this.boolValueFactory = valueFactory;
+ boolValueFactory = valueFactory;
}
/// <summary>
- /// The build url parameter.
+ /// The build url parameter.
/// </summary>
- /// <param name="child"> The child. </param>
- /// <returns> Url parameter part of the resulting path. </returns>
+ /// <param name="child"> The child. </param>
+ /// <returns> Url parameter part of the resulting path. </returns>
protected override string BuildUrlParameter(FirebaseQuery child)
{
- if (this.valueFactory != null)
- {
- if(this.valueFactory() == null)
- {
- return $"null";
- }
- return $"\"{this.valueFactory()}\"";
- }
- else if (this.doubleValueFactory != null)
+ if (valueFactory != null)
{
- return this.doubleValueFactory().ToString(CultureInfo.InvariantCulture);
- }
- else if (this.boolValueFactory != null)
- {
- return $"{this.boolValueFactory().ToString().ToLower()}";
+ if (valueFactory() == null) return "null";
+ return $"\"{valueFactory()}\"";
}
+ if (doubleValueFactory != null)
+ return doubleValueFactory().ToString(CultureInfo.InvariantCulture);
+ if (boolValueFactory != null) return $"{boolValueFactory().ToString().ToLower()}";
+
return string.Empty;
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/FirebaseQuery.cs b/FireBase/Query/FirebaseQuery.cs
index 3513c85..60d0289 100644
--- a/FireBase/Query/FirebaseQuery.cs
+++ b/FireBase/Query/FirebaseQuery.cs
@@ -1,71 +1,106 @@
+using System;
+using System.Collections.Generic;
+using System.Net;
+using System.Net.Http;
+using System.Reactive.Linq;
+using System.Threading.Tasks;
+using Firebase.Database.Http;
+using Firebase.Database.Streaming;
+using Newtonsoft.Json;
+
namespace Firebase.Database.Query
{
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
- using System.Reactive.Linq;
- using System.Threading.Tasks;
-
- using Firebase.Database.Http;
- using Firebase.Database.Offline;
- using Firebase.Database.Streaming;
-
- using Newtonsoft.Json;
- using System.Net;
-
/// <summary>
- /// Represents a firebase query.
+ /// Represents a firebase query.
/// </summary>
public abstract class FirebaseQuery : IFirebaseQuery, IDisposable
{
- protected TimeSpan DEFAULT_HTTP_CLIENT_TIMEOUT = new TimeSpan(0, 0, 180);
-
protected readonly FirebaseQuery Parent;
private HttpClient client;
+ protected TimeSpan DEFAULT_HTTP_CLIENT_TIMEOUT = new TimeSpan(0, 0, 180);
- /// <summary>
- /// Initializes a new instance of the <see cref="FirebaseQuery"/> class.
+ /// <summary>
+ /// Initializes a new instance of the <see cref="FirebaseQuery" /> class.
/// </summary>
/// <param name="parent"> The parent of this query. </param>
/// <param name="client"> The owning client. </param>
protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client)
{
- this.Client = client;
- this.Parent = parent;
+ Client = client;
+ Parent = parent;
}
/// <summary>
- /// Gets the client.
+ /// Disposes this instance.
/// </summary>
- public FirebaseClient Client
+ public void Dispose()
{
- get;
+ client?.Dispose();
}
/// <summary>
- /// Queries the firebase server once returning collection of items.
+ /// Gets the client.
+ /// </summary>
+ public FirebaseClient Client { get; }
+
+ /// <summary>
+ /// Queries the firebase server once returning collection of items.
/// </summary>
/// <param name="timeout"> Optional timeout value. </param>
/// <typeparam name="T"> Type of elements. </typeparam>
- /// <returns> Collection of <see cref="FirebaseObject{T}"/> holding the entities returned by server. </returns>
+ /// <returns> Collection of <see cref="FirebaseObject{T}" /> holding the entities returned by server. </returns>
public async Task<IReadOnlyCollection<FirebaseObject<T>>> OnceAsync<T>(TimeSpan? timeout = null)
{
var url = string.Empty;
try
{
- url = await this.BuildUrlAsync().ConfigureAwait(false);
+ url = await BuildUrlAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
- throw new FirebaseException("Couldn't build the url", string.Empty, string.Empty, HttpStatusCode.OK, ex);
+ throw new FirebaseException("Couldn't build the url", string.Empty, string.Empty, HttpStatusCode.OK,
+ ex);
}
- return await this.GetClient(timeout).GetObjectCollectionAsync<T>(url, Client.Options.JsonSerializerSettings)
+ return await GetClient(timeout).GetObjectCollectionAsync<T>(url, Client.Options.JsonSerializerSettings)
.ConfigureAwait(false);
}
+ /// <summary>
+ /// Starts observing this query watching for changes real time sent by the server.
+ /// </summary>
+ /// <typeparam name="T"> Type of elements. </typeparam>
+ /// <param name="elementRoot"> Optional custom root element of received json items. </param>
+ /// <returns> Observable stream of <see cref="FirebaseEvent{T}" />. </returns>
+ public IObservable<FirebaseEvent<T>> AsObservable<T>(
+ EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler = null, string elementRoot = "")
+ {
+ return Observable.Create<FirebaseEvent<T>>(observer =>
+ {
+ var sub = new FirebaseSubscription<T>(observer, this, elementRoot, new FirebaseCache<T>());
+ sub.ExceptionThrown += exceptionHandler;
+ return sub.Run();
+ });
+ }
+
+ /// <summary>
+ /// Builds the actual URL of this query.
+ /// </summary>
+ /// <returns> The <see cref="string" />. </returns>
+ public async Task<string> BuildUrlAsync()
+ {
+ // if token factory is present on the parent then use it to generate auth token
+ if (Client.Options.AuthTokenAsyncFactory != null)
+ {
+ var token = await Client.Options.AuthTokenAsyncFactory().ConfigureAwait(false);
+ return this.WithAuth(token).BuildUrl(null);
+ }
+
+ return BuildUrl(null);
+ }
+
/*public async Task<IReadOnlyCollection<FirebaseObject<Object>>> OnceAsync(Type dataType, TimeSpan? timeout = null)
{
var url = string.Empty;
@@ -84,11 +119,11 @@ namespace Firebase.Database.Query
}*/
/// <summary>
- /// Assumes given query is pointing to a single object of type <typeparamref name="T"/> and retrieves it.
+ /// Assumes given query is pointing to a single object of type <typeparamref name="T" /> and retrieves it.
/// </summary>
/// <param name="timeout"> Optional timeout value. </param>
/// <typeparam name="T"> Type of elements. </typeparam>
- /// <returns> Single object of type <typeparamref name="T"/>. </returns>
+ /// <returns> Single object of type <typeparamref name="T" />. </returns>
public async Task<T> OnceSingleAsync<T>(TimeSpan? timeout = null)
{
var responseData = string.Empty;
@@ -97,7 +132,7 @@ namespace Firebase.Database.Query
try
{
- url = await this.BuildUrlAsync().ConfigureAwait(false);
+ url = await BuildUrlAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -106,7 +141,7 @@ namespace Firebase.Database.Query
try
{
- var response = await this.GetClient(timeout).GetAsync(url).ConfigureAwait(false);
+ var response = await GetClient(timeout).GetAsync(url).ConfigureAwait(false);
statusCode = response.StatusCode;
responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
@@ -122,108 +157,75 @@ namespace Firebase.Database.Query
}
/// <summary>
- /// Starts observing this query watching for changes real time sent by the server.
- /// </summary>
- /// <typeparam name="T"> Type of elements. </typeparam>
- /// <param name="elementRoot"> Optional custom root element of received json items. </param>
- /// <returns> Observable stream of <see cref="FirebaseEvent{T}"/>. </returns>
- public IObservable<FirebaseEvent<T>> AsObservable<T>(EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler = null, string elementRoot = "")
- {
- return Observable.Create<FirebaseEvent<T>>(observer =>
- {
- var sub = new FirebaseSubscription<T>(observer, this, elementRoot, new FirebaseCache<T>());
- sub.ExceptionThrown += exceptionHandler;
- return sub.Run();
- });
- }
-
- /// <summary>
- /// Builds the actual URL of this query.
- /// </summary>
- /// <returns> The <see cref="string"/>. </returns>
- public async Task<string> BuildUrlAsync()
- {
- // if token factory is present on the parent then use it to generate auth token
- if (this.Client.Options.AuthTokenAsyncFactory != null)
- {
- var token = await this.Client.Options.AuthTokenAsyncFactory().ConfigureAwait(false);
- return this.WithAuth(token).BuildUrl(null);
- }
-
- return this.BuildUrl(null);
- }
-
- /// <summary>
- /// Posts given object to repository.
+ /// Posts given object to repository.
/// </summary>
/// <param name="obj"> The object. </param>
/// <param name="generateKeyOffline"> Specifies whether the key should be generated offline instead of online. </param>
/// <param name="timeout"> Optional timeout value. </param>
- /// <typeparam name="T"> Type of <see cref="obj"/> </typeparam>
+ /// <typeparam name="T"> Type of <see cref="obj" /> </typeparam>
/// <returns> Resulting firebase object with populated key. </returns>
- public async Task<FirebaseObject<string>> PostAsync(string data, bool generateKeyOffline = true, TimeSpan? timeout = null)
+ public async Task<FirebaseObject<string>> PostAsync(string data, bool generateKeyOffline = true,
+ TimeSpan? timeout = null)
{
// post generates a new key server-side, while put can be used with an already generated local key
if (generateKeyOffline)
{
var key = FirebaseKeyGenerator.Next();
- await new ChildQuery(this, () => key, this.Client).PutAsync(data).ConfigureAwait(false);
+ await new ChildQuery(this, () => key, Client).PutAsync(data).ConfigureAwait(false);
return new FirebaseObject<string>(key, data);
}
- else
- {
- var c = this.GetClient(timeout);
- var sendData = await this.SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false);
- var result = JsonConvert.DeserializeObject<PostResult>(sendData, Client.Options.JsonSerializerSettings);
- return new FirebaseObject<string>(result.Name, data);
- }
+ var c = GetClient(timeout);
+ var sendData = await SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false);
+ var result = JsonConvert.DeserializeObject<PostResult>(sendData, Client.Options.JsonSerializerSettings);
+
+ return new FirebaseObject<string>(result.Name, data);
}
/// <summary>
- /// Patches data at given location instead of overwriting them.
- /// </summary>
+ /// Patches data at given location instead of overwriting them.
+ /// </summary>
/// <param name="obj"> The object. </param>
/// <param name="timeout"> Optional timeout value. </param>
- /// <typeparam name="T"> Type of <see cref="obj"/> </typeparam>
- /// <returns> The <see cref="Task"/>. </returns>
+ /// <typeparam name="T"> Type of <see cref="obj" /> </typeparam>
+ /// <returns> The <see cref="Task" />. </returns>
public async Task PatchAsync(string data, TimeSpan? timeout = null)
{
- var c = this.GetClient(timeout);
+ var c = GetClient(timeout);
await this.Silent().SendAsync(c, data, new HttpMethod("PATCH")).ConfigureAwait(false);
}
/// <summary>
- /// Sets or overwrites data at given location.
- /// </summary>
+ /// Sets or overwrites data at given location.
+ /// </summary>
/// <param name="obj"> The object. </param>
/// <param name="timeout"> Optional timeout value. </param>
- /// <typeparam name="T"> Type of <see cref="obj"/> </typeparam>
- /// <returns> The <see cref="Task"/>. </returns>
+ /// <typeparam name="T"> Type of <see cref="obj" /> </typeparam>
+ /// <returns> The <see cref="Task" />. </returns>
public async Task PutAsync(string data, TimeSpan? timeout = null)
{
- var c = this.GetClient(timeout);
+ var c = GetClient(timeout);
await this.Silent().SendAsync(c, data, HttpMethod.Put).ConfigureAwait(false);
}
/// <summary>
- /// Deletes data from given location.
+ /// Deletes data from given location.
/// </summary>
/// <param name="timeout"> Optional timeout value. </param>
- /// <returns> The <see cref="Task"/>. </returns>
+ /// <returns> The <see cref="Task" />. </returns>
public async Task DeleteAsync(TimeSpan? timeout = null)
{
- var c = this.GetClient(timeout);
+ var c = GetClient(timeout);
var url = string.Empty;
var responseData = string.Empty;
var statusCode = HttpStatusCode.OK;
try
{
- url = await this.BuildUrlAsync().ConfigureAwait(false);
+ url = await BuildUrlAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -245,49 +247,31 @@ namespace Firebase.Database.Query
}
/// <summary>
- /// Disposes this instance.
- /// </summary>
- public void Dispose()
- {
- this.client?.Dispose();
- }
-
- /// <summary>
- /// Build the url segment of this child.
+ /// Build the url segment of this child.
/// </summary>
/// <param name="child"> The child of this query. </param>
- /// <returns> The <see cref="string"/>. </returns>
+ /// <returns> The <see cref="string" />. </returns>
protected abstract string BuildUrlSegment(FirebaseQuery child);
private string BuildUrl(FirebaseQuery child)
{
- var url = this.BuildUrlSegment(child);
+ var url = BuildUrlSegment(child);
- if (this.Parent != null)
- {
- url = this.Parent.BuildUrl(this) + url;
- }
+ if (Parent != null) url = Parent.BuildUrl(this) + url;
return url;
}
private HttpClient GetClient(TimeSpan? timeout = null)
{
- if (this.client == null)
- {
- this.client = new HttpClient();
- }
+ if (client == null) client = new HttpClient();
if (!timeout.HasValue)
- {
- this.client.Timeout = DEFAULT_HTTP_CLIENT_TIMEOUT;
- }
+ client.Timeout = DEFAULT_HTTP_CLIENT_TIMEOUT;
else
- {
- this.client.Timeout = timeout.Value;
- }
+ client.Timeout = timeout.Value;
- return this.client;
+ return client;
}
private async Task<string> SendAsync(HttpClient client, string data, HttpMethod method)
@@ -299,7 +283,7 @@ namespace Firebase.Database.Query
try
{
- url = await this.BuildUrlAsync().ConfigureAwait(false);
+ url = await BuildUrlAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
@@ -327,4 +311,4 @@ namespace Firebase.Database.Query
}
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/IFirebaseQuery.cs b/FireBase/Query/IFirebaseQuery.cs
index 2e8c671..0da4b15 100644
--- a/FireBase/Query/IFirebaseQuery.cs
+++ b/FireBase/Query/IFirebaseQuery.cs
@@ -1,43 +1,40 @@
-namespace Firebase.Database.Query
-{
- using System;
- using System.Collections.Generic;
- using System.Threading.Tasks;
-
- using Firebase.Database.Streaming;
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using Firebase.Database.Streaming;
+namespace Firebase.Database.Query
+{
/// <summary>
- /// The FirebaseQuery interface.
+ /// The FirebaseQuery interface.
/// </summary>
public interface IFirebaseQuery
{
/// <summary>
- /// Gets the owning client of this query.
+ /// Gets the owning client of this query.
/// </summary>
- FirebaseClient Client
- {
- get;
- }
+ FirebaseClient Client { get; }
/// <summary>
- /// Retrieves items which exist on the location specified by this query instance.
+ /// Retrieves items which exist on the location specified by this query instance.
/// </summary>
/// <param name="timeout"> Optional timeout value. </param>
/// <typeparam name="T"> Type of the items. </typeparam>
- /// <returns> Collection of <see cref="FirebaseObject{T}"/>. </returns>
+ /// <returns> Collection of <see cref="FirebaseObject{T}" />. </returns>
Task<IReadOnlyCollection<FirebaseObject<T>>> OnceAsync<T>(TimeSpan? timeout = null);
/// <summary>
- /// Returns current location as an observable which allows to real-time listening to events from the firebase server.
+ /// Returns current location as an observable which allows to real-time listening to events from the firebase server.
/// </summary>
/// <typeparam name="T"> Type of the items. </typeparam>
- /// <returns> Cold observable of <see cref="FirebaseEvent{T}"/>. </returns>
- IObservable<FirebaseEvent<T>> AsObservable<T>(EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler, string elementRoot = "");
+ /// <returns> Cold observable of <see cref="FirebaseEvent{T}" />. </returns>
+ IObservable<FirebaseEvent<T>> AsObservable<T>(
+ EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler, string elementRoot = "");
/// <summary>
- /// Builds the actual url of this query.
+ /// Builds the actual url of this query.
/// </summary>
- /// <returns> The <see cref="string"/>. </returns>
+ /// <returns> The <see cref="string" />. </returns>
Task<string> BuildUrlAsync();
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/OrderQuery.cs b/FireBase/Query/OrderQuery.cs
index 46ebd2c..302d1a3 100644
--- a/FireBase/Query/OrderQuery.cs
+++ b/FireBase/Query/OrderQuery.cs
@@ -1,16 +1,16 @@
+using System;
+
namespace Firebase.Database.Query
{
- using System;
-
/// <summary>
- /// Represents a firebase ordering query, e.g. "?OrderBy=Foo".
+ /// Represents a firebase ordering query, e.g. "?OrderBy=Foo".
/// </summary>
public class OrderQuery : ParameterQuery
{
private readonly Func<string> propertyNameFactory;
/// <summary>
- /// Initializes a new instance of the <see cref="OrderQuery"/> class.
+ /// Initializes a new instance of the <see cref="OrderQuery" /> class.
/// </summary>
/// <param name="parent"> The query parent. </param>
/// <param name="propertyNameFactory"> The property name. </param>
@@ -22,13 +22,13 @@ namespace Firebase.Database.Query
}
/// <summary>
- /// The build url parameter.
+ /// The build url parameter.
/// </summary>
/// <param name="child"> The child. </param>
- /// <returns> The <see cref="string"/>. </returns>
+ /// <returns> The <see cref="string" />. </returns>
protected override string BuildUrlParameter(FirebaseQuery child)
{
- return $"\"{this.propertyNameFactory()}\"";
+ return $"\"{propertyNameFactory()}\"";
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/ParameterQuery.cs b/FireBase/Query/ParameterQuery.cs
index e3d9717..572224c 100644
--- a/FireBase/Query/ParameterQuery.cs
+++ b/FireBase/Query/ParameterQuery.cs
@@ -1,9 +1,9 @@
+using System;
+
namespace Firebase.Database.Query
{
- using System;
-
/// <summary>
- /// Represents a parameter in firebase query, e.g. "?data=foo".
+ /// Represents a parameter in firebase query, e.g. "?data=foo".
/// </summary>
public abstract class ParameterQuery : FirebaseQuery
{
@@ -11,7 +11,7 @@ namespace Firebase.Database.Query
private readonly string separator;
/// <summary>
- /// Initializes a new instance of the <see cref="ParameterQuery"/> class.
+ /// Initializes a new instance of the <see cref="ParameterQuery" /> class.
/// </summary>
/// <param name="parent"> The parent of this query. </param>
/// <param name="parameterFactory"> The parameter. </param>
@@ -20,24 +20,24 @@ namespace Firebase.Database.Query
: base(parent, client)
{
this.parameterFactory = parameterFactory;
- this.separator = (this.Parent is ChildQuery) ? "?" : "&";
+ separator = Parent is ChildQuery ? "?" : "&";
}
/// <summary>
- /// Build the url segment represented by this query.
- /// </summary>
+ /// Build the url segment represented by this query.
+ /// </summary>
/// <param name="child"> The child. </param>
- /// <returns> The <see cref="string"/>. </returns>
+ /// <returns> The <see cref="string" />. </returns>
protected override string BuildUrlSegment(FirebaseQuery child)
{
- return $"{this.separator}{this.parameterFactory()}={this.BuildUrlParameter(child)}";
+ return $"{separator}{parameterFactory()}={BuildUrlParameter(child)}";
}
/// <summary>
- /// The build url parameter.
+ /// The build url parameter.
/// </summary>
/// <param name="child"> The child. </param>
- /// <returns> The <see cref="string"/>. </returns>
+ /// <returns> The <see cref="string" />. </returns>
protected abstract string BuildUrlParameter(FirebaseQuery child);
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/QueryExtensions.cs b/FireBase/Query/QueryExtensions.cs
index 77db644..df2edfc 100644
--- a/FireBase/Query/QueryExtensions.cs
+++ b/FireBase/Query/QueryExtensions.cs
@@ -6,158 +6,163 @@ using Newtonsoft.Json;
namespace Firebase.Database.Query
{
/// <summary>
- /// Query extensions providing linq like syntax for firebase server methods.
+ /// Query extensions providing linq like syntax for firebase server methods.
/// </summary>
public static class QueryExtensions
{
/// <summary>
- /// Adds an auth parameter to the query.
+ /// Adds an auth parameter to the query.
/// </summary>
/// <param name="node"> The child. </param>
/// <param name="token"> The auth token. </param>
- /// <returns> The <see cref="AuthQuery"/>. </returns>
+ /// <returns> The <see cref="AuthQuery" />. </returns>
internal static AuthQuery WithAuth(this FirebaseQuery node, string token)
{
return node.WithAuth(() => token);
}
/// <summary>
- /// Appends print=silent to save bandwidth.
+ /// Appends print=silent to save bandwidth.
/// </summary>
/// <param name="node"> The child. </param>
- /// <returns> The <see cref="SilentQuery"/>. </returns>
+ /// <returns> The <see cref="SilentQuery" />. </returns>
internal static SilentQuery Silent(this FirebaseQuery node)
{
return new SilentQuery(node, node.Client);
}
/// <summary>
- /// References a sub child of the existing node.
+ /// References a sub child of the existing node.
/// </summary>
/// <param name="node"> The child. </param>
/// <param name="path"> The path of sub child. </param>
- /// <returns> The <see cref="ChildQuery"/>. </returns>
+ /// <returns> The <see cref="ChildQuery" />. </returns>
public static ChildQuery Child(this ChildQuery node, string path)
{
return node.Child(() => path);
}
/// <summary>
- /// Order data by given <see cref="propertyName"/>. Note that this is used mainly for following filtering queries and due to firebase implementation
- /// the data may actually not be ordered.
+ /// Order data by given <see cref="propertyName" />. Note that this is used mainly for following filtering queries and
+ /// due to firebase implementation
+ /// the data may actually not be ordered.
/// </summary>
/// <param name="child"> The child. </param>
/// <param name="propertyName"> The property name. </param>
- /// <returns> The <see cref="OrderQuery"/>. </returns>
+ /// <returns> The <see cref="OrderQuery" />. </returns>
public static OrderQuery OrderBy(this ChildQuery child, string propertyName)
{
return child.OrderBy(() => propertyName);
}
/// <summary>
- /// Instructs firebase to send data greater or equal to the <see cref="value"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data greater or equal to the <see cref="value" />. This must be preceded by an OrderBy
+ /// query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="value"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery StartAt(this ParameterQuery child, string value)
{
return child.StartAt(() => value);
}
/// <summary>
- /// Instructs firebase to send data lower or equal to the <see cref="value"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data lower or equal to the <see cref="value" />. This must be preceded by an OrderBy
+ /// query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="value"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EndAt(this ParameterQuery child, string value)
{
return child.EndAt(() => value);
}
/// <summary>
- /// Instructs firebase to send data equal to the <see cref="value"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data equal to the <see cref="value" />. This must be preceded by an OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="value"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EqualTo(this ParameterQuery child, string value)
{
return child.EqualTo(() => value);
}
/// <summary>
- /// Instructs firebase to send data greater or equal to the <see cref="value"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data greater or equal to the <see cref="value" />. This must be preceded by an OrderBy
+ /// query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="value"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery StartAt(this ParameterQuery child, double value)
{
return child.StartAt(() => value);
}
/// <summary>
- /// Instructs firebase to send data lower or equal to the <see cref="value"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data lower or equal to the <see cref="value" />. This must be preceded by an OrderBy
+ /// query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="value"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EndAt(this ParameterQuery child, double value)
{
return child.EndAt(() => value);
}
/// <summary>
- /// Instructs firebase to send data equal to the <see cref="value"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data equal to the <see cref="value" />. This must be preceded by an OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="value"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EqualTo(this ParameterQuery child, double value)
{
return child.EqualTo(() => value);
}
-
+
/// <summary>
- /// Instructs firebase to send data equal to the <see cref="value"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data equal to the <see cref="value" />. This must be preceded by an OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="value"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EqualTo(this ParameterQuery child, bool value)
{
return child.EqualTo(() => value);
- }
+ }
/// <summary>
- /// Instructs firebase to send data equal to null. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data equal to null. This must be preceded by an OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EqualTo(this ParameterQuery child)
{
return child.EqualTo(() => null);
- }
+ }
/// <summary>
- /// Limits the result to first <see cref="count"/> items.
+ /// Limits the result to first <see cref="count" /> items.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="count"> Number of elements. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery LimitToFirst(this ParameterQuery child, int count)
{
return child.LimitToFirst(() => count);
}
/// <summary>
- /// Limits the result to last <see cref="count"/> items.
+ /// Limits the result to last <see cref="count" /> items.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="count"> Number of elements. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery LimitToLast(this ParameterQuery child, int count)
{
return child.LimitToLast(() => count);
@@ -173,15 +178,19 @@ namespace Firebase.Database.Query
return query.PatchAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings));
}
- public static async Task<FirebaseObject<T>> PostAsync<T>(this FirebaseQuery query, T obj, bool generateKeyOffline = true)
+ public static async Task<FirebaseObject<T>> PostAsync<T>(this FirebaseQuery query, T obj,
+ bool generateKeyOffline = true)
{
- var result = await query.PostAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings), generateKeyOffline);
+ var result =
+ await query.PostAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings),
+ generateKeyOffline);
return new FirebaseObject<T>(result.Key, obj);
}
/// <summary>
- /// Fan out given item to multiple locations at once. See https://firebase.googleblog.com/2015/10/client-side-fan-out-for-data-consistency_73.html for details.
+ /// Fan out given item to multiple locations at once. See
+ /// https://firebase.googleblog.com/2015/10/client-side-fan-out-for-data-consistency_73.html for details.
/// </summary>
/// <typeparam name="T"> Type of object to fan out. </typeparam>
/// <param name="query"> Current node. </param>
@@ -189,19 +198,13 @@ namespace Firebase.Database.Query
/// <param name="relativePaths"> Locations where to store the item. </param>
public static async Task FanOut<T>(this ChildQuery child, T item, params string[] relativePaths)
{
- if (relativePaths == null)
- {
- throw new ArgumentNullException(nameof(relativePaths));
- }
+ if (relativePaths == null) throw new ArgumentNullException(nameof(relativePaths));
var fanoutObject = new Dictionary<string, T>(relativePaths.Length);
- foreach (var path in relativePaths)
- {
- fanoutObject.Add(path, item);
- }
+ foreach (var path in relativePaths) fanoutObject.Add(path, item);
await child.PatchAsync(fanoutObject);
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/QueryFactoryExtensions.cs b/FireBase/Query/QueryFactoryExtensions.cs
index b36e74a..71dae5c 100644
--- a/FireBase/Query/QueryFactoryExtensions.cs
+++ b/FireBase/Query/QueryFactoryExtensions.cs
@@ -1,176 +1,187 @@
+using System;
+
namespace Firebase.Database.Query
{
- using System;
-
/// <summary>
- /// Query extensions providing linq like syntax for firebase server methods.
+ /// Query extensions providing linq like syntax for firebase server methods.
/// </summary>
public static class QueryFactoryExtensions
{
/// <summary>
- /// Adds an auth parameter to the query.
+ /// Adds an auth parameter to the query.
/// </summary>
/// <param name="node"> The child. </param>
/// <param name="tokenFactory"> The auth token. </param>
- /// <returns> The <see cref="AuthQuery"/>. </returns>
+ /// <returns> The <see cref="AuthQuery" />. </returns>
internal static AuthQuery WithAuth(this FirebaseQuery node, Func<string> tokenFactory)
{
return new AuthQuery(node, tokenFactory, node.Client);
}
/// <summary>
- /// References a sub child of the existing node.
+ /// References a sub child of the existing node.
/// </summary>
/// <param name="node"> The child. </param>
/// <param name="pathFactory"> The path of sub child. </param>
- /// <returns> The <see cref="ChildQuery"/>. </returns>
+ /// <returns> The <see cref="ChildQuery" />. </returns>
public static ChildQuery Child(this ChildQuery node, Func<string> pathFactory)
{
return new ChildQuery(node, pathFactory, node.Client);
}
/// <summary>
- /// Order data by given <see cref="propertyNameFactory"/>. Note that this is used mainly for following filtering queries and due to firebase implementation
- /// the data may actually not be ordered.
+ /// Order data by given <see cref="propertyNameFactory" />. Note that this is used mainly for following filtering
+ /// queries and due to firebase implementation
+ /// the data may actually not be ordered.
/// </summary>
/// <param name="child"> The child. </param>
/// <param name="propertyNameFactory"> The property name. </param>
- /// <returns> The <see cref="OrderQuery"/>. </returns>
+ /// <returns> The <see cref="OrderQuery" />. </returns>
public static OrderQuery OrderBy(this ChildQuery child, Func<string> propertyNameFactory)
{
return new OrderQuery(child, propertyNameFactory, child.Client);
}
/// <summary>
- /// Order data by $key. Note that this is used mainly for following filtering queries and due to firebase implementation
- /// the data may actually not be ordered.
+ /// Order data by $key. Note that this is used mainly for following filtering queries and due to firebase
+ /// implementation
+ /// the data may actually not be ordered.
/// </summary>
/// <param name="child"> The child. </param>
- /// <returns> The <see cref="OrderQuery"/>. </returns>
+ /// <returns> The <see cref="OrderQuery" />. </returns>
public static OrderQuery OrderByKey(this ChildQuery child)
{
return child.OrderBy("$key");
}
/// <summary>
- /// Order data by $value. Note that this is used mainly for following filtering queries and due to firebase implementation
- /// the data may actually not be ordered.
+ /// Order data by $value. Note that this is used mainly for following filtering queries and due to firebase
+ /// implementation
+ /// the data may actually not be ordered.
/// </summary>
/// <param name="child"> The child. </param>
- /// <returns> The <see cref="OrderQuery"/>. </returns>
+ /// <returns> The <see cref="OrderQuery" />. </returns>
public static OrderQuery OrderByValue(this ChildQuery child)
{
return child.OrderBy("$value");
}
/// <summary>
- /// Order data by $priority. Note that this is used mainly for following filtering queries and due to firebase implementation
- /// the data may actually not be ordered.
+ /// Order data by $priority. Note that this is used mainly for following filtering queries and due to firebase
+ /// implementation
+ /// the data may actually not be ordered.
/// </summary>
/// <param name="child"> The child. </param>
- /// <returns> The <see cref="OrderQuery"/>. </returns>
+ /// <returns> The <see cref="OrderQuery" />. </returns>
public static OrderQuery OrderByPriority(this ChildQuery child)
{
return child.OrderBy("$priority");
}
/// <summary>
- /// Instructs firebase to send data greater or equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data greater or equal to the <see cref="valueFactory" />. This must be preceded by an
+ /// OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="valueFactory"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery StartAt(this ParameterQuery child, Func<string> valueFactory)
{
return new FilterQuery(child, () => "startAt", valueFactory, child.Client);
}
/// <summary>
- /// Instructs firebase to send data lower or equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data lower or equal to the <see cref="valueFactory" />. This must be preceded by an
+ /// OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="valueFactory"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EndAt(this ParameterQuery child, Func<string> valueFactory)
{
return new FilterQuery(child, () => "endAt", valueFactory, child.Client);
}
/// <summary>
- /// Instructs firebase to send data equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data equal to the <see cref="valueFactory" />. This must be preceded by an OrderBy
+ /// query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="valueFactory"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EqualTo(this ParameterQuery child, Func<string> valueFactory)
{
return new FilterQuery(child, () => "equalTo", valueFactory, child.Client);
}
/// <summary>
- /// Instructs firebase to send data greater or equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data greater or equal to the <see cref="valueFactory" />. This must be preceded by an
+ /// OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="valueFactory"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery StartAt(this ParameterQuery child, Func<double> valueFactory)
{
return new FilterQuery(child, () => "startAt", valueFactory, child.Client);
}
/// <summary>
- /// Instructs firebase to send data lower or equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data lower or equal to the <see cref="valueFactory" />. This must be preceded by an
+ /// OrderBy query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="valueFactory"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EndAt(this ParameterQuery child, Func<double> valueFactory)
{
return new FilterQuery(child, () => "endAt", valueFactory, child.Client);
}
/// <summary>
- /// Instructs firebase to send data equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data equal to the <see cref="valueFactory" />. This must be preceded by an OrderBy
+ /// query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="valueFactory"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EqualTo(this ParameterQuery child, Func<double> valueFactory)
{
return new FilterQuery(child, () => "equalTo", valueFactory, child.Client);
}
-
+
/// <summary>
- /// Instructs firebase to send data equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query.
+ /// Instructs firebase to send data equal to the <see cref="valueFactory" />. This must be preceded by an OrderBy
+ /// query.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="valueFactory"> Value to start at. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery EqualTo(this ParameterQuery child, Func<bool> valueFactory)
{
return new FilterQuery(child, () => "equalTo", valueFactory, child.Client);
- }
+ }
/// <summary>
- /// Limits the result to first <see cref="countFactory"/> items.
+ /// Limits the result to first <see cref="countFactory" /> items.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="countFactory"> Number of elements. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery LimitToFirst(this ParameterQuery child, Func<int> countFactory)
{
return new FilterQuery(child, () => "limitToFirst", () => countFactory(), child.Client);
}
/// <summary>
- /// Limits the result to last <see cref="countFactory"/> items.
+ /// Limits the result to last <see cref="countFactory" /> items.
/// </summary>
/// <param name="child"> Current node. </param>
/// <param name="countFactory"> Number of elements. </param>
- /// <returns> The <see cref="FilterQuery"/>. </returns>
+ /// <returns> The <see cref="FilterQuery" />. </returns>
public static FilterQuery LimitToLast(this ParameterQuery child, Func<int> countFactory)
{
return new FilterQuery(child, () => "limitToLast", () => countFactory(), child.Client);
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Query/SilentQuery.cs b/FireBase/Query/SilentQuery.cs
index 15584f6..d09d38b 100644
--- a/FireBase/Query/SilentQuery.cs
+++ b/FireBase/Query/SilentQuery.cs
@@ -1,11 +1,11 @@
namespace Firebase.Database.Query
{
/// <summary>
- /// Appends print=silent to the url.
+ /// Appends print=silent to the url.
/// </summary>
public class SilentQuery : ParameterQuery
{
- public SilentQuery(FirebaseQuery parent, FirebaseClient client)
+ public SilentQuery(FirebaseQuery parent, FirebaseClient client)
: base(parent, () => "print", client)
{
}
@@ -15,4 +15,4 @@
return "silent";
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Streaming/FirebaseCache.cs b/FireBase/Streaming/FirebaseCache.cs
index ba7990b..66241e0 100644
--- a/FireBase/Streaming/FirebaseCache.cs
+++ b/FireBase/Streaming/FirebaseCache.cs
@@ -1,51 +1,50 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using Firebase.Database.Http;
+using Newtonsoft.Json;
+
namespace Firebase.Database.Streaming
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
-
- using Firebase.Database.Http;
-
- using Newtonsoft.Json;
-
/// <summary>
- /// The firebase cache.
+ /// The firebase cache.
/// </summary>
/// <typeparam name="T"> Type of top-level entities in the cache. </typeparam>
public class FirebaseCache<T> : IEnumerable<FirebaseObject<T>>
{
private readonly IDictionary<string, T> dictionary;
private readonly bool isDictionaryType;
- private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings()
+
+ private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
};
/// <summary>
- /// Initializes a new instance of the <see cref="FirebaseCache{T}"/> class.
+ /// Initializes a new instance of the <see cref="FirebaseCache{T}" /> class.
/// </summary>
- public FirebaseCache()
+ public FirebaseCache()
: this(new Dictionary<string, T>())
{
}
/// <summary>
- /// Initializes a new instance of the <see cref="FirebaseCache{T}"/> class and populates it with existing data.
+ /// Initializes a new instance of the <see cref="FirebaseCache{T}" /> class and populates it with existing data.
/// </summary>
/// <param name="existingItems"> The existing items. </param>
public FirebaseCache(IDictionary<string, T> existingItems)
{
- this.dictionary = existingItems;
- this.isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());
+ dictionary = existingItems;
+ isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());
}
/// <summary>
- /// The push data.
+ /// The push data.
/// </summary>
- /// <param name="path"> The path of incoming data, separated by slash. </param>
- /// <param name="data"> The data in json format as returned by firebase. </param>
+ /// <param name="path"> The path of incoming data, separated by slash. </param>
+ /// <param name="data"> The data in json format as returned by firebase. </param>
/// <returns> Collection of top-level entities which were affected by the push. </returns>
public IEnumerable<FirebaseObject<T>> PushData(string path, string data, bool removeEmptyEntries = true)
{
@@ -53,18 +52,18 @@ namespace Firebase.Database.Streaming
Action<object> primitiveObjSetter = null;
Action objDeleter = null;
- var pathElements = path.Split(new[] { "/" }, removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
+ var pathElements = path.Split(new[] {"/"},
+ removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
// first find where we should insert the data to
foreach (var element in pathElements)
- {
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];
- primitiveObjSetter = (d) => dictionary[element] = d;
+ primitiveObjSetter = d => dictionary[element] = d;
objDeleter = () => dictionary.Remove(element);
if (dictionary.Contains(element))
@@ -73,7 +72,7 @@ namespace Firebase.Database.Streaming
}
else
{
- dictionary[element] = this.CreateInstance(valueType);
+ dictionary[element] = CreateInstance(valueType);
obj = dictionary[element];
}
}
@@ -84,24 +83,24 @@ namespace Firebase.Database.Streaming
var property = objParent
.GetType()
.GetRuntimeProperties()
- .First(p => p.Name.Equals(element, StringComparison.OrdinalIgnoreCase) || element == p.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName);
+ .First(p => p.Name.Equals(element, StringComparison.OrdinalIgnoreCase) ||
+ element == p.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName);
objDeleter = () => property.SetValue(objParent, null);
- primitiveObjSetter = (d) => property.SetValue(objParent, d);
+ primitiveObjSetter = d => property.SetValue(objParent, d);
obj = property.GetValue(obj);
if (obj == null)
{
- obj = this.CreateInstance(property.PropertyType);
+ obj = CreateInstance(property.PropertyType);
property.SetValue(objParent, obj);
}
}
- }
// if data is null (=empty string) delete it
if (string.IsNullOrWhiteSpace(data) || data == "null")
{
var key = pathElements[0];
- var target = this.dictionary[key];
+ var target = dictionary[key];
objDeleter();
@@ -110,7 +109,7 @@ namespace Firebase.Database.Streaming
}
// now insert the data
- if (obj is IDictionary && !this.isDictionaryType)
+ if (obj is IDictionary && !isDictionaryType)
{
// insert data into dictionary and return it as a collection of FirebaseObject
var dictionary = obj as IDictionary;
@@ -122,10 +121,7 @@ namespace Firebase.Database.Streaming
dictionary[item.Key] = item.Object;
// top level dictionary changed
- if (!pathElements.Any())
- {
- yield return new FirebaseObject<T>(item.Key, (T)item.Object);
- }
+ if (!pathElements.Any()) yield return new FirebaseObject<T>(item.Key, (T) item.Object);
}
// nested dictionary changed
@@ -141,52 +137,45 @@ namespace Firebase.Database.Streaming
var valueType = obj.GetType();
// firebase sends strings without double quotes
- var targetObject = valueType == typeof(string) ? data.ToString() : JsonConvert.DeserializeObject(data, valueType);
+ var targetObject = valueType == typeof(string)
+ ? data
+ : JsonConvert.DeserializeObject(data, valueType);
if ((valueType.GetTypeInfo().IsPrimitive || valueType == typeof(string)) && primitiveObjSetter != null)
- {
// handle primitive (value) types separately
primitiveObjSetter(targetObject);
- }
else
- {
- JsonConvert.PopulateObject(data, obj, this.serializerSettings);
- }
+ JsonConvert.PopulateObject(data, obj, serializerSettings);
- this.dictionary[pathElements[0]] = this.dictionary[pathElements[0]];
- yield return new FirebaseObject<T>(pathElements[0], this.dictionary[pathElements[0]]);
+ dictionary[pathElements[0]] = dictionary[pathElements[0]];
+ yield return new FirebaseObject<T>(pathElements[0], dictionary[pathElements[0]]);
}
}
public bool Contains(string key)
{
- return this.dictionary.Keys.Contains(key);
+ return dictionary.Keys.Contains(key);
}
private object CreateInstance(Type type)
{
if (type == typeof(string))
- {
return string.Empty;
- }
- else
- {
- return Activator.CreateInstance(type);
- }
+ return Activator.CreateInstance(type);
}
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator()
{
- return this.GetEnumerator();
+ return GetEnumerator();
}
public IEnumerator<FirebaseObject<T>> GetEnumerator()
{
- return this.dictionary.Select(p => new FirebaseObject<T>(p.Key, p.Value)).GetEnumerator();
+ return dictionary.Select(p => new FirebaseObject<T>(p.Key, p.Value)).GetEnumerator();
}
#endregion
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Streaming/FirebaseEvent.cs b/FireBase/Streaming/FirebaseEvent.cs
index c2338ca..1761a72 100644
--- a/FireBase/Streaming/FirebaseEvent.cs
+++ b/FireBase/Streaming/FirebaseEvent.cs
@@ -1,13 +1,13 @@
namespace Firebase.Database.Streaming
{
/// <summary>
- /// Firebase event which hold <see cref="EventType"/> and the object affected by the event.
+ /// Firebase event which hold <see cref="EventType" /> and the object affected by the event.
/// </summary>
/// <typeparam name="T"> Type of object affected by the event. </typeparam>
public class FirebaseEvent<T> : FirebaseObject<T>
{
/// <summary>
- /// Initializes a new instance of the <see cref="FirebaseEvent{T}"/> class.
+ /// Initializes a new instance of the <see cref="FirebaseEvent{T}" /> class.
/// </summary>
/// <param name="key"> The key of the object. </param>
/// <param name="obj"> The object. </param>
@@ -15,26 +15,23 @@ namespace Firebase.Database.Streaming
public FirebaseEvent(string key, T obj, FirebaseEventType eventType, FirebaseEventSource eventSource)
: base(key, obj)
{
- this.EventType = eventType;
- this.EventSource = eventSource;
+ EventType = eventType;
+ EventSource = eventSource;
}
/// <summary>
- /// Gets the source of the event.
+ /// Gets the source of the event.
/// </summary>
- public FirebaseEventSource EventSource
- {
- get;
- }
+ public FirebaseEventSource EventSource { get; }
/// <summary>
- /// Gets the event type.
+ /// Gets the event type.
/// </summary>
- public FirebaseEventType EventType
+ public FirebaseEventType EventType { get; }
+
+ public static FirebaseEvent<T> Empty(FirebaseEventSource source)
{
- get;
+ return new FirebaseEvent<T>(string.Empty, default(T), FirebaseEventType.InsertOrUpdate, source);
}
-
- public static FirebaseEvent<T> Empty(FirebaseEventSource source) => new FirebaseEvent<T>(string.Empty, default(T), FirebaseEventType.InsertOrUpdate, source);
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Streaming/FirebaseEventSource.cs b/FireBase/Streaming/FirebaseEventSource.cs
index 98df977..b1385ca 100644
--- a/FireBase/Streaming/FirebaseEventSource.cs
+++ b/FireBase/Streaming/FirebaseEventSource.cs
@@ -1,38 +1,38 @@
namespace Firebase.Database.Streaming
{
/// <summary>
- /// Specifies the origin of given <see cref="FirebaseEvent{T}"/>
+ /// Specifies the origin of given <see cref="FirebaseEvent{T}" />
/// </summary>
public enum FirebaseEventSource
{
/// <summary>
- /// Event comes from an offline source.
+ /// Event comes from an offline source.
/// </summary>
Offline,
/// <summary>
- /// Event comes from online source fetched during initial pull (valid only for RealtimeDatabase).
+ /// Event comes from online source fetched during initial pull (valid only for RealtimeDatabase).
/// </summary>
OnlineInitial,
/// <summary>
- /// Event comes from online source received thru active stream.
+ /// Event comes from online source received thru active stream.
/// </summary>
OnlineStream,
/// <summary>
- /// Event comes from online source being fetched manually.
+ /// Event comes from online source being fetched manually.
/// </summary>
OnlinePull,
/// <summary>
- /// Event raised after successful online push (valid only for RealtimeDatabase which isn't streaming).
+ /// Event raised after successful online push (valid only for RealtimeDatabase which isn't streaming).
/// </summary>
OnlinePush,
/// <summary>
- /// Event comes from an online source.
+ /// Event comes from an online source.
/// </summary>
Online = OnlineInitial | OnlinePull | OnlinePush | OnlineStream
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Streaming/FirebaseEventType.cs b/FireBase/Streaming/FirebaseEventType.cs
index 5fb21ef..7606331 100644
--- a/FireBase/Streaming/FirebaseEventType.cs
+++ b/FireBase/Streaming/FirebaseEventType.cs
@@ -1,18 +1,18 @@
namespace Firebase.Database.Streaming
{
/// <summary>
- /// The type of event.
+ /// The type of event.
/// </summary>
public enum FirebaseEventType
{
/// <summary>
- /// Item was inserted or updated.
+ /// Item was inserted or updated.
/// </summary>
InsertOrUpdate,
/// <summary>
- /// Item was deleted.
+ /// Item was deleted.
/// </summary>
Delete
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Streaming/FirebaseServerEventType.cs b/FireBase/Streaming/FirebaseServerEventType.cs
index 1f10bc8..79c816d 100644
--- a/FireBase/Streaming/FirebaseServerEventType.cs
+++ b/FireBase/Streaming/FirebaseServerEventType.cs
@@ -12,4 +12,4 @@ namespace Firebase.Database.Streaming
AuthRevoked
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Streaming/FirebaseSubscription.cs b/FireBase/Streaming/FirebaseSubscription.cs
index 4b5e643..fb0f403 100644
--- a/FireBase/Streaming/FirebaseSubscription.cs
+++ b/FireBase/Streaming/FirebaseSubscription.cs
@@ -1,32 +1,28 @@
+using System;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading;
+using System.Threading.Tasks;
+using Firebase.Database.Query;
+using Newtonsoft.Json.Linq;
+
namespace Firebase.Database.Streaming
{
- using System;
- using System.Diagnostics;
- using System.Linq;
- using System.Net.Http;
- using System.Net.Http.Headers;
- using System.Threading;
- using System.Threading.Tasks;
-
- using Firebase.Database.Query;
-
- using Newtonsoft.Json.Linq;
- using System.Net;
-
/// <summary>
- /// The firebase subscription.
+ /// The firebase subscription.
/// </summary>
/// <typeparam name="T"> Type of object to be streaming back to the called. </typeparam>
internal class FirebaseSubscription<T> : IDisposable
{
+ private static readonly HttpClient http;
+ private readonly FirebaseCache<T> cache;
private readonly CancellationTokenSource cancel;
+ private readonly FirebaseClient client;
+ private readonly string elementRoot;
private readonly IObserver<FirebaseEvent<T>> observer;
private readonly IFirebaseQuery query;
- private readonly FirebaseCache<T> cache;
- private readonly string elementRoot;
- private readonly FirebaseClient client;
-
- private static HttpClient http;
static FirebaseSubscription()
{
@@ -45,31 +41,32 @@ namespace Firebase.Database.Streaming
}
/// <summary>
- /// Initializes a new instance of the <see cref="FirebaseSubscription{T}"/> class.
+ /// Initializes a new instance of the <see cref="FirebaseSubscription{T}" /> class.
/// </summary>
/// <param name="observer"> The observer. </param>
/// <param name="query"> The query. </param>
/// <param name="cache"> The cache. </param>
- public FirebaseSubscription(IObserver<FirebaseEvent<T>> observer, IFirebaseQuery query, string elementRoot, FirebaseCache<T> cache)
+ public FirebaseSubscription(IObserver<FirebaseEvent<T>> observer, IFirebaseQuery query, string elementRoot,
+ FirebaseCache<T> cache)
{
this.observer = observer;
this.query = query;
this.elementRoot = elementRoot;
- this.cancel = new CancellationTokenSource();
+ cancel = new CancellationTokenSource();
this.cache = cache;
- this.client = query.Client;
+ client = query.Client;
}
- public event EventHandler<ExceptionEventArgs<FirebaseException>> ExceptionThrown;
-
public void Dispose()
{
- this.cancel.Cancel();
+ cancel.Cancel();
}
+ public event EventHandler<ExceptionEventArgs<FirebaseException>> ExceptionThrown;
+
public IDisposable Run()
{
- Task.Run(() => this.ReceiveThread());
+ Task.Run(() => ReceiveThread());
return this;
}
@@ -84,15 +81,17 @@ namespace Firebase.Database.Streaming
try
{
- this.cancel.Token.ThrowIfCancellationRequested();
+ cancel.Token.ThrowIfCancellationRequested();
// initialize network connection
- url = await this.query.BuildUrlAsync().ConfigureAwait(false);
+ url = await query.BuildUrlAsync().ConfigureAwait(false);
var request = new HttpRequestMessage(HttpMethod.Get, url);
var serverEvent = FirebaseServerEventType.KeepAlive;
- var client = this.GetHttpClient();
- var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, this.cancel.Token).ConfigureAwait(false);
+ var client = GetHttpClient();
+ var response = await client
+ .SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancel.Token)
+ .ConfigureAwait(false);
statusCode = response.StatusCode;
response.EnsureSuccessStatusCode();
@@ -102,32 +101,28 @@ namespace Firebase.Database.Streaming
{
while (true)
{
- this.cancel.Token.ThrowIfCancellationRequested();
+ cancel.Token.ThrowIfCancellationRequested();
line = reader.ReadLine()?.Trim();
- if (string.IsNullOrWhiteSpace(line))
- {
- continue;
- }
+ if (string.IsNullOrWhiteSpace(line)) continue;
+
+ var tuple = line.Split(new[] {':'}, 2, StringSplitOptions.RemoveEmptyEntries)
+ .Select(s => s.Trim()).ToArray();
- var tuple = line.Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray();
-
switch (tuple[0].ToLower())
{
case "event":
- serverEvent = this.ParseServerEvent(serverEvent, tuple[1]);
+ serverEvent = ParseServerEvent(serverEvent, tuple[1]);
break;
case "data":
- this.ProcessServerData(url, serverEvent, tuple[1]);
+ ProcessServerData(url, serverEvent, tuple[1]);
break;
}
if (serverEvent == FirebaseServerEventType.AuthRevoked)
- {
// auth token no longer valid, reconnect
break;
- }
}
}
}
@@ -137,13 +132,15 @@ namespace Firebase.Database.Streaming
}
catch (Exception ex) when (statusCode != HttpStatusCode.OK)
{
- this.observer.OnError(new FirebaseException(url, string.Empty, line, statusCode, ex));
- this.Dispose();
+ observer.OnError(new FirebaseException(url, string.Empty, line, statusCode, ex));
+ Dispose();
break;
}
catch (Exception ex)
{
- this.ExceptionThrown?.Invoke(this, new ExceptionEventArgs<FirebaseException>(new FirebaseException(url, string.Empty, line, statusCode, ex)));
+ ExceptionThrown?.Invoke(this,
+ new ExceptionEventArgs<FirebaseException>(new FirebaseException(url, string.Empty, line,
+ statusCode, ex)));
await Task.Delay(2000).ConfigureAwait(false);
}
@@ -185,30 +182,29 @@ namespace Firebase.Database.Streaming
var data = result["data"].ToString();
// 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(this.elementRoot) || !this.cache.Contains(this.elementRoot))
- {
- if(path == "/" && data == string.Empty)
+ if (string.IsNullOrWhiteSpace(elementRoot) || !cache.Contains(elementRoot))
+ if (path == "/" && data == string.Empty)
{
- this.observer.OnNext(FirebaseEvent<T>.Empty(FirebaseEventSource.OnlineStream));
+ observer.OnNext(FirebaseEvent<T>.Empty(FirebaseEventSource.OnlineStream));
return;
}
- }
- var eventType = string.IsNullOrWhiteSpace(data) ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate;
+ var eventType = string.IsNullOrWhiteSpace(data)
+ ? FirebaseEventType.Delete
+ : FirebaseEventType.InsertOrUpdate;
- var items = this.cache.PushData(this.elementRoot + path, data);
+ var items = cache.PushData(elementRoot + path, data);
foreach (var i in items.ToList())
- {
- this.observer.OnNext(new FirebaseEvent<T>(i.Key, i.Object, eventType, FirebaseEventSource.OnlineStream));
- }
+ observer.OnNext(new FirebaseEvent<T>(i.Key, i.Object, eventType,
+ FirebaseEventSource.OnlineStream));
break;
case FirebaseServerEventType.KeepAlive:
break;
case FirebaseServerEventType.Cancel:
- this.observer.OnError(new FirebaseException(url, string.Empty, serverData, HttpStatusCode.Unauthorized));
- this.Dispose();
+ observer.OnError(new FirebaseException(url, string.Empty, serverData, HttpStatusCode.Unauthorized));
+ Dispose();
break;
}
}
@@ -218,4 +214,4 @@ namespace Firebase.Database.Streaming
return http;
}
}
-}
+} \ No newline at end of file
diff --git a/FireBase/Streaming/NonBlockingStreamReader.cs b/FireBase/Streaming/NonBlockingStreamReader.cs
index 2ac83fd..8228e32 100644
--- a/FireBase/Streaming/NonBlockingStreamReader.cs
+++ b/FireBase/Streaming/NonBlockingStreamReader.cs
@@ -1,45 +1,48 @@
-namespace Firebase.Database.Streaming
-{
- using System.IO;
- using System.Text;
+using System.IO;
+using System.Text;
+namespace Firebase.Database.Streaming
+{
/// <summary>
- /// When a regular <see cref="StreamReader"/> is used in a UWP app its <see cref="StreamReader.ReadLine"/> method tends to take a long
- /// time for data larger then 2 KB. This extremly simple implementation of <see cref="TextReader"/> can be used instead to boost performance
- /// in your UWP app. Use <see cref="FirebaseOptions"/> to inject an instance of this class into your <see cref="FirebaseClient"/>.
+ /// When a regular <see cref="StreamReader" /> is used in a UWP app its <see cref="StreamReader.ReadLine" /> method
+ /// tends to take a long
+ /// time for data larger then 2 KB. This extremly simple implementation of <see cref="TextReader" /> can be used
+ /// instead to boost performance
+ /// in your UWP app. Use <see cref="FirebaseOptions" /> to inject an instance of this class into your
+ /// <see cref="FirebaseClient" />.
/// </summary>
public class NonBlockingStreamReader : TextReader
{
private const int DefaultBufferSize = 16000;
-
- private readonly Stream stream;
private readonly byte[] buffer;
private readonly int bufferSize;
+ private readonly Stream stream;
+
private string cachedData;
-
- public NonBlockingStreamReader(Stream stream, int bufferSize = DefaultBufferSize)
+
+ public NonBlockingStreamReader(Stream stream, int bufferSize = DefaultBufferSize)
{
this.stream = stream;
this.bufferSize = bufferSize;
- this.buffer = new byte[bufferSize];
+ buffer = new byte[bufferSize];
- this.cachedData = string.Empty;
+ cachedData = string.Empty;
}
public override string ReadLine()
{
- var currentString = this.TryGetNewLine();
-
+ var currentString = TryGetNewLine();
+
while (currentString == null)
{
- var read = this.stream.Read(this.buffer, 0, this.bufferSize);
+ var read = stream.Read(buffer, 0, bufferSize);
var str = Encoding.UTF8.GetString(buffer, 0, read);
cachedData += str;
- currentString = this.TryGetNewLine();
+ currentString = TryGetNewLine();
}
-
+
return currentString;
}
@@ -50,11 +53,11 @@
if (newLine >= 0)
{
var r = cachedData.Substring(0, newLine + 1);
- this.cachedData = cachedData.Remove(0, r.Length);
+ cachedData = cachedData.Remove(0, r.Length);
return r.Trim();
}
return null;
}
}
-}
+} \ No newline at end of file
diff --git a/ZooBOTanica/CritCreate.cs b/ZooBOTanica/CritCreate.cs
index 3d0a6c2..e79cff4 100644
--- a/ZooBOTanica/CritCreate.cs
+++ b/ZooBOTanica/CritCreate.cs
@@ -1,56 +1,47 @@
using System;
using System.Collections.Generic;
-using System.ComponentModel;
-using System.Data;
-using System.Drawing;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
using System.Windows.Forms;
+using DSALib;
+using DSALib.Characters;
namespace ZooBOTanica
{
- using DSALib;
- using DSALib.Characters;
-
public partial class CritCreateForm : Form
{
- public DSALib.Characters.Critter critter;
+ public Critter critter;
public CritCreateForm()
{
- this.InitializeComponent();
- this.AllowDrop = true;
+ InitializeComponent();
+ AllowDrop = true;
}
public new void Load(string path)
{
- this.critter = Critter.Load(path);
+ critter = Critter.Load(path);
- this.AeEdit.Value = this.critter.Astralpunkte_Basis;
- this.AuEdit.Value = this.critter.Ausdauer_Basis;
- this.GWEdit.Value = this.critter.Gw;
- this.GsEdit.Value = this.critter.Gs;
- this.KoEdit.Value = this.critter.Ko;
- this.LeEdit.Value = this.critter.Lebenspunkte_Basis;
- this.MREdit.Value = this.critter.Mr;
- this.NameEdit.Text = this.critter.Name;
+ AeEdit.Value = critter.Astralpunkte_Basis;
+ AuEdit.Value = critter.Ausdauer_Basis;
+ GWEdit.Value = critter.Gw;
+ GsEdit.Value = critter.Gs;
+ KoEdit.Value = critter.Ko;
+ LeEdit.Value = critter.Lebenspunkte_Basis;
+ MREdit.Value = critter.Mr;
+ NameEdit.Text = critter.Name;
//this.PAEdit.Value = this.critter.Pa;
- this.RSEdit.Value = this.critter.Rs;
- this.INIEdit.Text = this.critter.Ini;
- this.MeisterkommentarEdit.Text = this.critter.Comment;
+ RSEdit.Value = critter.Rs;
+ INIEdit.Text = critter.Ini;
+ MeisterkommentarEdit.Text = critter.Comment;
- this.AttackList.Rows.Clear();
+ AttackList.Rows.Clear();
- foreach (var critterAttack in this.critter.CritterAttacks)
- {
- this.AttackList.Rows.Add(critterAttack.Name, critterAttack.At, critterAttack.Tp, critterAttack.Comment);
- }
+ foreach (var critterAttack in critter.CritterAttacks)
+ AttackList.Rows.Add(critterAttack.Name, critterAttack.At, critterAttack.Tp, critterAttack.Comment);
}
-
+
public void CritCreateForm_DragDrop(object sender, DragEventArgs e)
{
- this.Load(e.Data.GetData(DataFormats.Text).ToString());
+ Load(e.Data.GetData(DataFormats.Text).ToString());
}
public void LoadButton_Click(object sender, EventArgs e)
@@ -63,34 +54,31 @@ namespace ZooBOTanica
Filter = "*Json Dateien (*.json)|*.json"
};
- if (dig.ShowDialog() == DialogResult.OK)
- {
- this.Load(dig.FileName);
- }
+ if (dig.ShowDialog() == DialogResult.OK) Load(dig.FileName);
}
public void SaveButton_Click(object sender, EventArgs e)
{
- this.critter = new Critter();
- this.critter.Astralpunkte_Basis = (int)this.AeEdit.Value;
- this.critter.Ausdauer_Basis = (int)this.AuEdit.Value;
- this.critter.Gw = (int)this.GWEdit.Value;
- this.critter.Gs = (int)this.GsEdit.Value;
- this.critter.Ko = (int)this.KoEdit.Value;
- this.critter.Lebenspunkte_Basis = (int)this.LeEdit.Value;
- this.critter.Mr = (int)this.MREdit.Value;
- this.critter.Name = this.NameEdit.Text;
+ critter = new Critter();
+ critter.Astralpunkte_Basis = (int) AeEdit.Value;
+ critter.Ausdauer_Basis = (int) AuEdit.Value;
+ critter.Gw = (int) GWEdit.Value;
+ critter.Gs = (int) GsEdit.Value;
+ critter.Ko = (int) KoEdit.Value;
+ critter.Lebenspunkte_Basis = (int) LeEdit.Value;
+ critter.Mr = (int) MREdit.Value;
+ critter.Name = NameEdit.Text;
//this.critter.Pa = (int)this.PAEdit.Value;
- this.critter.Rs = (int)this.RSEdit.Value;
- this.critter.Ini = this.INIEdit.Text;
- this.critter.Comment = this.MeisterkommentarEdit.Text;
+ critter.Rs = (int) RSEdit.Value;
+ critter.Ini = INIEdit.Text;
+ critter.Comment = MeisterkommentarEdit.Text;
- this.critter.CritterAttacks = new List<CritterAttack>();
+ critter.CritterAttacks = new List<CritterAttack>();
- for (var index = 0; index < this.AttackList.Rows.Count -1; index++)
+ for (var index = 0; index < AttackList.Rows.Count - 1; index++)
{
- DataGridViewRow Row = this.AttackList.Rows[index];
- this.critter.CritterAttacks.Add(
+ var Row = AttackList.Rows[index];
+ critter.CritterAttacks.Add(
new CritterAttack(
(Row.Cells[0].Value ?? "").ToString(),
Convert.ToInt32(Row.Cells[1].Value ?? 0),
@@ -98,8 +86,7 @@ namespace ZooBOTanica
(Row.Cells[3].Value ?? "").ToString()));
}
- this.critter.Save();
+ critter.Save();
}
}
-}
-
+} \ No newline at end of file
diff --git a/ZooBOTanica/Program.cs b/ZooBOTanica/Program.cs
index e67b591..59c7434 100644
--- a/ZooBOTanica/Program.cs
+++ b/ZooBOTanica/Program.cs
@@ -1,22 +1,19 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
using System.Windows.Forms;
namespace ZooBOTanica
{
- static class Program
+ internal static class Program
{
/// <summary>
- /// Der Haupteinstiegspunkt für die Anwendung.
+ /// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
- static void Main()
+ private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CritCreateForm());
}
}
-}
+} \ No newline at end of file
diff --git a/ZooBOTanica/Properties/AssemblyInfo.cs b/ZooBOTanica/Properties/AssemblyInfo.cs
index c29729b..b2b516e 100644
--- a/ZooBOTanica/Properties/AssemblyInfo.cs
+++ b/ZooBOTanica/Properties/AssemblyInfo.cs
@@ -1,5 +1,4 @@
using System.Reflection;
-using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
@@ -33,4 +32,4 @@ using System.Runtime.InteropServices;
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file