From f89f308c525e9deebc6d2cf6416e27dfe1a299dc Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 19 May 2019 16:03:38 +0200 Subject: Cleanup DiscoBot Project --- FireBase/ExceptionEventArgs.cs | 4 +- FireBase/Extensions/ObservableExtensions.cs | 28 +- FireBase/Extensions/TaskExtensions.cs | 2 +- FireBase/FirebaseClient.cs | 18 +- FireBase/FirebaseException.cs | 44 ++- FireBase/FirebaseKeyGenerator.cs | 34 +-- FireBase/FirebaseObject.cs | 18 +- FireBase/FirebaseOptions.cs | 50 +--- FireBase/Http/HttpClientExtensions.cs | 23 +- FireBase/Http/PostResult.cs | 8 +- FireBase/ObservableExtensions.cs | 10 +- FireBase/Offline/ConcurrentOfflineDatabase.cs | 70 ++--- FireBase/Offline/DatabaseExtensions.cs | 77 +++-- FireBase/Offline/ISetHandler.cs | 5 +- FireBase/Offline/InitialPullStrategy.cs | 4 +- FireBase/Offline/Internals/MemberAccessVisitor.cs | 19 +- FireBase/Offline/OfflineCacheAdapter.cs | 69 ++--- FireBase/Offline/OfflineDatabase.cs | 71 +++-- FireBase/Offline/OfflineEntry.cs | 60 ++-- FireBase/Offline/RealtimeDatabase.cs | 324 +++++++++++----------- FireBase/Offline/SetHandler.cs | 9 +- FireBase/Offline/StreamingOptions.cs | 2 +- FireBase/Offline/SyncOptions.cs | 2 +- FireBase/Query/AuthQuery.cs | 7 +- FireBase/Query/ChildQuery.cs | 16 +- FireBase/Query/FilterQuery.cs | 36 +-- FireBase/Query/FirebaseQuery.cs | 82 +++--- FireBase/Query/IFirebaseQuery.cs | 13 +- FireBase/Query/OrderQuery.cs | 4 +- FireBase/Query/ParameterQuery.cs | 6 +- FireBase/Query/QueryExtensions.cs | 25 +- FireBase/Query/QueryFactoryExtensions.cs | 6 +- FireBase/Query/SilentQuery.cs | 4 +- FireBase/Streaming/FirebaseCache.cs | 58 ++-- FireBase/Streaming/FirebaseEvent.cs | 19 +- FireBase/Streaming/FirebaseEventSource.cs | 2 +- FireBase/Streaming/FirebaseEventType.cs | 2 +- FireBase/Streaming/FirebaseServerEventType.cs | 2 +- FireBase/Streaming/FirebaseSubscription.cs | 76 +++-- FireBase/Streaming/NonBlockingStreamReader.cs | 22 +- 40 files changed, 594 insertions(+), 737 deletions(-) (limited to 'FireBase') diff --git a/FireBase/ExceptionEventArgs.cs b/FireBase/ExceptionEventArgs.cs index f1c7fac..185c952 100644 --- a/FireBase/ExceptionEventArgs.cs +++ b/FireBase/ExceptionEventArgs.cs @@ -15,7 +15,7 @@ /// The exception. 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..cb41bcc 100644 --- a/FireBase/Extensions/ObservableExtensions.cs +++ b/FireBase/Extensions/ObservableExtensions.cs @@ -19,22 +19,22 @@ this IObservable source, TimeSpan dueTime, Func 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(true, item, null)) - .Catch, TException>(e => retryOnError(e) - ? Observable.Throw>(e) - : Observable.Return(new Tuple(false, default(T), e))); - }) - .Retry() - .SelectMany(t => t.Item1 - ? Observable.Return(t.Item2) - : Observable.Throw(t.Item3)); + { + return (++attempt == 1 ? source : source.DelaySubscription(dueTime)) + .Select(item => new Tuple(true, item, null)) + .Catch, TException>(e => retryOnError(e) + ? Observable.Throw>(e) + : Observable.Return(new Tuple(false, default(T), e))); + }) + .Retry() + .SelectMany(t => t.Item1 + ? Observable.Return(t.Item2) + : Observable.Throw(t.Item3)); } } -} +} \ No newline at end of file diff --git a/FireBase/Extensions/TaskExtensions.cs b/FireBase/Extensions/TaskExtensions.cs index 26bbde6..8e933b2 100644 --- a/FireBase/Extensions/TaskExtensions.cs +++ b/FireBase/Extensions/TaskExtensions.cs @@ -20,4 +20,4 @@ } } } -} +} \ No newline at end of file diff --git a/FireBase/FirebaseClient.cs b/FireBase/FirebaseClient.cs index a237c8d..8795668 100644 --- a/FireBase/FirebaseClient.cs +++ b/FireBase/FirebaseClient.cs @@ -7,9 +7,8 @@ namespace Firebase.Database using System; using System.Collections.Generic; using System.Threading.Tasks; - - using Firebase.Database.Offline; - using Firebase.Database.Query; + using Offline; + using Query; /// /// Firebase client which acts as an entry point to the online database. @@ -28,15 +27,12 @@ namespace Firebase.Database /// Offline database. 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 += "/"; } /// @@ -46,7 +42,7 @@ namespace Firebase.Database /// . public ChildQuery Child(string resourceName) { - return new ChildQuery(this, () => this.baseUrl + resourceName); + return new ChildQuery(this, () => baseUrl + resourceName); } public void Dispose() @@ -54,4 +50,4 @@ namespace Firebase.Database HttpClient?.Dispose(); } } -} +} \ No newline at end of file diff --git a/FireBase/FirebaseException.cs b/FireBase/FirebaseException.cs index e4b782b..2f8269d 100644 --- a/FireBase/FirebaseException.cs +++ b/FireBase/FirebaseException.cs @@ -8,56 +8,46 @@ 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; } /// /// Post data passed to the authentication service. /// - public string RequestData - { - get; - } + public string RequestData { get; } /// /// Original url of the request. /// - public string RequestUrl - { - get; - } + public string RequestUrl { get; } /// /// Response from the authentication service. /// - public string ResponseData - { - get; - } + public string ResponseData { get; } /// /// Status code of the response. /// - 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..70a855d 100644 --- a/FireBase/FirebaseKeyGenerator.cs +++ b/FireBase/FirebaseKeyGenerator.cs @@ -7,7 +7,7 @@ namespace Firebase.Database /// Offline key generator which mimics the official Firebase generators. /// Credit: https://github.com/bubbafat/FirebaseSharp/blob/master/src/FirebaseSharp.Portable/FireBasePushIdGenerator.cs /// - public class FirebaseKeyGenerator + public class FirebaseKeyGenerator { // Modeled after base64 web-safe chars, but ordered by ASCII. private const string PushCharsString = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; @@ -37,31 +37,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 +63,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..653d508 100644 --- a/FireBase/FirebaseObject.cs +++ b/FireBase/FirebaseObject.cs @@ -4,28 +4,22 @@ namespace Firebase.Database /// Holds the object of type along with its key. /// /// Type of the underlying object. - public class FirebaseObject + public class FirebaseObject { internal FirebaseObject(string key, T obj) { - this.Key = key; - this.Object = obj; + Key = key; + Object = obj; } /// /// Gets the key of . /// - public string Key - { - get; - } + public string Key { get; } /// /// Gets the underlying object. /// - 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..f31a047 100644 --- a/FireBase/FirebaseOptions.cs +++ b/FireBase/FirebaseOptions.cs @@ -4,73 +4,47 @@ using System.Collections.Generic; using System.IO; using System.Threading.Tasks; - - using Firebase.Database.Offline; - + using Offline; using Newtonsoft.Json; public class FirebaseOptions { public FirebaseOptions() { - this.OfflineDatabaseFactory = (t, s) => new Dictionary(); - this.SubscriptionStreamReaderFactory = s => new StreamReader(s); - this.JsonSerializerSettings = new JsonSerializerSettings(); - this.SyncPeriod = TimeSpan.FromSeconds(10); + OfflineDatabaseFactory = (t, s) => new Dictionary(); + SubscriptionStreamReaderFactory = s => new StreamReader(s); + JsonSerializerSettings = new JsonSerializerSettings(); + SyncPeriod = TimeSpan.FromSeconds(10); } /// /// Gets or sets the factory for Firebase offline database. Default is in-memory dictionary. /// - public Func> OfflineDatabaseFactory - { - get; - set; - } + public Func> OfflineDatabaseFactory { get; set; } /// /// Gets or sets the method for retrieving auth tokens. Default is null. /// - public Func> AuthTokenAsyncFactory - { - get; - set; - } + public Func> AuthTokenAsyncFactory { get; set; } /// /// Gets or sets the factory for used for reading online streams. Default is . /// - public Func SubscriptionStreamReaderFactory - { - get; - set; - } + public Func SubscriptionStreamReaderFactory { get; set; } /// /// Gets or sets the json serializer settings. /// - public JsonSerializerSettings JsonSerializerSettings - { - get; - set; - } + public JsonSerializerSettings JsonSerializerSettings { get; set; } /// /// Gets or sets the time between synchronization attempts for pulling and pushing offline entities. Default is 10 seconds. /// - public TimeSpan SyncPeriod - { - get; - set; - } + public TimeSpan SyncPeriod { get; set; } /// /// Specify if token returned by factory will be used as "auth" url parameter or "access_token". /// - 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..7f8fffe 100644 --- a/FireBase/Http/HttpClientExtensions.cs +++ b/FireBase/Http/HttpClientExtensions.cs @@ -6,7 +6,6 @@ namespace Firebase.Database.Http using System.Linq; using System.Net.Http; using System.Threading.Tasks; - using Newtonsoft.Json; using System.Net; @@ -23,7 +22,8 @@ namespace Firebase.Database.Http /// The specific JSON Serializer Settings. /// The type of entities the collection should contain. /// The . - public static async Task>> GetObjectCollectionAsync(this HttpClient client, string requestUri, + public static async Task>> GetObjectCollectionAsync( + 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>(responseData, jsonSerializerSettings); + var dictionary = + JsonConvert.DeserializeObject>(responseData, jsonSerializerSettings); - if (dictionary == null) - { - return new FirebaseObject[0]; - } + if (dictionary == null) return new FirebaseObject[0]; return dictionary.Select(item => new FirebaseObject(item.Key, item.Value)).ToList(); } @@ -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((string)item.Key, item.Value); - } + yield return new FirebaseObject((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..5a779ed 100644 --- a/FireBase/Http/PostResult.cs +++ b/FireBase/Http/PostResult.cs @@ -8,10 +8,6 @@ namespace Firebase.Database.Http /// /// Gets or sets the generated key after a successful post. /// - 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..da78365 100644 --- a/FireBase/ObservableExtensions.cs +++ b/FireBase/ObservableExtensions.cs @@ -2,8 +2,7 @@ { using System; using System.Collections.ObjectModel; - - using Firebase.Database.Streaming; + using Streaming; /// /// Extensions for . @@ -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..5527168 100644 --- a/FireBase/Offline/ConcurrentOfflineDatabase.cs +++ b/FireBase/Offline/ConcurrentOfflineDatabase.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using LiteDB; /// @@ -24,34 +23,30 @@ /// Custom string which will get appended to the file name. 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().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() .FindAll() .ToDictionary(o => o.Key, o => o); - this.ccache = new ConcurrentDictionary(cache); - + ccache = new ConcurrentDictionary(cache); } /// /// Gets the number of elements contained in the . /// /// The number of elements contained in the . - public int Count => this.ccache.Count; + public int Count => ccache.Count; /// /// Gets a value indicating whether this is a read-only collection. @@ -62,13 +57,13 @@ /// Gets an containing the keys of the . /// /// An containing the keys of the object that implements . - public ICollection Keys => this.ccache.Keys; + public ICollection Keys => ccache.Keys; /// /// Gets an containing the values in the . /// /// An containing the values in the object that implements . - public ICollection Values => this.ccache.Values; + public ICollection Values => ccache.Values; /// /// Gets or sets the element with the specified key. @@ -77,15 +72,12 @@ /// The element with the specified key. 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); } } @@ -95,12 +87,12 @@ /// An enumerator that can be used to iterate through the collection. public IEnumerator> GetEnumerator() { - return this.ccache.GetEnumerator(); + return ccache.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } /// @@ -109,7 +101,7 @@ /// The object to add to the . public void Add(KeyValuePair item) { - this.Add(item.Key, item.Value); + Add(item.Key, item.Value); } /// @@ -117,8 +109,8 @@ /// public void Clear() { - this.ccache.Clear(); - this.db.Delete(Query.All()); + ccache.Clear(); + db.Delete(Query.All()); } /// @@ -128,7 +120,7 @@ /// True if is found in the ; otherwise, false. public bool Contains(KeyValuePair item) { - return this.ContainsKey(item.Key); + return ContainsKey(item.Key); } /// @@ -138,7 +130,7 @@ /// The zero-based index in at which copying begins. public void CopyTo(KeyValuePair[] array, int arrayIndex) { - this.ccache.ToList().CopyTo(array, arrayIndex); + ccache.ToList().CopyTo(array, arrayIndex); } /// @@ -148,7 +140,7 @@ /// True if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . public bool Remove(KeyValuePair item) { - return this.Remove(item.Key); + return Remove(item.Key); } /// @@ -158,7 +150,7 @@ /// True if the contains an element with the key; otherwise, false. public bool ContainsKey(string key) { - return this.ccache.ContainsKey(key); + return ccache.ContainsKey(key); } /// @@ -168,8 +160,8 @@ /// The object to use as the value of the element to add. 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); } /// @@ -179,8 +171,8 @@ /// True if the element is successfully removed; otherwise, false. This method also returns false if was not found in the original . public bool Remove(string key) { - this.ccache.TryRemove(key, out OfflineEntry _); - return this.db.Delete(key); + ccache.TryRemove(key, out _); + return db.Delete(key); } /// @@ -190,18 +182,16 @@ /// True if the object that implements contains an element with the specified key; otherwise, false. 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..56dcf46 100644 --- a/FireBase/Offline/DatabaseExtensions.cs +++ b/FireBase/Offline/DatabaseExtensions.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; - using Firebase.Database.Query; + using Query; public static class DatabaseExtensions { @@ -19,10 +19,13 @@ /// Specifies what strategy should be used for initial pulling of server data. /// Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. /// The . - public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) + public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, string filenameModifier = "", + string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, + InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class { - return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges); + return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, + filenameModifier, streamingOptions, initialPullStrategy, pushChanges); } /// @@ -36,11 +39,16 @@ /// Specifies what strategy should be used for initial pulling of server data. /// Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. /// The . - public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) + public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, + string filenameModifier = "", string elementRoot = "", + StreamingOptions streamingOptions = StreamingOptions.LatestOnly, + InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class where TSetHandler : ISetHandler, new() { - return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges, Activator.CreateInstance()); + return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, + filenameModifier, streamingOptions, initialPullStrategy, pushChanges, + Activator.CreateInstance()); } /// @@ -50,8 +58,9 @@ /// The object to set. /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. - public static void Patch(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) - where T: class + public static void Patch(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -63,8 +72,9 @@ /// The object to set. /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. - public static void Put(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) - where T: class + public static void Put(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -77,7 +87,7 @@ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. /// The generated key for this object. public static string Post(this RealtimeDatabase db, T obj, bool syncOnline = true, int priority = 1) - where T: class + where T : class { var key = FirebaseKeyGenerator.Next(); @@ -93,7 +103,7 @@ /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. public static void Delete(this RealtimeDatabase db, string key, bool syncOnline = true, int priority = 1) - where T: class + where T : class { db.Set(key, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -109,8 +119,10 @@ /// Value to put. /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. - public static void Put(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T: class + public static void Put(this RealtimeDatabase db, string key, + Expression> propertyExpression, TProperty value, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -126,8 +138,10 @@ /// Value to patch. /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. - public static void Patch(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T: class + public static void Patch(this RealtimeDatabase db, string key, + Expression> propertyExpression, TProperty value, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -143,9 +157,10 @@ /// Value to put. /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. - public static void Delete(this RealtimeDatabase db, string key, Expression> propertyExpression, bool syncOnline = true, int priority = 1) - where T: class - where TProperty: class + public static void Delete(this RealtimeDatabase db, string key, + Expression> propertyExpression, bool syncOnline = true, int priority = 1) + where T : class + where TProperty : class { db.Set(key, propertyExpression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -163,12 +178,17 @@ /// Value to put. /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. - public static void Post(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T: class - where TSelector: IDictionary + public static void Post(this RealtimeDatabase db, string key, + Expression> propertyExpression, TProperty value, bool syncOnline = true, + int priority = 1) + where T : class + where TSelector : IDictionary { var nextKey = FirebaseKeyGenerator.Next(); - var expression = Expression.Lambda>(Expression.Call(propertyExpression.Body, typeof(TSelector).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(nextKey)), propertyExpression.Parameters); + var expression = Expression.Lambda>( + 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); } @@ -185,11 +205,16 @@ /// Key within the nested dictionary to delete. /// Indicates whether the item should be synced online. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. - public static void Delete(this RealtimeDatabase db, string key, Expression>> propertyExpression, string dictionaryKey, bool syncOnline = true, int priority = 1) - where T: class + public static void Delete(this RealtimeDatabase db, string key, + Expression>> propertyExpression, string dictionaryKey, + bool syncOnline = true, int priority = 1) + where T : class { - var expression = Expression.Lambda>(Expression.Call(propertyExpression.Body, typeof(IDictionary).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(dictionaryKey)), propertyExpression.Parameters); + var expression = Expression.Lambda>( + Expression.Call(propertyExpression.Body, + typeof(IDictionary).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..e3b49b5 100644 --- a/FireBase/Offline/ISetHandler.cs +++ b/FireBase/Offline/ISetHandler.cs @@ -1,11 +1,10 @@ namespace Firebase.Database.Offline { - using Firebase.Database.Query; - + using Query; using System.Threading.Tasks; public interface ISetHandler { 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..a1ae3f7 100644 --- a/FireBase/Offline/InitialPullStrategy.cs +++ b/FireBase/Offline/InitialPullStrategy.cs @@ -8,7 +8,7 @@ /// /// Don't pull anything. /// - None, + None, /// /// Pull only what isn't already stored offline. @@ -20,4 +20,4 @@ /// Everything, } -} +} \ No newline at end of file diff --git a/FireBase/Offline/Internals/MemberAccessVisitor.cs b/FireBase/Offline/Internals/MemberAccessVisitor.cs index 1f7cb11..2bc0fc3 100644 --- a/FireBase/Offline/Internals/MemberAccessVisitor.cs +++ b/FireBase/Offline/Internals/MemberAccessVisitor.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; - using Newtonsoft.Json; public class MemberAccessVisitor : ExpressionVisitor @@ -12,7 +11,7 @@ private bool wasDictionaryAccess; - public IEnumerable PropertyNames => this.propertyNames; + public IEnumerable PropertyNames => propertyNames; public MemberAccessVisitor() { @@ -22,30 +21,30 @@ { 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(); - 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..0918a8c 100644 --- a/FireBase/Offline/OfflineCacheAdapter.cs +++ b/FireBase/Offline/OfflineCacheAdapter.cs @@ -5,7 +5,7 @@ using System.Collections.Generic; using System.Linq; - internal class OfflineCacheAdapter : IDictionary, IDictionary + internal class OfflineCacheAdapter : IDictionary, IDictionary { private readonly IDictionary database; @@ -19,66 +19,53 @@ throw new NotImplementedException(); } - public int Count => this.database.Count; + public int Count => database.Count; public bool IsSynchronized { get; } public object SyncRoot { get; } - public bool IsReadOnly => this.database.IsReadOnly; + public bool IsReadOnly => database.IsReadOnly; object IDictionary.this[object key] { - get - { - return this.database[key.ToString()].Deserialize(); - } + get => database[key.ToString()].Deserialize(); 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 Keys => this.database.Keys; + public ICollection Keys => database.Keys; ICollection IDictionary.Values { get; } ICollection IDictionary.Keys { get; } - public ICollection Values => this.database.Values.Select(o => o.Deserialize()).ToList(); + public ICollection Values => database.Values.Select(o => o.Deserialize()).ToList(); public T this[string key] { - get - { - return this.database[key].Deserialize(); - } + get => database[key].Deserialize(); set { - if (this.database.ContainsKey(key)) - { - this.database[key] = new OfflineEntry(key, value, this.database[key].Priority, this.database[key].SyncOptions); - } + if (database.ContainsKey(key)) + database[key] = new OfflineEntry(key, value, database[key].Priority, database[key].SyncOptions); else - { - this.database[key] = new OfflineEntry(key, value, 1, SyncOptions.None); - } + 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 +75,39 @@ public void Remove(object key) { - this.Remove(key.ToString()); + Remove(key.ToString()); } public bool IsFixedSize => false; public IEnumerator> GetEnumerator() { - return this.database.Select(d => new KeyValuePair(d.Key, d.Value.Deserialize())).GetEnumerator(); + return database.Select(d => new KeyValuePair(d.Key, d.Value.Deserialize())).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } public void Add(KeyValuePair item) { - this.Add(item.Key, item.Value); + Add(item.Key, item.Value); } public void Add(object key, object value) { - this.Add(key.ToString(), (T)value); + Add(key.ToString(), (T) value); } public void Clear() { - this.database.Clear(); + database.Clear(); } public bool Contains(KeyValuePair item) { - return this.ContainsKey(item.Key); + return ContainsKey(item.Key); } public void CopyTo(KeyValuePair[] array, int arrayIndex) @@ -130,29 +117,29 @@ public bool Remove(KeyValuePair 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(); 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..3e6e7d8 100644 --- a/FireBase/Offline/OfflineDatabase.cs +++ b/FireBase/Offline/OfflineDatabase.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; - using LiteDB; /// @@ -23,21 +22,18 @@ /// Custom string which will get appended to the file name. 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().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().FindAll() + cache = db.Database.GetCollection().FindAll() .ToDictionary(o => o.Key, o => o); } @@ -45,24 +41,24 @@ /// Gets the number of elements contained in the . /// /// The number of elements contained in the . - public int Count => this.cache.Count; + public int Count => cache.Count; /// /// Gets a value indicating whether this is a read-only collection. /// - public bool IsReadOnly => this.cache.IsReadOnly; + public bool IsReadOnly => cache.IsReadOnly; /// /// Gets an containing the keys of the . /// /// An containing the keys of the object that implements . - public ICollection Keys => this.cache.Keys; + public ICollection Keys => cache.Keys; /// /// Gets an containing the values in the . /// /// An containing the values in the object that implements . - public ICollection Values => this.cache.Values; + public ICollection Values => cache.Values; /// /// Gets or sets the element with the specified key. @@ -71,15 +67,12 @@ /// The element with the specified key. 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); } } @@ -89,12 +82,12 @@ /// An enumerator that can be used to iterate through the collection. public IEnumerator> GetEnumerator() { - return this.cache.GetEnumerator(); + return cache.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } /// @@ -103,7 +96,7 @@ /// The object to add to the . public void Add(KeyValuePair item) { - this.Add(item.Key, item.Value); + Add(item.Key, item.Value); } /// @@ -111,8 +104,8 @@ /// public void Clear() { - this.cache.Clear(); - this.db.Delete(Query.All()); + cache.Clear(); + db.Delete(Query.All()); } /// @@ -122,7 +115,7 @@ /// True if is found in the ; otherwise, false. public bool Contains(KeyValuePair item) { - return this.ContainsKey(item.Key); + return ContainsKey(item.Key); } /// @@ -132,7 +125,7 @@ /// The zero-based index in at which copying begins. public void CopyTo(KeyValuePair[] array, int arrayIndex) { - this.cache.CopyTo(array, arrayIndex); + cache.CopyTo(array, arrayIndex); } /// @@ -142,7 +135,7 @@ /// True if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . public bool Remove(KeyValuePair item) { - return this.Remove(item.Key); + return Remove(item.Key); } /// @@ -152,7 +145,7 @@ /// True if the contains an element with the key; otherwise, false. public bool ContainsKey(string key) { - return this.cache.ContainsKey(key); + return cache.ContainsKey(key); } /// @@ -162,8 +155,8 @@ /// The object to use as the value of the element to add. public void Add(string key, OfflineEntry value) { - this.cache.Add(key, value); - this.db.Insert(value); + cache.Add(key, value); + db.Insert(value); } /// @@ -173,8 +166,8 @@ /// True if the element is successfully removed; otherwise, false. This method also returns false if was not found in the original . public bool Remove(string key) { - this.cache.Remove(key); - return this.db.Delete(key); + cache.Remove(key); + return db.Delete(key); } /// @@ -184,18 +177,16 @@ /// True if the object that implements contains an element with the specified key; otherwise, false. 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..dfd5910 100644 --- a/FireBase/Offline/OfflineEntry.cs +++ b/FireBase/Offline/OfflineEntry.cs @@ -1,7 +1,6 @@ namespace Firebase.Database.Offline { using System; - using Newtonsoft.Json; /// @@ -18,16 +17,17 @@ /// The object. /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. /// The sync options. - 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; } /// @@ -45,63 +45,39 @@ /// /// Initializes a new instance of the class. /// - public OfflineEntry() + public OfflineEntry() { } /// /// Gets or sets the key of this entry. /// - public string Key - { - get; - set; - } + public string Key { get; set; } /// /// Gets or sets the priority. Objects with higher priority will be synced first. Higher number indicates higher priority. /// - public int Priority - { - get; - set; - } + public int Priority { get; set; } /// /// Gets or sets the timestamp when this entry was last touched. /// - public DateTime Timestamp - { - get; - set; - } + public DateTime Timestamp { get; set; } /// /// Gets or sets the which define what sync state this entry is in. /// - public SyncOptions SyncOptions - { - get; - set; - } + public SyncOptions SyncOptions { get; set; } /// /// Gets or sets serialized JSON data. /// - public string Data - { - get; - set; - } + public string Data { get; set; } /// /// Specifies whether this is only a partial object. /// - public bool IsPartial - { - get; - set; - } + public bool IsPartial { get; set; } /// /// Deserializes into . The result is cached. @@ -110,7 +86,7 @@ /// Instance of . public T Deserialize() { - return (T)(this.dataInstance ?? (this.dataInstance = JsonConvert.DeserializeObject(this.Data))); + return (T) (dataInstance ?? (dataInstance = JsonConvert.DeserializeObject(Data))); } } -} +} \ No newline at end of file diff --git a/FireBase/Offline/RealtimeDatabase.cs b/FireBase/Offline/RealtimeDatabase.cs index 61a7010..4d61027 100644 --- a/FireBase/Offline/RealtimeDatabase.cs +++ b/FireBase/Offline/RealtimeDatabase.cs @@ -7,10 +7,9 @@ using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; - - using Firebase.Database.Extensions; - using Firebase.Database.Query; - using Firebase.Database.Streaming; + using Extensions; + using Query; + using Streaming; using System.Reactive.Threading.Tasks; using System.Linq.Expressions; using Internals; @@ -46,21 +45,25 @@ /// Specifies whether changes should be streamed from the server. /// Specifies if everything should be pull from the online storage on start. It only makes sense when is set to true. /// Specifies whether changed items should actually be pushed to the server. If this is false, then Put / Post / Delete will not affect server data. - public RealtimeDatabase(ChildQuery childQuery, string elementRoot, Func> offlineDatabaseFactory, string filenameModifier, StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, ISetHandler setHandler = null) + public RealtimeDatabase(ChildQuery childQuery, string elementRoot, + Func> offlineDatabaseFactory, string filenameModifier, + StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, + ISetHandler 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(new OfflineCacheAdapter(this.Database)); - this.subject = new Subject>(); + Database = offlineDatabaseFactory(typeof(T), filenameModifier); + firebaseCache = new FirebaseCache(new OfflineCacheAdapter(Database)); + subject = new Subject>(); - this.PutHandler = setHandler ?? new SetHandler(); + PutHandler = setHandler ?? new SetHandler(); - 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); } /// @@ -71,17 +74,9 @@ /// /// Gets the backing Database. /// - public IDictionary Database - { - get; - private set; - } + public IDictionary Database { get; private set; } - public ISetHandler PutHandler - { - private get; - set; - } + public ISetHandler PutHandler { private get; set; } /// /// Overwrites existing object with given key. @@ -92,35 +87,34 @@ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1) { - this.SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions)); + SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions)); } - public void Set(string key, Expression> propertyExpression, object value, SyncOptions syncOptions, int priority = 1) + public void Set(string key, Expression> 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(key, setObject.Object, setObject == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)); + subject.OnNext(new FirebaseEvent(key, setObject.Object, + setObject == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, + FirebaseEventSource.Offline)); } /// @@ -130,15 +124,11 @@ /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. 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; } /// @@ -146,26 +136,30 @@ /// public async Task PullAsync() { - var existingEntries = await this.childQuery + var existingEntries = await childQuery .OnceAsync() .ToObservable() .RetryAfterDelay>, 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 == + System.Net.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(e.Key, e.Object, FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePull)); + Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None); + subject.OnNext(new FirebaseEvent(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(item, null, FirebaseEventType.Delete, FirebaseEventSource.OnlinePull)); + Database.Remove(item); + subject.OnNext(new FirebaseEvent(item, null, FirebaseEventType.Delete, + FirebaseEventSource.OnlinePull)); } } @@ -174,7 +168,7 @@ /// public IEnumerable> Once() { - return this.Database + return Database .Where(kvp => !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial) .Select(kvp => new FirebaseObject(kvp.Key, kvp.Value.Deserialize())) .ToList(); @@ -186,67 +180,72 @@ /// Stream of . public IObservable> 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.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(offlineEntry.Key, offlineEntry.Deserialize(), 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(kvp.Key, kvp.Value.Deserialize(), FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)) + .Where(offlineEntry => + !string.IsNullOrEmpty(offlineEntry.Data) && offlineEntry.Data != "null" && + !offlineEntry.IsPartial) + .Select(offlineEntry => new FirebaseEvent(offlineEntry.Key, offlineEntry.Deserialize(), + 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(kvp.Key, kvp.Value.Deserialize(), + FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)) .ToList() .ToObservable(); - } - this.observable = initialData - .Merge(this.subject) - .Merge(this.GetInitialPullObservable() - .RetryAfterDelay>, 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(e.Key, e.Object, e.Object == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlineInitial)) - .Concat(Observable.Create>(observer => this.InitializeStreamingSubscription(observer)))) - .Do(next => { }, e => this.observable = null, () => this.observable = null) + observable = initialData + .Merge(subject) + .Merge(GetInitialPullObservable() + .RetryAfterDelay>, FirebaseException>( + childQuery.Client.Options.SyncPeriod, + ex => ex.StatusCode == + System.Net.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(e.Key, e.Object, + e.Object == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, + FirebaseEventSource.OnlineInitial)) + .Concat(Observable.Create>(observer => + InitializeStreamingSubscription(observer)))) + .Do(next => { }, e => observable = null, () => observable = null) .Replay() .RefCount(); } - return this.observable; + return observable; } public void Dispose() { - this.subject.OnCompleted(); - this.firebaseSubscription?.Dispose(); + subject.OnCompleted(); + firebaseSubscription?.Dispose(); } - private IReadOnlyCollection> ResetDatabaseFromInitial(IReadOnlyCollection> collection, bool onlyWhenInitialEverything = true) + private IReadOnlyCollection> ResetDatabaseFromInitial( + IReadOnlyCollection> 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(k, null)); + var extra = Once() + .Select(f => f.Key) + .Except(collection.Select(c => c.Key)) + .Select(k => new FirebaseObject(k, null)); return collection.Concat(extra).ToList(); } @@ -257,57 +256,58 @@ // 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>> 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>>(); } - if (string.IsNullOrWhiteSpace(this.elementRoot)) - { + if (string.IsNullOrWhiteSpace(elementRoot)) return Observable.Defer(() => query.OnceAsync().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()).Select(e => new[] { new FirebaseObject(this.elementRoot, e) })); + return Observable.Defer(async () => + Observable.Return(await query.OnceSingleAsync()) + .Select(e => new[] {new FirebaseObject(elementRoot, e)})); } private IDisposable InitializeStreamingSubscription(IObserver> 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(observer, queryLatest, this.elementRoot, this.firebaseCache); - this.firebaseSubscription.ExceptionThrown += this.StreamingExceptionThrown; + var queryLatest = childQuery.OrderByKey().StartAt(() => GetLatestKey()); + firebaseSubscription = + new FirebaseSubscription(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(observer, queryAll, this.elementRoot, this.firebaseCache); - this.firebaseSubscription.ExceptionThrown += this.StreamingExceptionThrown; + var queryAll = childQuery; + firebaseSubscription = new FirebaseSubscription(observer, queryAll, elementRoot, firebaseCache); + firebaseSubscription.ExceptionThrown += StreamingExceptionThrown; - return new CompositeDisposable(this.firebaseSubscription.Run(), completeDisposable); + return new CompositeDisposable(firebaseSubscription.Run(), completeDisposable); default: break; } @@ -315,43 +315,44 @@ 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(key, obj?.Deserialize(), string.IsNullOrEmpty(obj?.Data) || obj?.Data == "null" ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, eventSource)); + Database[key] = obj; + subject.OnNext(new FirebaseEvent(key, obj?.Deserialize(), + 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 +363,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())); + var tasks = group.OrderBy(kvp => kvp.Value.IsPartial).Select(kvp => + kvp.Value.IsPartial + ? ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key) + : ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key, + kvp.Value.Deserialize())); try { @@ -373,7 +375,7 @@ } catch (Exception ex) { - this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); + SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } } } @@ -384,15 +386,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(), pair.Key, pair.Value)); + var tasks = group.Select(pair => + ResetAfterPull( + childQuery.Child(pair.Key == elementRoot ? string.Empty : pair.Key).OnceSingleAsync(), + 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 +405,48 @@ private async Task ResetAfterPull(Task 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(key, obj, obj == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePush)); - } + if (streamingOptions == StreamingOptions.None) + subject.OnNext(new FirebaseEvent(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 e) { - this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception)); + SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception)); } - private Tuple GenerateFullKey(string key, Expression> propertyGetter, SyncOptions syncOptions) + private Tuple GenerateFullKey(string key, + Expression> propertyGetter, SyncOptions syncOptions) { var visitor = new MemberAccessVisitor(); visitor.Visit(propertyGetter); @@ -447,13 +454,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..18a5131 100644 --- a/FireBase/Offline/SetHandler.cs +++ b/FireBase/Offline/SetHandler.cs @@ -1,7 +1,6 @@ namespace Firebase.Database.Offline { - using Firebase.Database.Query; - + using Query; using System.Threading.Tasks; public class SetHandler : ISetHandler @@ -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..4a5f7b8 100644 --- a/FireBase/Offline/StreamingOptions.cs +++ b/FireBase/Offline/StreamingOptions.cs @@ -18,4 +18,4 @@ /// Everything } -} +} \ No newline at end of file diff --git a/FireBase/Offline/SyncOptions.cs b/FireBase/Offline/SyncOptions.cs index b2f382a..aa3e21c 100644 --- a/FireBase/Offline/SyncOptions.cs +++ b/FireBase/Offline/SyncOptions.cs @@ -25,4 +25,4 @@ /// Patch } -} +} \ No newline at end of file diff --git a/FireBase/Query/AuthQuery.cs b/FireBase/Query/AuthQuery.cs index 8a8d3e8..14beb7e 100644 --- a/FireBase/Query/AuthQuery.cs +++ b/FireBase/Query/AuthQuery.cs @@ -15,7 +15,8 @@ namespace Firebase.Database.Query /// The parent. /// The authentication token factory. /// The owner. - public AuthQuery(FirebaseQuery parent, Func tokenFactory, FirebaseClient client) : base(parent, () => client.Options.AsAccessToken ? "access_token" : "auth", client) + public AuthQuery(FirebaseQuery parent, Func tokenFactory, FirebaseClient client) : base(parent, + () => client.Options.AsAccessToken ? "access_token" : "auth", client) { this.tokenFactory = tokenFactory; } @@ -27,7 +28,7 @@ namespace Firebase.Database.Query /// The . 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..510ae75 100644 --- a/FireBase/Query/ChildQuery.cs +++ b/FireBase/Query/ChildQuery.cs @@ -1,7 +1,7 @@ namespace Firebase.Database.Query { using System; - + /// /// Firebase query which references the child of current node. /// @@ -38,19 +38,13 @@ namespace Firebase.Database.Query /// The . 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..be544c8 100644 --- a/FireBase/Query/FilterQuery.cs +++ b/FireBase/Query/FilterQuery.cs @@ -1,4 +1,4 @@ -namespace Firebase.Database.Query +namespace Firebase.Database.Query { using System; using System.Globalization; @@ -6,7 +6,7 @@ namespace Firebase.Database.Query /// /// Represents a firebase filtering query, e.g. "?LimitToLast=10". /// - public class FilterQuery : ParameterQuery + public class FilterQuery : ParameterQuery { private readonly Func valueFactory; private readonly Func doubleValueFactory; @@ -19,7 +19,8 @@ namespace Firebase.Database.Query /// The filter. /// The value for filter. /// The owning client. - public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) + public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, + FirebaseClient client) : base(parent, filterFactory, client) { this.valueFactory = valueFactory; @@ -32,10 +33,11 @@ namespace Firebase.Database.Query /// The filter. /// The value for filter. /// The owning client. - public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) + public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, + FirebaseClient client) : base(parent, filterFactory, client) { - this.doubleValueFactory = valueFactory; + doubleValueFactory = valueFactory; } /// @@ -45,10 +47,11 @@ namespace Firebase.Database.Query /// The filter. /// The value for filter. /// The owning client. - public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) + public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, + FirebaseClient client) : base(parent, filterFactory, client) { - this.boolValueFactory = valueFactory; + boolValueFactory = valueFactory; } /// @@ -58,24 +61,21 @@ namespace Firebase.Database.Query /// Url parameter part of the resulting path. protected override string BuildUrlParameter(FirebaseQuery child) { - if (this.valueFactory != null) + if (valueFactory != null) { - if(this.valueFactory() == null) - { - return $"null"; - } - return $"\"{this.valueFactory()}\""; + if (valueFactory() == null) return $"null"; + return $"\"{valueFactory()}\""; } - else if (this.doubleValueFactory != null) + else if (doubleValueFactory != null) { - return this.doubleValueFactory().ToString(CultureInfo.InvariantCulture); + return doubleValueFactory().ToString(CultureInfo.InvariantCulture); } - else if (this.boolValueFactory != null) + else if (boolValueFactory != null) { - return $"{this.boolValueFactory().ToString().ToLower()}"; + 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..5e09795 100644 --- a/FireBase/Query/FirebaseQuery.cs +++ b/FireBase/Query/FirebaseQuery.cs @@ -5,11 +5,9 @@ namespace Firebase.Database.Query 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 Http; + using Offline; + using Streaming; using Newtonsoft.Json; using System.Net; @@ -31,17 +29,14 @@ namespace Firebase.Database.Query /// The owning client. protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client) { - this.Client = client; - this.Parent = parent; + Client = client; + Parent = parent; } /// /// Gets the client. /// - public FirebaseClient Client - { - get; - } + public FirebaseClient Client { get; } /// /// Queries the firebase server once returning collection of items. @@ -55,14 +50,15 @@ namespace Firebase.Database.Query 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(url, Client.Options.JsonSerializerSettings) + return await GetClient(timeout).GetObjectCollectionAsync(url, Client.Options.JsonSerializerSettings) .ConfigureAwait(false); } @@ -97,7 +93,7 @@ namespace Firebase.Database.Query try { - url = await this.BuildUrlAsync().ConfigureAwait(false); + url = await BuildUrlAsync().ConfigureAwait(false); } catch (Exception ex) { @@ -106,7 +102,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); @@ -127,7 +123,8 @@ namespace Firebase.Database.Query /// Type of elements. /// Optional custom root element of received json items. /// Observable stream of . - public IObservable> AsObservable(EventHandler> exceptionHandler = null, string elementRoot = "") + public IObservable> AsObservable( + EventHandler> exceptionHandler = null, string elementRoot = "") { return Observable.Create>(observer => { @@ -144,13 +141,13 @@ namespace Firebase.Database.Query public async Task BuildUrlAsync() { // if token factory is present on the parent then use it to generate auth token - if (this.Client.Options.AuthTokenAsyncFactory != null) + if (Client.Options.AuthTokenAsyncFactory != null) { - var token = await this.Client.Options.AuthTokenAsyncFactory().ConfigureAwait(false); + var token = await Client.Options.AuthTokenAsyncFactory().ConfigureAwait(false); return this.WithAuth(token).BuildUrl(null); } - return this.BuildUrl(null); + return BuildUrl(null); } /// @@ -161,20 +158,21 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of /// Resulting firebase object with populated key. - public async Task> PostAsync(string data, bool generateKeyOffline = true, TimeSpan? timeout = null) + public async Task> 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(key, data); } else { - var c = this.GetClient(timeout); - var sendData = await this.SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false); + var c = GetClient(timeout); + var sendData = await SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false); var result = JsonConvert.DeserializeObject(sendData, Client.Options.JsonSerializerSettings); return new FirebaseObject(result.Name, data); @@ -190,7 +188,7 @@ namespace Firebase.Database.Query /// The . 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); } @@ -204,7 +202,7 @@ namespace Firebase.Database.Query /// The . 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); } @@ -216,14 +214,14 @@ namespace Firebase.Database.Query /// The . 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) { @@ -249,7 +247,7 @@ namespace Firebase.Database.Query /// public void Dispose() { - this.client?.Dispose(); + client?.Dispose(); } /// @@ -261,33 +259,23 @@ namespace Firebase.Database.Query 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 SendAsync(HttpClient client, string data, HttpMethod method) @@ -299,7 +287,7 @@ namespace Firebase.Database.Query try { - url = await this.BuildUrlAsync().ConfigureAwait(false); + url = await BuildUrlAsync().ConfigureAwait(false); } catch (Exception ex) { @@ -327,4 +315,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..9f6e36c 100644 --- a/FireBase/Query/IFirebaseQuery.cs +++ b/FireBase/Query/IFirebaseQuery.cs @@ -3,8 +3,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; - - using Firebase.Database.Streaming; + using Streaming; /// /// The FirebaseQuery interface. @@ -14,10 +13,7 @@ /// /// Gets the owning client of this query. /// - FirebaseClient Client - { - get; - } + FirebaseClient Client { get; } /// /// Retrieves items which exist on the location specified by this query instance. @@ -32,7 +28,8 @@ /// /// Type of the items. /// Cold observable of . - IObservable> AsObservable(EventHandler> exceptionHandler, string elementRoot = ""); + IObservable> AsObservable( + EventHandler> exceptionHandler, string elementRoot = ""); /// /// Builds the actual url of this query. @@ -40,4 +37,4 @@ /// The . Task BuildUrlAsync(); } -} +} \ No newline at end of file diff --git a/FireBase/Query/OrderQuery.cs b/FireBase/Query/OrderQuery.cs index 46ebd2c..16adba7 100644 --- a/FireBase/Query/OrderQuery.cs +++ b/FireBase/Query/OrderQuery.cs @@ -28,7 +28,7 @@ namespace Firebase.Database.Query /// The . 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..fb273a3 100644 --- a/FireBase/Query/ParameterQuery.cs +++ b/FireBase/Query/ParameterQuery.cs @@ -20,7 +20,7 @@ namespace Firebase.Database.Query : base(parent, client) { this.parameterFactory = parameterFactory; - this.separator = (this.Parent is ChildQuery) ? "?" : "&"; + separator = Parent is ChildQuery ? "?" : "&"; } /// @@ -30,7 +30,7 @@ namespace Firebase.Database.Query /// The . protected override string BuildUrlSegment(FirebaseQuery child) { - return $"{this.separator}{this.parameterFactory()}={this.BuildUrlParameter(child)}"; + return $"{separator}{parameterFactory()}={BuildUrlParameter(child)}"; } /// @@ -40,4 +40,4 @@ namespace Firebase.Database.Query /// The . 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..735fe0a 100644 --- a/FireBase/Query/QueryExtensions.cs +++ b/FireBase/Query/QueryExtensions.cs @@ -119,7 +119,7 @@ namespace Firebase.Database.Query { return child.EqualTo(() => value); } - + /// /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. /// @@ -129,7 +129,7 @@ namespace Firebase.Database.Query public static FilterQuery EqualTo(this ParameterQuery child, bool value) { return child.EqualTo(() => value); - } + } /// /// Instructs firebase to send data equal to null. This must be preceded by an OrderBy query. @@ -139,7 +139,7 @@ namespace Firebase.Database.Query public static FilterQuery EqualTo(this ParameterQuery child) { return child.EqualTo(() => null); - } + } /// /// Limits the result to first items. @@ -173,9 +173,12 @@ namespace Firebase.Database.Query return query.PatchAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } - public static async Task> PostAsync(this FirebaseQuery query, T obj, bool generateKeyOffline = true) + public static async Task> PostAsync(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(result.Key, obj); } @@ -189,19 +192,13 @@ namespace Firebase.Database.Query /// Locations where to store the item. public static async Task FanOut(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(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..b54c315 100644 --- a/FireBase/Query/QueryFactoryExtensions.cs +++ b/FireBase/Query/QueryFactoryExtensions.cs @@ -139,7 +139,7 @@ namespace Firebase.Database.Query { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } - + /// /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. /// @@ -149,7 +149,7 @@ namespace Firebase.Database.Query public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); - } + } /// /// Limits the result to first items. @@ -173,4 +173,4 @@ namespace Firebase.Database.Query 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..1960426 100644 --- a/FireBase/Query/SilentQuery.cs +++ b/FireBase/Query/SilentQuery.cs @@ -5,7 +5,7 @@ /// 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..77fc622 100644 --- a/FireBase/Streaming/FirebaseCache.cs +++ b/FireBase/Streaming/FirebaseCache.cs @@ -5,9 +5,7 @@ namespace Firebase.Database.Streaming using System.Collections.Generic; using System.Linq; using System.Reflection; - - using Firebase.Database.Http; - + using Http; using Newtonsoft.Json; /// @@ -18,6 +16,7 @@ namespace Firebase.Database.Streaming { private readonly IDictionary dictionary; private readonly bool isDictionaryType; + private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace @@ -26,7 +25,7 @@ namespace Firebase.Database.Streaming /// /// Initializes a new instance of the class. /// - public FirebaseCache() + public FirebaseCache() : this(new Dictionary()) { } @@ -37,8 +36,8 @@ namespace Firebase.Database.Streaming /// The existing items. public FirebaseCache(IDictionary existingItems) { - this.dictionary = existingItems; - this.isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); + dictionary = existingItems; + isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); } /// @@ -53,11 +52,11 @@ namespace Firebase.Database.Streaming Action 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 @@ -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()?.PropertyName); + .First(p => p.Name.Equals(element, StringComparison.OrdinalIgnoreCase) || + element == p.GetCustomAttribute()?.PropertyName); objDeleter = () => property.SetValue(objParent, null); 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(item.Key, (T)item.Object); - } + if (!pathElements.Any()) yield return new FirebaseObject(item.Key, (T) item.Object); } // nested dictionary changed @@ -141,52 +137,46 @@ 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.ToString() + : 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(pathElements[0], this.dictionary[pathElements[0]]); + dictionary[pathElements[0]] = dictionary[pathElements[0]]; + yield return new FirebaseObject(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); - } } #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } public IEnumerator> GetEnumerator() { - return this.dictionary.Select(p => new FirebaseObject(p.Key, p.Value)).GetEnumerator(); + return dictionary.Select(p => new FirebaseObject(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..e4fd238 100644 --- a/FireBase/Streaming/FirebaseEvent.cs +++ b/FireBase/Streaming/FirebaseEvent.cs @@ -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; } /// /// Gets the source of the event. /// - public FirebaseEventSource EventSource - { - get; - } + public FirebaseEventSource EventSource { get; } /// /// Gets the event type. /// - public FirebaseEventType EventType + public FirebaseEventType EventType { get; } + + public static FirebaseEvent Empty(FirebaseEventSource source) { - get; + return new FirebaseEvent(string.Empty, default(T), FirebaseEventType.InsertOrUpdate, source); } - - public static FirebaseEvent Empty(FirebaseEventSource source) => new FirebaseEvent(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..0a397ad 100644 --- a/FireBase/Streaming/FirebaseEventSource.cs +++ b/FireBase/Streaming/FirebaseEventSource.cs @@ -35,4 +35,4 @@ /// 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..d8c65b3 100644 --- a/FireBase/Streaming/FirebaseEventType.cs +++ b/FireBase/Streaming/FirebaseEventType.cs @@ -15,4 +15,4 @@ namespace Firebase.Database.Streaming /// 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..acdc76c 100644 --- a/FireBase/Streaming/FirebaseSubscription.cs +++ b/FireBase/Streaming/FirebaseSubscription.cs @@ -7,9 +7,7 @@ namespace Firebase.Database.Streaming using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; - - using Firebase.Database.Query; - + using Query; using Newtonsoft.Json.Linq; using System.Net; @@ -50,26 +48,27 @@ namespace Firebase.Database.Streaming /// The observer. /// The query. /// The cache. - public FirebaseSubscription(IObserver> observer, IFirebaseQuery query, string elementRoot, FirebaseCache cache) + public FirebaseSubscription(IObserver> observer, IFirebaseQuery query, string elementRoot, + FirebaseCache 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> ExceptionThrown; public void Dispose() { - this.cancel.Cancel(); + cancel.Cancel(); } public IDisposable Run() { - Task.Run(() => this.ReceiveThread()); + Task.Run(() => ReceiveThread()); return this; } @@ -84,15 +83,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 +103,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 +134,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(new FirebaseException(url, string.Empty, line, statusCode, ex))); + ExceptionThrown?.Invoke(this, + new ExceptionEventArgs(new FirebaseException(url, string.Empty, line, + statusCode, ex))); await Task.Delay(2000).ConfigureAwait(false); } @@ -185,30 +184,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.Empty(FirebaseEventSource.OnlineStream)); + observer.OnNext(FirebaseEvent.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(i.Key, i.Object, eventType, FirebaseEventSource.OnlineStream)); - } + observer.OnNext(new FirebaseEvent(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 +216,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..ab01510 100644 --- a/FireBase/Streaming/NonBlockingStreamReader.cs +++ b/FireBase/Streaming/NonBlockingStreamReader.cs @@ -17,29 +17,29 @@ private readonly int bufferSize; 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 +50,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 -- cgit v1.2.3-70-g09d2 From c4d046858e0822b7c2c540ac2368b2c0e88e7a26 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Sun, 19 May 2019 17:00:02 +0200 Subject: general refectoring added 42 as dummy Token --- DSACore/Auxiliary/Calculator/Argument.cs | 8 +- DSACore/Auxiliary/Calculator/ISolvable.cs | 2 +- DSACore/Auxiliary/Calculator/Operator.cs | 2 +- DSACore/Auxiliary/Calculator/Ops.cs | 2 +- DSACore/Auxiliary/Calculator/StringSolver.cs | 21 ++- DSACore/Auxiliary/CommandInfo.cs | 6 +- DSACore/Auxiliary/SpellCorrect.cs | 10 +- DSACore/Auxiliary/TalentEnumerableExtension.cs | 4 +- DSACore/Auxiliary/WeaponImporter.cs | 10 +- DSACore/Commands/CommandHandler.cs | 4 +- DSACore/Commands/FileHandler.cs | 11 +- DSACore/Commands/Gm.cs | 9 +- DSACore/Commands/HeldList.cs | 2 +- DSACore/Commands/Help.cs | 27 +--- DSACore/Commands/LebenUndAstral.cs | 4 +- DSACore/Commands/List.cs | 3 +- DSACore/Commands/MiscCommands.cs | 13 +- DSACore/Commands/NpcCommands.cs | 3 - DSACore/Controllers/CommandsController.cs | 7 +- DSACore/Controllers/LobbyController.cs | 5 +- DSACore/Controllers/TokensController.cs | 11 +- DSACore/DSA_Game/Characters/Character.cs | 14 +- DSACore/DSA_Game/Characters/NPC.cs | 4 - DSACore/DSA_Game/Dsa.cs | 15 +- DSACore/DSA_Game/Save/Properties.cs | 9 +- DSACore/DSA_Game/Save/SaveCommand.cs | 10 +- DSACore/DSA_Game/Save/Session.cs | 7 +- DSACore/FireBase/Database.cs | 55 ++++---- DSACore/Hubs/Login.cs | 30 ++-- DSACore/Models/Database/DSA/DatabaseChar.cs | 3 +- DSACore/Models/Database/DSA/Weapon.cs | 18 +-- DSACore/Models/Network/Command.cs | 4 +- DSACore/Models/Network/CommandResponse.cs | 7 +- DSACore/Models/Network/Group.cs | 2 - DSACore/Models/Network/Token.cs | 10 +- DSACore/Models/Network/User.cs | 7 +- DSACore/Program.cs | 10 +- DSACore/Startup.cs | 9 +- DSALib/Characters/Being.cs | 4 +- DSALib/Characters/Critter.cs | 53 ++++--- DSALib/Characters/ICombatant.cs | 8 +- DSALib/CritterAttack.cs | 8 +- FireBase/ExceptionEventArgs.cs | 10 +- FireBase/Extensions/ObservableExtensions.cs | 15 +- FireBase/Extensions/TaskExtensions.cs | 10 +- FireBase/FirebaseClient.cs | 34 ++--- FireBase/FirebaseException.cs | 16 +-- FireBase/FirebaseKeyGenerator.cs | 15 +- FireBase/FirebaseObject.cs | 10 +- FireBase/FirebaseOptions.cs | 30 ++-- FireBase/Http/HttpClientExtensions.cs | 32 ++--- FireBase/Http/PostResult.cs | 4 +- FireBase/ObservableExtensions.cs | 16 +-- FireBase/Offline/ConcurrentOfflineDatabase.cs | 128 +++++++++++------ FireBase/Offline/DatabaseExtensions.cs | 111 ++++++++++----- FireBase/Offline/ISetHandler.cs | 8 +- FireBase/Offline/InitialPullStrategy.cs | 10 +- FireBase/Offline/Internals/MemberAccessVisitor.cs | 16 +-- FireBase/Offline/OfflineCacheAdapter.cs | 64 ++++----- FireBase/Offline/OfflineDatabase.cs | 126 +++++++++++------ FireBase/Offline/OfflineEntry.cs | 43 +++--- FireBase/Offline/RealtimeDatabase.cs | 118 +++++++++------- FireBase/Offline/SetHandler.cs | 8 +- FireBase/Offline/StreamingOptions.cs | 10 +- FireBase/Offline/SyncOptions.cs | 10 +- FireBase/Query/AuthQuery.cs | 14 +- FireBase/Query/ChildQuery.cs | 14 +- FireBase/Query/FilterQuery.cs | 38 +++-- FireBase/Query/FirebaseQuery.cs | 162 +++++++++++----------- FireBase/Query/IFirebaseQuery.cs | 28 ++-- FireBase/Query/OrderQuery.cs | 12 +- FireBase/Query/ParameterQuery.cs | 18 +-- FireBase/Query/QueryExtensions.cs | 68 ++++----- FireBase/Query/QueryFactoryExtensions.cs | 85 +++++++----- FireBase/Query/SilentQuery.cs | 2 +- FireBase/Streaming/FirebaseCache.cs | 39 +++--- FireBase/Streaming/FirebaseEvent.cs | 8 +- FireBase/Streaming/FirebaseEventSource.cs | 14 +- FireBase/Streaming/FirebaseEventType.cs | 6 +- FireBase/Streaming/FirebaseSubscription.cs | 38 +++-- FireBase/Streaming/NonBlockingStreamReader.cs | 21 +-- ZooBOTanica/CritCreate.cs | 11 +- ZooBOTanica/Program.cs | 5 +- ZooBOTanica/Properties/AssemblyInfo.cs | 1 - 84 files changed, 947 insertions(+), 932 deletions(-) (limited to 'FireBase') diff --git a/DSACore/Auxiliary/Calculator/Argument.cs b/DSACore/Auxiliary/Calculator/Argument.cs index 14982aa..5ed9ee3 100644 --- a/DSACore/Auxiliary/Calculator/Argument.cs +++ b/DSACore/Auxiliary/Calculator/Argument.cs @@ -1,9 +1,9 @@ -namespace DSACore.Auxiliary.Calculator -{ - using System; +using System; +namespace DSACore.Auxiliary.Calculator +{ /// - /// 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. /// public class Argument : ISolvable { diff --git a/DSACore/Auxiliary/Calculator/ISolvable.cs b/DSACore/Auxiliary/Calculator/ISolvable.cs index 2acbd11..7be4d19 100644 --- a/DSACore/Auxiliary/Calculator/ISolvable.cs +++ b/DSACore/Auxiliary/Calculator/ISolvable.cs @@ -1,7 +1,7 @@ namespace DSACore.Auxiliary.Calculator { /// - /// 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 /// public interface ISolvable { diff --git a/DSACore/Auxiliary/Calculator/Operator.cs b/DSACore/Auxiliary/Calculator/Operator.cs index ed46186..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 { /// - /// 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 /// public class Operator : ISolvable { diff --git a/DSACore/Auxiliary/Calculator/Ops.cs b/DSACore/Auxiliary/Calculator/Ops.cs index c804257..a5c9a2d 100644 --- a/DSACore/Auxiliary/Calculator/Ops.cs +++ b/DSACore/Auxiliary/Calculator/Ops.cs @@ -1,7 +1,7 @@ namespace DSACorev.Auxiliary.Calculator { /// - /// The Different Operations, witch can be performed in execution-order + /// The Different Operations, witch can be performed in execution-order /// public enum Ops { diff --git a/DSACore/Auxiliary/Calculator/StringSolver.cs b/DSACore/Auxiliary/Calculator/StringSolver.cs index 212f812..b2a7d83 100644 --- a/DSACore/Auxiliary/Calculator/StringSolver.cs +++ b/DSACore/Auxiliary/Calculator/StringSolver.cs @@ -5,28 +5,20 @@ using DSACorev.Auxiliary.Calculator; namespace DSACore.Auxiliary.Calculator { - using System; - using System.Collections.Generic; - using System.Linq; - /// - /// 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 /// public class StringSolver : ISolvable { - private readonly string input; private readonly List arguments = new List(); + private readonly string input; public StringSolver(string input) { this.input = input; } - public override string ToString() - { - return "(0+" + input.Replace(" ", string.Empty).ToLower() + ")"; - } - public int Solve() { var workInput = "0+" + input.Replace(" ", string.Empty).ToLower(); @@ -42,6 +34,11 @@ namespace DSACore.Auxiliary.Calculator return ((ISolvable) arguments.First()).Solve(); } + public override string ToString() + { + 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 { @@ -123,7 +120,7 @@ namespace DSACore.Auxiliary.Calculator switch (c) { case ')': - throw new ArgumentException($"Unmögliche Anordnung von Klammern"); + throw new ArgumentException("Unmögliche Anordnung von Klammern"); case '(': arguments.Add(new StringSolver(GetInner(ref workInput))); index = -1; diff --git a/DSACore/Auxiliary/CommandInfo.cs b/DSACore/Auxiliary/CommandInfo.cs index 9afe6c0..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 { diff --git a/DSACore/Auxiliary/SpellCorrect.cs b/DSACore/Auxiliary/SpellCorrect.cs index 3ef7bb6..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; diff --git a/DSACore/Auxiliary/TalentEnumerableExtension.cs b/DSACore/Auxiliary/TalentEnumerableExtension.cs index 159480d..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 diff --git a/DSACore/Auxiliary/WeaponImporter.cs b/DSACore/Auxiliary/WeaponImporter.cs index ab51efb..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,14 +6,13 @@ 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 Weapons = new List(); - private List Range = new List(); + private readonly List Range = new List(); + private readonly List Weapons = new List(); public async Task DownloadWeapons() { @@ -48,7 +46,7 @@ namespace DSACore.Auxiliary { var talent = lines[j]; - var values = await client.GetStringAsync($"http://diarium.eu/dsa4-forge/ajax/calculate/" + i + "/" + + 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", "")); diff --git a/DSACore/Commands/CommandHandler.cs b/DSACore/Commands/CommandHandler.cs index 6879045..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 @@ -49,7 +49,7 @@ 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); diff --git a/DSACore/Commands/FileHandler.cs b/DSACore/Commands/FileHandler.cs index d8fb585..bce7c54 100644 --- a/DSACore/Commands/FileHandler.cs +++ b/DSACore/Commands/FileHandler.cs @@ -1,13 +1,12 @@ -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) diff --git a/DSACore/Commands/Gm.cs b/DSACore/Commands/Gm.cs index 59b3129..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 { diff --git a/DSACore/Commands/HeldList.cs b/DSACore/Commands/HeldList.cs index 73861b7..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 { diff --git a/DSACore/Commands/Help.cs b/DSACore/Commands/Help.cs index 6458c20..974c44c 100644 --- a/DSACore/Commands/Help.cs +++ b/DSACore/Commands/Help.cs @@ -1,39 +1,18 @@ 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>(reader); // Deserialize Data and create CommandInfo Struct - - Commands.AddRange(test); // Add new CommandInfos to List - } - catch (Exception e) - { - // ignored - }*/ - } - //public static List Commands { get; } = new List(); public static string Get_Specific_Help(string command) { // return command specific help - var com = DSA_Game.Save.Properties.CommandInfos + var com = Properties.CommandInfos .OrderBy(x => SpellCorrect.CompareEasy(x.Name, command.ToLower())).First(); // get best fit command return com.GetDescription(); } @@ -41,7 +20,7 @@ namespace DSACore.Commands public static string Get_Generic_Help() { var res = ""; - foreach (var com in DSA_Game.Save.Properties.CommandInfos) + foreach (var com in Properties.CommandInfos) { var first_column_width = 8; res += ("!" + com.Name + ": ").AddSpaces(first_column_width) + com.Brief; diff --git a/DSACore/Commands/LebenUndAstral.cs b/DSACore/Commands/LebenUndAstral.cs index 7e0cb5c..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 diff --git a/DSACore/Commands/List.cs b/DSACore/Commands/List.cs index 2c8f3d0..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 { diff --git a/DSACore/Commands/MiscCommands.cs b/DSACore/Commands/MiscCommands.cs index 36d5fb1..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 { diff --git a/DSACore/Commands/NpcCommands.cs b/DSACore/Commands/NpcCommands.cs index 9a27e6a..95243ca 100644 --- a/DSACore/Commands/NpcCommands.cs +++ b/DSACore/Commands/NpcCommands.cs @@ -1,12 +1,9 @@ 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 { diff --git a/DSACore/Controllers/CommandsController.cs b/DSACore/Controllers/CommandsController.cs index e9700ff..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; @@ -33,7 +30,7 @@ namespace DSACore.Controllers { try { - return Commands.CommandHandler.ExecuteCommand(cmd).message; + return CommandHandler.ExecuteCommand(cmd).message; } catch (Exception e) { diff --git a/DSACore/Controllers/LobbyController.cs b/DSACore/Controllers/LobbyController.cs index 100fb5b..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 @@ -19,7 +20,7 @@ namespace DSACore.Controllers { try { - return Commands.CommandHandler.ExecuteCommand(cmd).message; + return CommandHandler.ExecuteCommand(cmd).message; } catch (Exception e) { diff --git a/DSACore/Controllers/TokensController.cs b/DSACore/Controllers/TokensController.cs index 6a59db4..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 @@ -10,13 +11,15 @@ namespace DSACore.Controllers [HttpGet("{token}")] public ActionResult 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 62d2e11..ac890cb 100644 --- a/DSACore/DSA_Game/Characters/Character.cs +++ b/DSACore/DSA_Game/Characters/Character.cs @@ -1,17 +1,15 @@ -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() diff --git a/DSACore/DSA_Game/Characters/NPC.cs b/DSACore/DSA_Game/Characters/NPC.cs index e6b7bed..75c3fe9 100644 --- a/DSACore/DSA_Game/Characters/NPC.cs +++ b/DSACore/DSA_Game/Characters/NPC.cs @@ -4,10 +4,6 @@ using DSALib.Characters; namespace DSACore.Characters { - using System; - using Auxiliary; - using DSACore.DSA_Game.Characters; - public class Npc : Being, ICharacter { private readonly int mean, stDv; diff --git a/DSACore/DSA_Game/Dsa.cs b/DSACore/DSA_Game/Dsa.cs index f2ffe48..18d0b81 100644 --- a/DSACore/DSA_Game/Dsa.cs +++ b/DSACore/DSA_Game/Dsa.cs @@ -1,18 +1,13 @@ 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 Characters; - using Save; - public static class Dsa { #if DEBUG @@ -59,7 +54,7 @@ namespace DSACore.DSA_Game } */ - Properties.Deserialize(rootPath + "Properties"); + Properties.Deserialize(); Properties.Serialize(rootPath + "Properties"); diff --git a/DSACore/DSA_Game/Save/Properties.cs b/DSACore/DSA_Game/Save/Properties.cs index 50bd8fa..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 objects; @@ -64,7 +61,7 @@ namespace DSACore.DSA_Game.Save foreach (var o in objects) { var assembly = o.Value is IList list - ? ((IList) list)[0]?.GetType().FullName + ? list[0]?.GetType().FullName : o.Value.GetType().FullName; var name = path + assembly.Replace('.', '-') + ".json"; @@ -76,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 80d4426..f358047 100644 --- a/DSACore/DSA_Game/Save/SaveCommand.cs +++ b/DSACore/DSA_Game/Save/SaveCommand.cs @@ -1,18 +1,16 @@ using System; +using System.IO; using System.Linq; -using System.Threading.Tasks; namespace DSACore.DSA_Game.Save { - using System.IO; - public class SaveCommand { public void LoadSession(string name = "") { if (name.Equals("?") || name.Equals(string.Empty)) { - Console.WriteLine($"Gespeicherte Sessions:"); + Console.WriteLine("Gespeicherte Sessions:"); Console.WriteLine(ListSessions()); return; } @@ -32,7 +30,7 @@ namespace DSACore.DSA_Game.Save if (name.Equals("?") || name.Equals(string.Empty)) { - Console.WriteLine($"Gespeicherte Sessions:"); + Console.WriteLine("Gespeicherte Sessions:"); Console.WriteLine(ListSessions()); return; } @@ -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"); diff --git a/DSACore/DSA_Game/Save/Session.cs b/DSACore/DSA_Game/Save/Session.cs index 595f0e8..6944fb1 100644 --- a/DSACore/DSA_Game/Save/Session.cs +++ b/DSACore/DSA_Game/Save/Session.cs @@ -1,12 +1,11 @@ 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"; diff --git a/DSACore/FireBase/Database.cs b/DSACore/FireBase/Database.cs index abe2b92..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,19 @@ namespace DSACore.FireBase { public static FirebaseClient firebase; + public static Dictionary Chars = new Dictionary(); + + public static Dictionary MeleeList = new Dictionary(); + + public static Dictionary RangedWeapons = new Dictionary(); + + public static Dictionary Talents = new Dictionary(); + + public static Dictionary Spells = new Dictionary(); + static Database() { - var auth = File.ReadAllText(DSA_Game.Dsa.rootPath + "Token"); + var auth = File.ReadAllText(Dsa.rootPath + "Token"); ; // your app secret firebase = new FirebaseClient( "https://heldenonline-4d828.firebaseio.com/", @@ -49,17 +58,7 @@ namespace DSACore.FireBase foreach (var firebaseObject in temp) list.Add(firebaseObject.Key, firebaseObject.Object); } - public static Dictionary Chars = new Dictionary(); - - public static Dictionary MeleeList = new Dictionary(); - - public static Dictionary RangedWeapons = new Dictionary(); - - public static Dictionary Talents = new Dictionary(); - - public static Dictionary Spells = new Dictionary(); - - public static async Task AddChar(Character file, Models.Network.Group group) + public static async Task AddChar(Character file, Group group) { DatabaseChar.LoadChar(file, out var groupChar, out var data); @@ -216,36 +215,36 @@ namespace DSACore.FireBase .OnceSingleAsync(); } - public static async Task> GetGroups() + public static async Task> GetGroups() { var groups = await firebase .Child("Groups") .OrderByKey() - .OnceAsync(); - var ret = new List(); + .OnceAsync(); + var ret = new List(); 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 GetGroup(int id) + public static async Task GetGroup(int id) { var group = await firebase .Child("Groups") .Child("Group" + id) - .OnceSingleAsync(); + .OnceSingleAsync(); return group; } - public static async Task AddGroup(Group group) + public static async Task AddGroup(Models.Database.Groups.Group group) { var lastChar = await firebase .Child("Groups") .OrderByKey() .LimitToLast(1) - .OnceAsync(); + .OnceAsync(); var id = group.Id = lastChar.First().Object.Id + 1; await firebase @@ -254,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") diff --git a/DSACore/Hubs/Login.cs b/DSACore/Hubs/Login.cs index f589e49..1f6ca39 100644 --- a/DSACore/Hubs/Login.cs +++ b/DSACore/Hubs/Login.cs @@ -1,14 +1,14 @@ -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 { @@ -18,9 +18,6 @@ namespace DSACore.Hubs private const string ReceiveMethod = "ReceiveMessage"; //receiveMethod; - private static List DsaGroups { get; set; } - public static List Tokens { get; } = new List(); - static Users() { DsaGroups = Database.GetGroups().Result; @@ -29,6 +26,9 @@ namespace DSACore.Hubs //AddGroups(); } + private static List DsaGroups { get; } + public static List Tokens { get; } = new List(); + [Obsolete] private static async void AddGroups() @@ -60,7 +60,7 @@ namespace DSACore.Hubs var ident = args.First().Replace("/", ""); if (args.Count > 0) args.RemoveAt(0); - var ret = Commands.CommandHandler.ExecuteCommand(new Command + var ret = CommandHandler.ExecuteCommand(new Command { CharId = 0, CmdIdentifier = ident, @@ -116,8 +116,8 @@ namespace DSACore.Hubs var test = await Database.GetGroups(); foreach (var group in test) - if (!DsaGroups.Exists(x => x.Name.Equals(@group.Name))) - DsaGroups.Add(@group); + if (!DsaGroups.Exists(x => x.Name.Equals(group.Name))) + DsaGroups.Add(group); await Clients.Caller.SendCoreAsync("ListGroups", new object[] {DsaGroups.Select(x => x.SendGroup())}); //throw new NotImplementedException("add database call to get groups"); @@ -128,7 +128,7 @@ namespace DSACore.Hubs DsaGroups.Add(new Group(group, password)); 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"); } @@ -202,8 +202,8 @@ namespace DSACore.Hubs 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); + group.Users.Remove(user); + await Groups.RemoveFromGroupAsync(Context.ConnectionId, group.Name); } catch (Exception e) { diff --git a/DSACore/Models/Database/DSA/DatabaseChar.cs b/DSACore/Models/Database/DSA/DatabaseChar.cs index 6a57629..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 { @@ -40,7 +41,7 @@ namespace DSACore.Models.Database.DSA public List WeaponTalents { get; set; } = new List(); - 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(); diff --git a/DSACore/Models/Database/DSA/Weapon.cs b/DSACore/Models/Database/DSA/Weapon.cs index d6d7999..58a44cd 100644 --- a/DSACore/Models/Database/DSA/Weapon.cs +++ b/DSACore/Models/Database/DSA/Weapon.cs @@ -26,27 +26,27 @@ namespace DSACore.Models.Database.DSA public class MeleeWeapon : Weapon { - 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 string TpKK { get; set; } + public int INI { get; set; } + public string MW { get; set; } } 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/Network/Command.cs b/DSACore/Models/Network/Command.cs index 316461e..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 { diff --git a/DSACore/Models/Network/CommandResponse.cs b/DSACore/Models/Network/CommandResponse.cs index 7478397..c7a410a 100644 --- a/DSACore/Models/Network/CommandResponse.cs +++ b/DSACore/Models/Network/CommandResponse.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; namespace DSACore.Models.Network { @@ -13,8 +10,8 @@ namespace DSACore.Models.Network 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() { diff --git a/DSACore/Models/Network/Group.cs b/DSACore/Models/Network/Group.cs index 3a8ce77..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 { 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 97a9224..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 { diff --git a/DSACore/Program.cs b/DSACore/Program.cs index 357f919..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,7 +10,7 @@ namespace DSACore public static void Main(string[] args) { Database.GetGroup(0).Wait(); - DSA_Game.Dsa.Startup(); + Dsa.Startup(); CreateWebHostBuilder(args).Build().Run(); } diff --git a/DSACore/Startup.cs b/DSACore/Startup.cs index 6f3ec79..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 { diff --git a/DSALib/Characters/Being.cs b/DSALib/Characters/Being.cs index cf338f9..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 { diff --git a/DSALib/Characters/Critter.cs b/DSALib/Characters/Critter.cs index c511090..d9f8b53 100644 --- a/DSALib/Characters/Critter.cs +++ b/DSALib/Characters/Critter.cs @@ -1,14 +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; - using DiscoBot.DSA_Game.Characters; - using Newtonsoft.Json; - public class Critter : Being, ICombatant { + public CritterAttack lastAttack; + + public Critter(int gw, int gs, int rs, int mr, int ko, int pa, string ini, List critterAttacks) + { + Gw = gw; + Gs = gs; + Rs = rs; + Mr = mr; + Ko = ko; + Pa = pa; + Ini = ini; + CritterAttacks = critterAttacks; + lastAttack = CritterAttacks[new Random().Next(critterAttacks.Count)]; + } + + public Critter() + { + } + public int Rs { get; set; } public int Mr { get; set; } @@ -27,23 +45,14 @@ namespace DSALib.Characters public List CritterAttacks { get; set; } - public CritterAttack lastAttack; - - public Critter(int gw, int gs, int rs, int mr, int ko, int pa, string ini, List critterAttacks) + public string Angriff(string talent, int erschwernis = 0) { - Gw = gw; - Gs = gs; - Rs = rs; - Mr = mr; - Ko = ko; - Pa = pa; - Ini = ini; - CritterAttacks = critterAttacks; - lastAttack = 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) @@ -61,16 +70,6 @@ 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 diff --git a/DSALib/Characters/ICombatant.cs b/DSALib/Characters/ICombatant.cs index 887893c..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 { diff --git a/DSALib/CritterAttack.cs b/DSALib/CritterAttack.cs index 5fdcffa..3b0a11d 100644 --- a/DSALib/CritterAttack.cs +++ b/DSALib/CritterAttack.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace DSALib +namespace DSALib { public class CritterAttack { diff --git a/FireBase/ExceptionEventArgs.cs b/FireBase/ExceptionEventArgs.cs index 185c952..09c205a 100644 --- a/FireBase/ExceptionEventArgs.cs +++ b/FireBase/ExceptionEventArgs.cs @@ -1,16 +1,16 @@ -namespace Firebase.Database -{ - using System; +using System; +namespace Firebase.Database +{ /// - /// Event args holding the object. + /// Event args holding the object. /// public class ExceptionEventArgs : EventArgs where T : Exception { public readonly T Exception; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The exception. public ExceptionEventArgs(T exception) diff --git a/FireBase/Extensions/ObservableExtensions.cs b/FireBase/Extensions/ObservableExtensions.cs index cb41bcc..0a672d7 100644 --- a/FireBase/Extensions/ObservableExtensions.cs +++ b/FireBase/Extensions/ObservableExtensions.cs @@ -1,19 +1,20 @@ -namespace Firebase.Database.Extensions -{ - using System; - using System.Reactive.Linq; +using System; +using System.Reactive.Linq; +namespace Firebase.Database.Extensions +{ public static class ObservableExtensions { /// - /// Returns a cold observable which retries (re-subscribes to) the source observable on error until it successfully terminates. + /// Returns a cold observable which retries (re-subscribes to) the source observable on error until it successfully + /// terminates. /// /// The source observable. /// How long to wait between attempts. /// A predicate determining for which exceptions to retry. Defaults to all /// - /// 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. /// public static IObservable RetryAfterDelay( this IObservable source, diff --git a/FireBase/Extensions/TaskExtensions.cs b/FireBase/Extensions/TaskExtensions.cs index 8e933b2..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 { /// - /// Instead of unwrapping it throws it as it is. + /// Instead of unwrapping it throws it as it is. /// public static async Task WithAggregateException(this Task source) { diff --git a/FireBase/FirebaseClient.cs b/FireBase/FirebaseClient.cs index 8795668..3079f3b 100644 --- a/FireBase/FirebaseClient.cs +++ b/FireBase/FirebaseClient.cs @@ -1,30 +1,26 @@ +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 Offline; - using Query; - /// - /// Firebase client which acts as an entry point to the online database. + /// Firebase client which acts as an entry point to the online database. /// public class FirebaseClient : IDisposable { + private readonly string baseUrl; internal readonly HttpClient HttpClient; internal readonly FirebaseOptions Options; - private readonly string baseUrl; - /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The base url. - /// Offline database. + /// Offline database. public FirebaseClient(string baseUrl, FirebaseOptions options = null) { HttpClient = new HttpClient(); @@ -35,19 +31,19 @@ namespace Firebase.Database if (!this.baseUrl.EndsWith("/")) this.baseUrl += "/"; } + public void Dispose() + { + HttpClient?.Dispose(); + } + /// - /// Queries for a child of the data root. + /// Queries for a child of the data root. /// /// Name of the child. - /// . + /// . public ChildQuery Child(string resourceName) { return new ChildQuery(this, () => baseUrl + resourceName); } - - public void Dispose() - { - HttpClient?.Dispose(); - } } } \ No newline at end of file diff --git a/FireBase/FirebaseException.cs b/FireBase/FirebaseException.cs index 2f8269d..cfc09d3 100644 --- a/FireBase/FirebaseException.cs +++ b/FireBase/FirebaseException.cs @@ -1,8 +1,8 @@ -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) @@ -25,22 +25,22 @@ } /// - /// Post data passed to the authentication service. + /// Post data passed to the authentication service. /// public string RequestData { get; } /// - /// Original url of the request. + /// Original url of the request. /// public string RequestUrl { get; } /// - /// Response from the authentication service. + /// Response from the authentication service. /// public string ResponseData { get; } /// - /// Status code of the response. + /// Status code of the response. /// public HttpStatusCode StatusCode { get; } diff --git a/FireBase/FirebaseKeyGenerator.cs b/FireBase/FirebaseKeyGenerator.cs index 70a855d..37beed5 100644 --- a/FireBase/FirebaseKeyGenerator.cs +++ b/FireBase/FirebaseKeyGenerator.cs @@ -1,11 +1,11 @@ +using System; +using System.Text; + namespace Firebase.Database { - using System; - using System.Text; - /// - /// 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 /// public class FirebaseKeyGenerator { @@ -26,10 +26,11 @@ namespace Firebase.Database } /// - /// Returns next firebase key based on current time. + /// Returns next firebase key based on current time. /// /// - /// The . + /// The . + /// public static string Next() { // We generate 72-bits of randomness which get turned into 12 characters and diff --git a/FireBase/FirebaseObject.cs b/FireBase/FirebaseObject.cs index 653d508..2e0fd20 100644 --- a/FireBase/FirebaseObject.cs +++ b/FireBase/FirebaseObject.cs @@ -1,9 +1,11 @@ namespace Firebase.Database { /// - /// Holds the object of type along with its key. + /// Holds the object of type + /// + /// along with its key. /// - /// Type of the underlying object. + /// Type of the underlying object. public class FirebaseObject { internal FirebaseObject(string key, T obj) @@ -13,12 +15,12 @@ namespace Firebase.Database } /// - /// Gets the key of . + /// Gets the key of . /// public string Key { get; } /// - /// Gets the underlying object. + /// Gets the underlying object. /// public T Object { get; } } diff --git a/FireBase/FirebaseOptions.cs b/FireBase/FirebaseOptions.cs index f31a047..b4a5e51 100644 --- a/FireBase/FirebaseOptions.cs +++ b/FireBase/FirebaseOptions.cs @@ -1,12 +1,12 @@ -namespace Firebase.Database -{ - using System; - using System.Collections.Generic; - using System.IO; - using System.Threading.Tasks; - using Offline; - using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; +using Firebase.Database.Offline; +using Newtonsoft.Json; +namespace Firebase.Database +{ public class FirebaseOptions { public FirebaseOptions() @@ -18,32 +18,34 @@ } /// - /// 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. /// public Func> OfflineDatabaseFactory { get; set; } /// - /// Gets or sets the method for retrieving auth tokens. Default is null. + /// Gets or sets the method for retrieving auth tokens. Default is null. /// public Func> AuthTokenAsyncFactory { get; set; } /// - /// Gets or sets the factory for used for reading online streams. Default is . + /// Gets or sets the factory for used for reading online streams. Default is + /// . /// public Func SubscriptionStreamReaderFactory { get; set; } /// - /// Gets or sets the json serializer settings. + /// Gets or sets the json serializer settings. /// public JsonSerializerSettings JsonSerializerSettings { get; set; } /// - /// 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. /// public TimeSpan SyncPeriod { get; set; } /// - /// 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". /// public bool AsAccessToken { get; set; } } diff --git a/FireBase/Http/HttpClientExtensions.cs b/FireBase/Http/HttpClientExtensions.cs index 7f8fffe..6582769 100644 --- a/FireBase/Http/HttpClientExtensions.cs +++ b/FireBase/Http/HttpClientExtensions.cs @@ -1,27 +1,27 @@ +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; - /// - /// The http client extensions for object deserializations. + /// The http client extensions for object deserializations. /// internal static class HttpClientExtensions { /// - /// The get object collection async. + /// The get object collection async. /// /// The client. - /// The request uri. - /// The specific JSON Serializer Settings. + /// The request uri. + /// The specific JSON Serializer Settings. /// The type of entities the collection should contain. - /// The . + /// The . public static async Task>> GetObjectCollectionAsync( this HttpClient client, string requestUri, JsonSerializerSettings jsonSerializerSettings) @@ -91,11 +91,11 @@ namespace Firebase.Database.Http }*/ /// - /// The get object collection async. + /// The get object collection async. /// /// The json data. /// The type of entities the collection should contain. - /// The . + /// The . public static IEnumerable> GetObjectCollection(this string data, Type elementType) { var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), elementType); diff --git a/FireBase/Http/PostResult.cs b/FireBase/Http/PostResult.cs index 5a779ed..15a4894 100644 --- a/FireBase/Http/PostResult.cs +++ b/FireBase/Http/PostResult.cs @@ -1,12 +1,12 @@ namespace Firebase.Database.Http { /// - /// Represents data returned after a successful POST to firebase server. + /// Represents data returned after a successful POST to firebase server. /// public class PostResult { /// - /// Gets or sets the generated key after a successful post. + /// Gets or sets the generated key after a successful post. /// public string Name { get; set; } } diff --git a/FireBase/ObservableExtensions.cs b/FireBase/ObservableExtensions.cs index da78365..bc46261 100644 --- a/FireBase/ObservableExtensions.cs +++ b/FireBase/ObservableExtensions.cs @@ -1,20 +1,20 @@ -namespace Firebase.Database -{ - using System; - using System.Collections.ObjectModel; - using Streaming; +using System; +using System.Collections.ObjectModel; +using Firebase.Database.Streaming; +namespace Firebase.Database +{ /// - /// Extensions for . + /// Extensions for . /// public static class ObservableExtensions { /// - /// Starts observing on given firebase observable and propagates event into an . + /// Starts observing on given firebase observable and propagates event into an . /// /// The observable. /// Type of entity. - /// The . + /// The . public static ObservableCollection AsObservableCollection(this IObservable> observable) { var collection = new ObservableCollection(); diff --git a/FireBase/Offline/ConcurrentOfflineDatabase.cs b/FireBase/Offline/ConcurrentOfflineDatabase.cs index 5527168..1a9e607 100644 --- a/FireBase/Offline/ConcurrentOfflineDatabase.cs +++ b/FireBase/Offline/ConcurrentOfflineDatabase.cs @@ -1,23 +1,23 @@ -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; - /// - /// The offline database. + /// The offline database. /// public class ConcurrentOfflineDatabase : IDictionary { - private readonly LiteRepository db; private readonly ConcurrentDictionary ccache; + private readonly LiteRepository db; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The item type which is used to determine the database file name. /// Custom string which will get appended to the file name. @@ -43,33 +43,41 @@ } /// - /// Gets the number of elements contained in the . + /// Gets the number of elements contained in the . /// - /// The number of elements contained in the . + /// The number of elements contained in the . public int Count => ccache.Count; /// - /// Gets a value indicating whether this is a read-only collection. + /// Gets a value indicating whether this is a read-only collection. /// public bool IsReadOnly => false; /// - /// Gets an containing the keys of the . + /// Gets an containing the keys of the + /// . /// - /// An containing the keys of the object that implements . + /// + /// An containing the keys of the object that + /// implements . + /// public ICollection Keys => ccache.Keys; /// - /// Gets an containing the values in the . + /// Gets an containing the values in the + /// . /// - /// An containing the values in the object that implements . + /// + /// An containing the values in the object that + /// implements . + /// public ICollection Values => ccache.Values; /// - /// Gets or sets the element with the specified key. + /// Gets or sets the element with the specified key. /// /// The key of the element to get or set. - /// The element with the specified key. + /// The element with the specified key. public OfflineEntry this[string key] { get => ccache[key]; @@ -82,7 +90,7 @@ } /// - /// Returns an enumerator that iterates through the collection. + /// Returns an enumerator that iterates through the collection. /// /// An enumerator that can be used to iterate through the collection. public IEnumerator> GetEnumerator() @@ -96,65 +104,82 @@ } /// - /// Adds an item to the . + /// Adds an item to the . /// - /// The object to add to the . + /// The object to add to the . public void Add(KeyValuePair item) { Add(item.Key, item.Value); } /// - /// Removes all items from the . - /// + /// Removes all items from the . + /// public void Clear() { ccache.Clear(); - db.Delete(Query.All()); + db.Delete(LiteDB.Query.All()); } /// - /// Determines whether the contains a specific value. + /// Determines whether the contains a specific value. /// - /// The object to locate in the . - /// True if is found in the ; otherwise, false. + /// The object to locate in the . + /// + /// True if is found in the ; + /// otherwise, false. + /// public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } /// - /// Copies the elements of the to an , starting at a particular index. + /// Copies the elements of the to an + /// , starting at a particular index. /// - /// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing. - /// The zero-based index in at which copying begins. + /// + /// The one-dimensional that is the destination of the elements copied + /// from . The must have + /// zero-based indexing. + /// + /// The zero-based index in at which copying begins. public void CopyTo(KeyValuePair[] array, int arrayIndex) { ccache.ToList().CopyTo(array, arrayIndex); } /// - /// Removes the first occurrence of a specific object from the . + /// Removes the first occurrence of a specific object from the + /// . /// - /// The object to remove from the . - /// True if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . + /// The object to remove from the . + /// + /// True if was successfully removed from the + /// ; otherwise, false. This method also returns false if + /// is not found in the original . + /// public bool Remove(KeyValuePair item) { return Remove(item.Key); } /// - /// Determines whether the contains an element with the specified key. + /// Determines whether the contains an element with the + /// specified key. /// - /// The key to locate in the . - /// True if the contains an element with the key; otherwise, false. + /// The key to locate in the . + /// + /// True if the contains an element with the key; + /// otherwise, false. + /// public bool ContainsKey(string key) { return ccache.ContainsKey(key); } /// - /// Adds an element with the provided key and value to the . + /// Adds an element with the provided key and value to the . /// /// The object to use as the key of the element to add. /// The object to use as the value of the element to add. @@ -165,10 +190,13 @@ } /// - /// Removes the element with the specified key from the . + /// Removes the element with the specified key from the . /// /// The key of the element to remove. - /// True if the element is successfully removed; otherwise, false. This method also returns false if was not found in the original . + /// + /// True if the element is successfully removed; otherwise, false. This method also returns false if + /// was not found in the original . + /// public bool Remove(string key) { ccache.TryRemove(key, out _); @@ -176,10 +204,18 @@ } /// - /// Gets the value associated with the specified key. - /// - /// The key whose value to get.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 parameter. This parameter is passed uninitialized. - /// True if the object that implements contains an element with the specified key; otherwise, false. + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// + /// 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 parameter. This parameter is passed + /// uninitialized. + /// + /// + /// True if the object that implements contains an + /// element with the specified key; otherwise, false. + /// public bool TryGetValue(string key, out OfflineEntry value) { return ccache.TryGetValue(key, out value); diff --git a/FireBase/Offline/DatabaseExtensions.cs b/FireBase/Offline/DatabaseExtensions.cs index 56dcf46..e7c4074 100644 --- a/FireBase/Offline/DatabaseExtensions.cs +++ b/FireBase/Offline/DatabaseExtensions.cs @@ -1,24 +1,26 @@ -namespace Firebase.Database.Offline -{ - using System; - using System.Collections; - using System.Collections.Generic; - using System.Linq.Expressions; - using System.Reflection; - using 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 { /// - /// Create new instances of the . + /// Create new instances of the . /// /// Type of elements. /// Custom string which will get appended to the file name. /// Optional custom root element of received json items. - /// Realtime streaming options. + /// Realtime streaming options. /// Specifies what strategy should be used for initial pulling of server data. - /// Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. - /// The . + /// + /// Specifies whether changed items should actually be pushed to the server. It this is false, + /// then Put / Post / Delete will not affect server data. + /// + /// The . public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) @@ -29,16 +31,19 @@ } /// - /// Create new instances of the . + /// Create new instances of the . /// /// Type of elements. - /// Type of the custom to use. + /// Type of the custom to use. /// Custom string which will get appended to the file name. /// Optional custom root element of received json items. - /// Realtime streaming options. + /// Realtime streaming options. /// Specifies what strategy should be used for initial pulling of server data. - /// Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. - /// The . + /// + /// Specifies whether changed items should actually be pushed to the server. It this is false, + /// then Put / Post / Delete will not affect server data. + /// + /// The . public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, @@ -52,12 +57,15 @@ } /// - /// 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. /// /// The key. /// The object to set. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Patch(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) where T : class @@ -66,12 +74,15 @@ } /// - /// Overwrites existing object with given key. + /// Overwrites existing object with given key. /// /// The key. /// The object to set. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Put(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) where T : class @@ -80,11 +91,14 @@ } /// - /// Adds a new entity to the Database. + /// Adds a new entity to the Database. /// /// The object to add. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// /// The generated key for this object. public static string Post(this RealtimeDatabase db, T obj, bool syncOnline = true, int priority = 1) where T : class @@ -97,11 +111,14 @@ } /// - /// Deletes the entity with the given key. + /// Deletes the entity with the given key. /// /// The key. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Delete(this RealtimeDatabase db, string key, bool syncOnline = true, int priority = 1) where T : class { @@ -109,7 +126,8 @@ } /// - /// Do a Put for a nested property specified by of an object with key . + /// Do a Put for a nested property specified by of an object with key + /// . /// /// Type of the root elements. /// Type of the property being modified @@ -118,7 +136,10 @@ /// Expression on the root element leading to target value to modify. /// Value to put. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Put(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) @@ -128,7 +149,8 @@ } /// - /// Do a Patch for a nested property specified by of an object with key . + /// Do a Patch for a nested property specified by of an object with key + /// . /// /// Type of the root elements. /// Type of the property being modified @@ -137,7 +159,10 @@ /// Expression on the root element leading to target value to modify. /// Value to patch. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Patch(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) @@ -147,7 +172,8 @@ } /// - /// Delete a nested property specified by of an object with key . This basically does a Put with null value. + /// Delete a nested property specified by of an object with key + /// . This basically does a Put with null value. /// /// Type of the root elements. /// Type of the property being modified @@ -156,7 +182,10 @@ /// Expression on the root element leading to target value to modify. /// Value to put. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Delete(this RealtimeDatabase db, string key, Expression> propertyExpression, bool syncOnline = true, int priority = 1) where T : class @@ -166,8 +195,9 @@ } /// - /// Post a new entity into the nested dictionary specified by of an object with key . - /// The key of the new entity is automatically generated. + /// Post a new entity into the nested dictionary specified by of an object with + /// key . + /// The key of the new entity is automatically generated. /// /// Type of the root elements. /// Type of the dictionary being modified @@ -177,7 +207,10 @@ /// Expression on the root element leading to target value to modify. /// Value to put. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Post(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) @@ -193,8 +226,9 @@ } /// - /// Delete an entity with key in the nested dictionary specified by of an object with key . - /// The key of the new entity is automatically generated. + /// Delete an entity with key in the nested dictionary specified by + /// of an object with key . + /// The key of the new entity is automatically generated. /// /// Type of the root elements. /// Type of the dictionary being modified @@ -204,7 +238,10 @@ /// Expression on the root element leading to target value to modify. /// Key within the nested dictionary to delete. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public static void Delete(this RealtimeDatabase db, string key, Expression>> propertyExpression, string dictionaryKey, bool syncOnline = true, int priority = 1) diff --git a/FireBase/Offline/ISetHandler.cs b/FireBase/Offline/ISetHandler.cs index e3b49b5..c04bd41 100644 --- a/FireBase/Offline/ISetHandler.cs +++ b/FireBase/Offline/ISetHandler.cs @@ -1,8 +1,8 @@ -namespace Firebase.Database.Offline -{ - using Query; - using System.Threading.Tasks; +using System.Threading.Tasks; +using Firebase.Database.Query; +namespace Firebase.Database.Offline +{ public interface ISetHandler { Task SetAsync(ChildQuery query, string key, OfflineEntry entry); diff --git a/FireBase/Offline/InitialPullStrategy.cs b/FireBase/Offline/InitialPullStrategy.cs index a1ae3f7..ca2bebf 100644 --- a/FireBase/Offline/InitialPullStrategy.cs +++ b/FireBase/Offline/InitialPullStrategy.cs @@ -1,23 +1,23 @@ namespace Firebase.Database.Offline { /// - /// Specifies the strategy for initial pull of server data. + /// Specifies the strategy for initial pull of server data. /// public enum InitialPullStrategy { /// - /// Don't pull anything. + /// Don't pull anything. /// None, /// - /// Pull only what isn't already stored offline. + /// Pull only what isn't already stored offline. /// MissingOnly, /// - /// Pull everything that exists on the server. + /// Pull everything that exists on the server. /// - Everything, + Everything } } \ No newline at end of file diff --git a/FireBase/Offline/Internals/MemberAccessVisitor.cs b/FireBase/Offline/Internals/MemberAccessVisitor.cs index 2bc0fc3..89a77da 100644 --- a/FireBase/Offline/Internals/MemberAccessVisitor.cs +++ b/FireBase/Offline/Internals/MemberAccessVisitor.cs @@ -1,10 +1,10 @@ -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 propertyNames = new List(); @@ -13,10 +13,6 @@ public IEnumerable PropertyNames => propertyNames; - public MemberAccessVisitor() - { - } - public override Expression Visit(Expression expr) { if (expr?.NodeType == ExpressionType.MemberAccess) diff --git a/FireBase/Offline/OfflineCacheAdapter.cs b/FireBase/Offline/OfflineCacheAdapter.cs index 0918a8c..3153d1b 100644 --- a/FireBase/Offline/OfflineCacheAdapter.cs +++ b/FireBase/Offline/OfflineCacheAdapter.cs @@ -1,10 +1,10 @@ -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; +namespace Firebase.Database.Offline +{ internal class OfflineCacheAdapter : IDictionary, IDictionary { private readonly IDictionary database; @@ -19,14 +19,10 @@ throw new NotImplementedException(); } - public int Count => database.Count; - public bool IsSynchronized { get; } public object SyncRoot { get; } - public bool IsReadOnly => database.IsReadOnly; - object IDictionary.this[object key] { get => database[key.ToString()].Deserialize(); @@ -42,27 +38,10 @@ } } - public ICollection Keys => database.Keys; - ICollection IDictionary.Values { get; } ICollection IDictionary.Keys { get; } - public ICollection Values => database.Values.Select(o => o.Deserialize()).ToList(); - - public T this[string key] - { - get => database[key].Deserialize(); - - 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 bool Contains(object key) { return ContainsKey(key.ToString()); @@ -80,6 +59,32 @@ public bool IsFixedSize => false; + public void Add(object key, object value) + { + Add(key.ToString(), (T) value); + } + + public int Count => database.Count; + + public bool IsReadOnly => database.IsReadOnly; + + public ICollection Keys => database.Keys; + + public ICollection Values => database.Values.Select(o => o.Deserialize()).ToList(); + + public T this[string key] + { + get => database[key].Deserialize(); + + 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> GetEnumerator() { return database.Select(d => new KeyValuePair(d.Key, d.Value.Deserialize())).GetEnumerator(); @@ -95,11 +100,6 @@ Add(item.Key, item.Value); } - public void Add(object key, object value) - { - Add(key.ToString(), (T) value); - } - public void Clear() { database.Clear(); diff --git a/FireBase/Offline/OfflineDatabase.cs b/FireBase/Offline/OfflineDatabase.cs index 3e6e7d8..be0380b 100644 --- a/FireBase/Offline/OfflineDatabase.cs +++ b/FireBase/Offline/OfflineDatabase.cs @@ -1,22 +1,22 @@ -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; - /// - /// The offline database. + /// The offline database. /// public class OfflineDatabase : IDictionary { - private readonly LiteRepository db; private readonly IDictionary cache; + private readonly LiteRepository db; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The item type which is used to determine the database file name. /// Custom string which will get appended to the file name. @@ -38,33 +38,41 @@ } /// - /// Gets the number of elements contained in the . + /// Gets the number of elements contained in the . /// - /// The number of elements contained in the . + /// The number of elements contained in the . public int Count => cache.Count; /// - /// Gets a value indicating whether this is a read-only collection. + /// Gets a value indicating whether this is a read-only collection. /// public bool IsReadOnly => cache.IsReadOnly; /// - /// Gets an containing the keys of the . + /// Gets an containing the keys of the + /// . /// - /// An containing the keys of the object that implements . + /// + /// An containing the keys of the object that + /// implements . + /// public ICollection Keys => cache.Keys; /// - /// Gets an containing the values in the . + /// Gets an containing the values in the + /// . /// - /// An containing the values in the object that implements . + /// + /// An containing the values in the object that + /// implements . + /// public ICollection Values => cache.Values; /// - /// Gets or sets the element with the specified key. + /// Gets or sets the element with the specified key. /// /// The key of the element to get or set. - /// The element with the specified key. + /// The element with the specified key. public OfflineEntry this[string key] { get => cache[key]; @@ -77,7 +85,7 @@ } /// - /// Returns an enumerator that iterates through the collection. + /// Returns an enumerator that iterates through the collection. /// /// An enumerator that can be used to iterate through the collection. public IEnumerator> GetEnumerator() @@ -91,65 +99,82 @@ } /// - /// Adds an item to the . + /// Adds an item to the . /// - /// The object to add to the . + /// The object to add to the . public void Add(KeyValuePair item) { Add(item.Key, item.Value); } /// - /// Removes all items from the . - /// + /// Removes all items from the . + /// public void Clear() { cache.Clear(); - db.Delete(Query.All()); + db.Delete(LiteDB.Query.All()); } /// - /// Determines whether the contains a specific value. + /// Determines whether the contains a specific value. /// - /// The object to locate in the . - /// True if is found in the ; otherwise, false. + /// The object to locate in the . + /// + /// True if is found in the ; + /// otherwise, false. + /// public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } /// - /// Copies the elements of the to an , starting at a particular index. + /// Copies the elements of the to an + /// , starting at a particular index. /// - /// The one-dimensional that is the destination of the elements copied from . The must have zero-based indexing. - /// The zero-based index in at which copying begins. + /// + /// The one-dimensional that is the destination of the elements copied + /// from . The must have + /// zero-based indexing. + /// + /// The zero-based index in at which copying begins. public void CopyTo(KeyValuePair[] array, int arrayIndex) { cache.CopyTo(array, arrayIndex); } /// - /// Removes the first occurrence of a specific object from the . + /// Removes the first occurrence of a specific object from the + /// . /// - /// The object to remove from the . - /// True if was successfully removed from the ; otherwise, false. This method also returns false if is not found in the original . + /// The object to remove from the . + /// + /// True if was successfully removed from the + /// ; otherwise, false. This method also returns false if + /// is not found in the original . + /// public bool Remove(KeyValuePair item) { return Remove(item.Key); } /// - /// Determines whether the contains an element with the specified key. + /// Determines whether the contains an element with the + /// specified key. /// - /// The key to locate in the . - /// True if the contains an element with the key; otherwise, false. + /// The key to locate in the . + /// + /// True if the contains an element with the key; + /// otherwise, false. + /// public bool ContainsKey(string key) { return cache.ContainsKey(key); } /// - /// Adds an element with the provided key and value to the . + /// Adds an element with the provided key and value to the . /// /// The object to use as the key of the element to add. /// The object to use as the value of the element to add. @@ -160,10 +185,13 @@ } /// - /// Removes the element with the specified key from the . + /// Removes the element with the specified key from the . /// /// The key of the element to remove. - /// True if the element is successfully removed; otherwise, false. This method also returns false if was not found in the original . + /// + /// True if the element is successfully removed; otherwise, false. This method also returns false if + /// was not found in the original . + /// public bool Remove(string key) { cache.Remove(key); @@ -171,10 +199,18 @@ } /// - /// Gets the value associated with the specified key. - /// - /// The key whose value to get.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 parameter. This parameter is passed uninitialized. - /// True if the object that implements contains an element with the specified key; otherwise, false. + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// + /// 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 parameter. This parameter is passed + /// uninitialized. + /// + /// + /// True if the object that implements contains an + /// element with the specified key; otherwise, false. + /// public bool TryGetValue(string key, out OfflineEntry value) { return cache.TryGetValue(key, out value); diff --git a/FireBase/Offline/OfflineEntry.cs b/FireBase/Offline/OfflineEntry.cs index dfd5910..9feffa3 100644 --- a/FireBase/Offline/OfflineEntry.cs +++ b/FireBase/Offline/OfflineEntry.cs @@ -1,21 +1,24 @@ -namespace Firebase.Database.Offline -{ - using System; - using Newtonsoft.Json; +using System; +using Newtonsoft.Json; +namespace Firebase.Database.Offline +{ /// - /// Represents an object stored in offline storage. + /// Represents an object stored in offline storage. /// public class OfflineEntry { private object dataInstance; /// - /// Initializes a new instance of the class with an already serialized object. + /// Initializes a new instance of the class with an already serialized object. /// /// The key. /// The object. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// /// The sync options. public OfflineEntry(string key, object obj, string data, int priority, SyncOptions syncOptions, bool isPartial = false) @@ -31,11 +34,14 @@ } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The key. /// The object. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// /// The sync options. public OfflineEntry(string key, object obj, int priority, SyncOptions syncOptions, bool isPartial = false) : this(key, obj, JsonConvert.SerializeObject(obj), priority, syncOptions, isPartial) @@ -43,47 +49,48 @@ } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// public OfflineEntry() { } /// - /// Gets or sets the key of this entry. + /// Gets or sets the key of this entry. /// public string Key { get; set; } /// - /// 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. /// public int Priority { get; set; } /// - /// Gets or sets the timestamp when this entry was last touched. + /// Gets or sets the timestamp when this entry was last touched. /// public DateTime Timestamp { get; set; } /// - /// Gets or sets the which define what sync state this entry is in. + /// Gets or sets the which define what sync state this entry is in. /// public SyncOptions SyncOptions { get; set; } /// - /// Gets or sets serialized JSON data. + /// Gets or sets serialized JSON data. /// public string Data { get; set; } /// - /// Specifies whether this is only a partial object. + /// Specifies whether this is only a partial object. /// public bool IsPartial { get; set; } /// - /// Deserializes into . The result is cached. + /// Deserializes into . The result is cached. /// /// Type of object to deserialize into. - /// Instance of . + /// Instance of . public T Deserialize() { return (T) (dataInstance ?? (dataInstance = JsonConvert.DeserializeObject(Data))); diff --git a/FireBase/Offline/RealtimeDatabase.cs b/FireBase/Offline/RealtimeDatabase.cs index 4d61027..973db46 100644 --- a/FireBase/Offline/RealtimeDatabase.cs +++ b/FireBase/Offline/RealtimeDatabase.cs @@ -1,50 +1,57 @@ -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 Extensions; - using Query; - using Streaming; - using System.Reactive.Threading.Tasks; - using System.Linq.Expressions; - using Internals; - using Newtonsoft.Json; - using System.Reflection; - using System.Reactive.Disposables; - /// - /// The real-time Database which synchronizes online and offline data. + /// The real-time Database which synchronizes online and offline data. /// /// Type of entities. - public partial class RealtimeDatabase : IDisposable where T : class + public class RealtimeDatabase : IDisposable where T : class { private readonly ChildQuery childQuery; private readonly string elementRoot; - private readonly StreamingOptions streamingOptions; - private readonly Subject> subject; + private readonly FirebaseCache firebaseCache; private readonly InitialPullStrategy initialPullStrategy; private readonly bool pushChanges; - private readonly FirebaseCache firebaseCache; + private readonly StreamingOptions streamingOptions; + private readonly Subject> subject; + private FirebaseSubscription firebaseSubscription; private bool isSyncRunning; private IObservable> observable; - private FirebaseSubscription firebaseSubscription; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The child query. /// The element Root. /// The offline database factory. /// Custom string which will get appended to the file name. /// Specifies whether changes should be streamed from the server. - /// Specifies if everything should be pull from the online storage on start. It only makes sense when is set to true. - /// Specifies whether changed items should actually be pushed to the server. If this is false, then Put / Post / Delete will not affect server data. + /// + /// Specifies if everything should be pull from the online storage on start. It only + /// makes sense when is set to true. + /// + /// + /// Specifies whether changed items should actually be pushed to the server. If this is false, + /// then Put / Post / Delete will not affect server data. + /// public RealtimeDatabase(ChildQuery childQuery, string elementRoot, Func> offlineDatabaseFactory, string filenameModifier, StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, @@ -67,24 +74,34 @@ } /// - /// 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. /// - public event EventHandler SyncExceptionThrown; + public IDictionary Database { get; } + + public ISetHandler PutHandler { private get; set; } + + public void Dispose() + { + subject.OnCompleted(); + firebaseSubscription?.Dispose(); + } /// - /// Gets the backing Database. + /// 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. /// - public IDictionary Database { get; private set; } - - public ISetHandler PutHandler { private get; set; } + public event EventHandler SyncExceptionThrown; /// - /// Overwrites existing object with given key. + /// Overwrites existing object with given key. /// /// The key. /// The object to set. /// Indicates whether the item should be synced online. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1) { SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions)); @@ -118,10 +135,13 @@ } /// - /// 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. /// /// The key. - /// The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. + /// + /// The priority. Objects with higher priority will be synced first. Higher number indicates higher + /// priority. + /// public void Pull(string key, int priority = 1) { if (!Database.ContainsKey(key)) @@ -132,7 +152,7 @@ } /// - /// Fetches everything from the remote database. + /// Fetches everything from the remote database. /// public async Task PullAsync() { @@ -142,7 +162,7 @@ .RetryAfterDelay>, FirebaseException>( childQuery.Client.Options.SyncPeriod, ex => ex.StatusCode == - System.Net.HttpStatusCode + HttpStatusCode .OK) // OK implies the request couldn't complete due to network error. .Select(e => ResetDatabaseFromInitial(e, false)) .SelectMany(e => e) @@ -164,7 +184,7 @@ } /// - /// Retrieves all offline items currently stored in local database. + /// Retrieves all offline items currently stored in local database. /// public IEnumerable> Once() { @@ -174,10 +194,10 @@ .ToList(); } - /// - /// Starts observing the real-time Database. Events will be fired both when change is done locally and remotely. - /// - /// Stream of . + /// + /// Starts observing the real-time Database. Events will be fired both when change is done locally and remotely. + /// + /// Stream of . public IObservable> AsObservable() { if (!isSyncRunning) @@ -212,7 +232,7 @@ .RetryAfterDelay>, FirebaseException>( childQuery.Client.Options.SyncPeriod, ex => ex.StatusCode == - System.Net.HttpStatusCode + HttpStatusCode .OK) // OK implies the request couldn't complete due to network error. .Select(e => ResetDatabaseFromInitial(e)) .SelectMany(e => e) @@ -230,12 +250,6 @@ return observable; } - public void Dispose() - { - subject.OnCompleted(); - firebaseSubscription?.Dispose(); - } - private IReadOnlyCollection> ResetDatabaseFromInitial( IReadOnlyCollection> collection, bool onlyWhenInitialEverything = true) { @@ -308,8 +322,6 @@ firebaseSubscription.ExceptionThrown += StreamingExceptionThrown; return new CompositeDisposable(firebaseSubscription.Run(), completeDisposable); - default: - break; } return completeDisposable; diff --git a/FireBase/Offline/SetHandler.cs b/FireBase/Offline/SetHandler.cs index 18a5131..6314c3c 100644 --- a/FireBase/Offline/SetHandler.cs +++ b/FireBase/Offline/SetHandler.cs @@ -1,8 +1,8 @@ -namespace Firebase.Database.Offline -{ - using Query; - using System.Threading.Tasks; +using System.Threading.Tasks; +using Firebase.Database.Query; +namespace Firebase.Database.Offline +{ public class SetHandler : ISetHandler { public virtual async Task SetAsync(ChildQuery query, string key, OfflineEntry entry) diff --git a/FireBase/Offline/StreamingOptions.cs b/FireBase/Offline/StreamingOptions.cs index 4a5f7b8..a420cbb 100644 --- a/FireBase/Offline/StreamingOptions.cs +++ b/FireBase/Offline/StreamingOptions.cs @@ -3,18 +3,20 @@ public enum StreamingOptions { /// - /// No realtime streaming. + /// No realtime streaming. /// None, /// - /// Streaming of only new items - not the existing ones. + /// Streaming of only new items - not the existing ones. /// LatestOnly, /// - /// 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 to 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 to + /// because you would pointlessly pull everything twice. /// Everything } diff --git a/FireBase/Offline/SyncOptions.cs b/FireBase/Offline/SyncOptions.cs index aa3e21c..ca68d0a 100644 --- a/FireBase/Offline/SyncOptions.cs +++ b/FireBase/Offline/SyncOptions.cs @@ -1,27 +1,27 @@ namespace Firebase.Database.Offline { /// - /// Specifies type of sync requested for given data. + /// Specifies type of sync requested for given data. /// public enum SyncOptions { /// - /// No sync needed for given data. + /// No sync needed for given data. /// None, /// - /// Data should be pulled from firebase. + /// Data should be pulled from firebase. /// Pull, /// - /// Data should be put to firebase. + /// Data should be put to firebase. /// Put, /// - /// Data should be patched in firebase. + /// Data should be patched in firebase. /// Patch } diff --git a/FireBase/Query/AuthQuery.cs b/FireBase/Query/AuthQuery.cs index 14beb7e..2cfda3c 100644 --- a/FireBase/Query/AuthQuery.cs +++ b/FireBase/Query/AuthQuery.cs @@ -1,18 +1,18 @@ +using System; + namespace Firebase.Database.Query { - using System; - /// - /// Represents an auth parameter in firebase query, e.g. "?auth=xyz". + /// Represents an auth parameter in firebase query, e.g. "?auth=xyz". /// public class AuthQuery : ParameterQuery { private readonly Func tokenFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - /// The parent. + /// The parent. /// The authentication token factory. /// The owner. public AuthQuery(FirebaseQuery parent, Func tokenFactory, FirebaseClient client) : base(parent, @@ -22,10 +22,10 @@ namespace Firebase.Database.Query } /// - /// Build the url parameter value of this child. + /// Build the url parameter value of this child. /// /// The child of this child. - /// The . + /// The . protected override string BuildUrlParameter(FirebaseQuery child) { return tokenFactory(); diff --git a/FireBase/Query/ChildQuery.cs b/FireBase/Query/ChildQuery.cs index 510ae75..014fe09 100644 --- a/FireBase/Query/ChildQuery.cs +++ b/FireBase/Query/ChildQuery.cs @@ -1,16 +1,16 @@ +using System; + namespace Firebase.Database.Query { - using System; - /// - /// Firebase query which references the child of current node. + /// Firebase query which references the child of current node. /// public class ChildQuery : FirebaseQuery { private readonly Func pathFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The parent. /// The path to the child node. @@ -22,7 +22,7 @@ namespace Firebase.Database.Query } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The client. /// The path to the child node. @@ -32,10 +32,10 @@ namespace Firebase.Database.Query } /// - /// Build the url segment of this child. + /// Build the url segment of this child. /// /// The child of this child. - /// The . + /// The . protected override string BuildUrlSegment(FirebaseQuery child) { var s = pathFactory(); diff --git a/FireBase/Query/FilterQuery.cs b/FireBase/Query/FilterQuery.cs index be544c8..3434d1d 100644 --- a/FireBase/Query/FilterQuery.cs +++ b/FireBase/Query/FilterQuery.cs @@ -1,24 +1,24 @@ +using System; +using System.Globalization; + namespace Firebase.Database.Query { - using System; - using System.Globalization; - /// - /// Represents a firebase filtering query, e.g. "?LimitToLast=10". + /// Represents a firebase filtering query, e.g. "?LimitToLast=10". /// public class FilterQuery : ParameterQuery { - private readonly Func valueFactory; - private readonly Func doubleValueFactory; private readonly Func boolValueFactory; + private readonly Func doubleValueFactory; + private readonly Func valueFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The parent. /// The filter. /// The value for filter. - /// The owning client. + /// The owning client. public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) : base(parent, filterFactory, client) @@ -27,7 +27,7 @@ namespace Firebase.Database.Query } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The parent. /// The filter. @@ -41,7 +41,7 @@ namespace Firebase.Database.Query } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The parent. /// The filter. @@ -55,25 +55,21 @@ namespace Firebase.Database.Query } /// - /// The build url parameter. + /// The build url parameter. /// - /// The child. - /// Url parameter part of the resulting path. + /// The child. + /// Url parameter part of the resulting path. protected override string BuildUrlParameter(FirebaseQuery child) { if (valueFactory != null) { - if (valueFactory() == null) return $"null"; + if (valueFactory() == null) return "null"; return $"\"{valueFactory()}\""; } - else if (doubleValueFactory != null) - { + + if (doubleValueFactory != null) return doubleValueFactory().ToString(CultureInfo.InvariantCulture); - } - else if (boolValueFactory != null) - { - return $"{boolValueFactory().ToString().ToLower()}"; - } + if (boolValueFactory != null) return $"{boolValueFactory().ToString().ToLower()}"; return string.Empty; } diff --git a/FireBase/Query/FirebaseQuery.cs b/FireBase/Query/FirebaseQuery.cs index 5e09795..60d0289 100644 --- a/FireBase/Query/FirebaseQuery.cs +++ b/FireBase/Query/FirebaseQuery.cs @@ -1,29 +1,27 @@ +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 Http; - using Offline; - using Streaming; - using Newtonsoft.Json; - using System.Net; - /// - /// Represents a firebase query. + /// Represents a firebase query. /// 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); - /// - /// Initializes a new instance of the class. + /// + /// Initializes a new instance of the class. /// /// The parent of this query. /// The owning client. @@ -34,16 +32,24 @@ namespace Firebase.Database.Query } /// - /// Gets the client. + /// Disposes this instance. + /// + public void Dispose() + { + client?.Dispose(); + } + + /// + /// Gets the client. /// public FirebaseClient Client { get; } /// - /// Queries the firebase server once returning collection of items. + /// Queries the firebase server once returning collection of items. /// /// Optional timeout value. /// Type of elements. - /// Collection of holding the entities returned by server. + /// Collection of holding the entities returned by server. public async Task>> OnceAsync(TimeSpan? timeout = null) { var url = string.Empty; @@ -62,6 +68,39 @@ namespace Firebase.Database.Query .ConfigureAwait(false); } + /// + /// Starts observing this query watching for changes real time sent by the server. + /// + /// Type of elements. + /// Optional custom root element of received json items. + /// Observable stream of . + public IObservable> AsObservable( + EventHandler> exceptionHandler = null, string elementRoot = "") + { + return Observable.Create>(observer => + { + var sub = new FirebaseSubscription(observer, this, elementRoot, new FirebaseCache()); + sub.ExceptionThrown += exceptionHandler; + return sub.Run(); + }); + } + + /// + /// Builds the actual URL of this query. + /// + /// The . + public async Task 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>> OnceAsync(Type dataType, TimeSpan? timeout = null) { var url = string.Empty; @@ -80,11 +119,11 @@ namespace Firebase.Database.Query }*/ /// - /// Assumes given query is pointing to a single object of type and retrieves it. + /// Assumes given query is pointing to a single object of type and retrieves it. /// /// Optional timeout value. /// Type of elements. - /// Single object of type . + /// Single object of type . public async Task OnceSingleAsync(TimeSpan? timeout = null) { var responseData = string.Empty; @@ -118,45 +157,12 @@ namespace Firebase.Database.Query } /// - /// Starts observing this query watching for changes real time sent by the server. - /// - /// Type of elements. - /// Optional custom root element of received json items. - /// Observable stream of . - public IObservable> AsObservable( - EventHandler> exceptionHandler = null, string elementRoot = "") - { - return Observable.Create>(observer => - { - var sub = new FirebaseSubscription(observer, this, elementRoot, new FirebaseCache()); - sub.ExceptionThrown += exceptionHandler; - return sub.Run(); - }); - } - - /// - /// Builds the actual URL of this query. - /// - /// The . - public async Task 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); - } - - /// - /// Posts given object to repository. + /// Posts given object to repository. /// /// The object. /// Specifies whether the key should be generated offline instead of online. /// Optional timeout value. - /// Type of + /// Type of /// Resulting firebase object with populated key. public async Task> PostAsync(string data, bool generateKeyOffline = true, TimeSpan? timeout = null) @@ -169,23 +175,21 @@ namespace Firebase.Database.Query return new FirebaseObject(key, data); } - else - { - var c = GetClient(timeout); - var sendData = await SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false); - var result = JsonConvert.DeserializeObject(sendData, Client.Options.JsonSerializerSettings); - return new FirebaseObject(result.Name, data); - } + var c = GetClient(timeout); + var sendData = await SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false); + var result = JsonConvert.DeserializeObject(sendData, Client.Options.JsonSerializerSettings); + + return new FirebaseObject(result.Name, data); } /// - /// Patches data at given location instead of overwriting them. - /// + /// Patches data at given location instead of overwriting them. + /// /// The object. /// Optional timeout value. - /// Type of - /// The . + /// Type of + /// The . public async Task PatchAsync(string data, TimeSpan? timeout = null) { var c = GetClient(timeout); @@ -194,12 +198,12 @@ namespace Firebase.Database.Query } /// - /// Sets or overwrites data at given location. - /// + /// Sets or overwrites data at given location. + /// /// The object. /// Optional timeout value. - /// Type of - /// The . + /// Type of + /// The . public async Task PutAsync(string data, TimeSpan? timeout = null) { var c = GetClient(timeout); @@ -208,10 +212,10 @@ namespace Firebase.Database.Query } /// - /// Deletes data from given location. + /// Deletes data from given location. /// /// Optional timeout value. - /// The . + /// The . public async Task DeleteAsync(TimeSpan? timeout = null) { var c = GetClient(timeout); @@ -243,18 +247,10 @@ namespace Firebase.Database.Query } /// - /// Disposes this instance. - /// - public void Dispose() - { - client?.Dispose(); - } - - /// - /// Build the url segment of this child. + /// Build the url segment of this child. /// /// The child of this query. - /// The . + /// The . protected abstract string BuildUrlSegment(FirebaseQuery child); private string BuildUrl(FirebaseQuery child) diff --git a/FireBase/Query/IFirebaseQuery.cs b/FireBase/Query/IFirebaseQuery.cs index 9f6e36c..0da4b15 100644 --- a/FireBase/Query/IFirebaseQuery.cs +++ b/FireBase/Query/IFirebaseQuery.cs @@ -1,40 +1,40 @@ -namespace Firebase.Database.Query -{ - using System; - using System.Collections.Generic; - using System.Threading.Tasks; - using Streaming; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Firebase.Database.Streaming; +namespace Firebase.Database.Query +{ /// - /// The FirebaseQuery interface. + /// The FirebaseQuery interface. /// public interface IFirebaseQuery { /// - /// Gets the owning client of this query. + /// Gets the owning client of this query. /// FirebaseClient Client { get; } /// - /// Retrieves items which exist on the location specified by this query instance. + /// Retrieves items which exist on the location specified by this query instance. /// /// Optional timeout value. /// Type of the items. - /// Collection of . + /// Collection of . Task>> OnceAsync(TimeSpan? timeout = null); /// - /// 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. /// /// Type of the items. - /// Cold observable of . + /// Cold observable of . IObservable> AsObservable( EventHandler> exceptionHandler, string elementRoot = ""); /// - /// Builds the actual url of this query. + /// Builds the actual url of this query. /// - /// The . + /// The . Task BuildUrlAsync(); } } \ No newline at end of file diff --git a/FireBase/Query/OrderQuery.cs b/FireBase/Query/OrderQuery.cs index 16adba7..302d1a3 100644 --- a/FireBase/Query/OrderQuery.cs +++ b/FireBase/Query/OrderQuery.cs @@ -1,16 +1,16 @@ +using System; + namespace Firebase.Database.Query { - using System; - /// - /// Represents a firebase ordering query, e.g. "?OrderBy=Foo". + /// Represents a firebase ordering query, e.g. "?OrderBy=Foo". /// public class OrderQuery : ParameterQuery { private readonly Func propertyNameFactory; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The query parent. /// The property name. @@ -22,10 +22,10 @@ namespace Firebase.Database.Query } /// - /// The build url parameter. + /// The build url parameter. /// /// The child. - /// The . + /// The . protected override string BuildUrlParameter(FirebaseQuery child) { return $"\"{propertyNameFactory()}\""; diff --git a/FireBase/Query/ParameterQuery.cs b/FireBase/Query/ParameterQuery.cs index fb273a3..572224c 100644 --- a/FireBase/Query/ParameterQuery.cs +++ b/FireBase/Query/ParameterQuery.cs @@ -1,9 +1,9 @@ +using System; + namespace Firebase.Database.Query { - using System; - /// - /// Represents a parameter in firebase query, e.g. "?data=foo". + /// Represents a parameter in firebase query, e.g. "?data=foo". /// public abstract class ParameterQuery : FirebaseQuery { @@ -11,7 +11,7 @@ namespace Firebase.Database.Query private readonly string separator; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The parent of this query. /// The parameter. @@ -24,20 +24,20 @@ namespace Firebase.Database.Query } /// - /// Build the url segment represented by this query. - /// + /// Build the url segment represented by this query. + /// /// The child. - /// The . + /// The . protected override string BuildUrlSegment(FirebaseQuery child) { return $"{separator}{parameterFactory()}={BuildUrlParameter(child)}"; } /// - /// The build url parameter. + /// The build url parameter. /// /// The child. - /// The . + /// The . 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 735fe0a..df2edfc 100644 --- a/FireBase/Query/QueryExtensions.cs +++ b/FireBase/Query/QueryExtensions.cs @@ -6,158 +6,163 @@ using Newtonsoft.Json; namespace Firebase.Database.Query { /// - /// Query extensions providing linq like syntax for firebase server methods. + /// Query extensions providing linq like syntax for firebase server methods. /// public static class QueryExtensions { /// - /// Adds an auth parameter to the query. + /// Adds an auth parameter to the query. /// /// The child. /// The auth token. - /// The . + /// The . internal static AuthQuery WithAuth(this FirebaseQuery node, string token) { return node.WithAuth(() => token); } /// - /// Appends print=silent to save bandwidth. + /// Appends print=silent to save bandwidth. /// /// The child. - /// The . + /// The . internal static SilentQuery Silent(this FirebaseQuery node) { return new SilentQuery(node, node.Client); } /// - /// References a sub child of the existing node. + /// References a sub child of the existing node. /// /// The child. /// The path of sub child. - /// The . + /// The . public static ChildQuery Child(this ChildQuery node, string path) { return node.Child(() => path); } /// - /// Order data by given . 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 . Note that this is used mainly for following filtering queries and + /// due to firebase implementation + /// the data may actually not be ordered. /// /// The child. /// The property name. - /// The . + /// The . public static OrderQuery OrderBy(this ChildQuery child, string propertyName) { return child.OrderBy(() => propertyName); } /// - /// Instructs firebase to send data greater or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data greater or equal to the . This must be preceded by an OrderBy + /// query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery StartAt(this ParameterQuery child, string value) { return child.StartAt(() => value); } /// - /// Instructs firebase to send data lower or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data lower or equal to the . This must be preceded by an OrderBy + /// query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EndAt(this ParameterQuery child, string value) { return child.EndAt(() => value); } /// - /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EqualTo(this ParameterQuery child, string value) { return child.EqualTo(() => value); } /// - /// Instructs firebase to send data greater or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data greater or equal to the . This must be preceded by an OrderBy + /// query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery StartAt(this ParameterQuery child, double value) { return child.StartAt(() => value); } /// - /// Instructs firebase to send data lower or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data lower or equal to the . This must be preceded by an OrderBy + /// query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EndAt(this ParameterQuery child, double value) { return child.EndAt(() => value); } /// - /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EqualTo(this ParameterQuery child, double value) { return child.EqualTo(() => value); } /// - /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EqualTo(this ParameterQuery child, bool value) { return child.EqualTo(() => value); } /// - /// 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. /// /// Current node. - /// The . + /// The . public static FilterQuery EqualTo(this ParameterQuery child) { return child.EqualTo(() => null); } /// - /// Limits the result to first items. + /// Limits the result to first items. /// /// Current node. /// Number of elements. - /// The . + /// The . public static FilterQuery LimitToFirst(this ParameterQuery child, int count) { return child.LimitToFirst(() => count); } /// - /// Limits the result to last items. + /// Limits the result to last items. /// /// Current node. /// Number of elements. - /// The . + /// The . public static FilterQuery LimitToLast(this ParameterQuery child, int count) { return child.LimitToLast(() => count); @@ -184,7 +189,8 @@ namespace Firebase.Database.Query } /// - /// 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. /// /// Type of object to fan out. /// Current node. diff --git a/FireBase/Query/QueryFactoryExtensions.cs b/FireBase/Query/QueryFactoryExtensions.cs index b54c315..71dae5c 100644 --- a/FireBase/Query/QueryFactoryExtensions.cs +++ b/FireBase/Query/QueryFactoryExtensions.cs @@ -1,173 +1,184 @@ +using System; + namespace Firebase.Database.Query { - using System; - /// - /// Query extensions providing linq like syntax for firebase server methods. + /// Query extensions providing linq like syntax for firebase server methods. /// public static class QueryFactoryExtensions { /// - /// Adds an auth parameter to the query. + /// Adds an auth parameter to the query. /// /// The child. /// The auth token. - /// The . + /// The . internal static AuthQuery WithAuth(this FirebaseQuery node, Func tokenFactory) { return new AuthQuery(node, tokenFactory, node.Client); } /// - /// References a sub child of the existing node. + /// References a sub child of the existing node. /// /// The child. /// The path of sub child. - /// The . + /// The . public static ChildQuery Child(this ChildQuery node, Func pathFactory) { return new ChildQuery(node, pathFactory, node.Client); } /// - /// Order data by given . 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 . Note that this is used mainly for following filtering + /// queries and due to firebase implementation + /// the data may actually not be ordered. /// /// The child. /// The property name. - /// The . + /// The . public static OrderQuery OrderBy(this ChildQuery child, Func propertyNameFactory) { return new OrderQuery(child, propertyNameFactory, child.Client); } /// - /// 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. /// /// The child. - /// The . + /// The . public static OrderQuery OrderByKey(this ChildQuery child) { return child.OrderBy("$key"); } /// - /// 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. /// /// The child. - /// The . + /// The . public static OrderQuery OrderByValue(this ChildQuery child) { return child.OrderBy("$value"); } /// - /// 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. /// /// The child. - /// The . + /// The . public static OrderQuery OrderByPriority(this ChildQuery child) { return child.OrderBy("$priority"); } /// - /// Instructs firebase to send data greater or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data greater or equal to the . This must be preceded by an + /// OrderBy query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "startAt", valueFactory, child.Client); } /// - /// Instructs firebase to send data lower or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data lower or equal to the . This must be preceded by an + /// OrderBy query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "endAt", valueFactory, child.Client); } /// - /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy + /// query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } /// - /// Instructs firebase to send data greater or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data greater or equal to the . This must be preceded by an + /// OrderBy query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "startAt", valueFactory, child.Client); } /// - /// Instructs firebase to send data lower or equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data lower or equal to the . This must be preceded by an + /// OrderBy query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "endAt", valueFactory, child.Client); } /// - /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy + /// query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } /// - /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy query. + /// Instructs firebase to send data equal to the . This must be preceded by an OrderBy + /// query. /// /// Current node. /// Value to start at. - /// The . + /// The . public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } /// - /// Limits the result to first items. + /// Limits the result to first items. /// /// Current node. /// Number of elements. - /// The . + /// The . public static FilterQuery LimitToFirst(this ParameterQuery child, Func countFactory) { return new FilterQuery(child, () => "limitToFirst", () => countFactory(), child.Client); } /// - /// Limits the result to last items. + /// Limits the result to last items. /// /// Current node. /// Number of elements. - /// The . + /// The . public static FilterQuery LimitToLast(this ParameterQuery child, Func countFactory) { return new FilterQuery(child, () => "limitToLast", () => countFactory(), child.Client); diff --git a/FireBase/Query/SilentQuery.cs b/FireBase/Query/SilentQuery.cs index 1960426..d09d38b 100644 --- a/FireBase/Query/SilentQuery.cs +++ b/FireBase/Query/SilentQuery.cs @@ -1,7 +1,7 @@ namespace Firebase.Database.Query { /// - /// Appends print=silent to the url. + /// Appends print=silent to the url. /// public class SilentQuery : ParameterQuery { diff --git a/FireBase/Streaming/FirebaseCache.cs b/FireBase/Streaming/FirebaseCache.cs index 77fc622..66241e0 100644 --- a/FireBase/Streaming/FirebaseCache.cs +++ b/FireBase/Streaming/FirebaseCache.cs @@ -1,15 +1,15 @@ +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 Http; - using Newtonsoft.Json; - /// - /// The firebase cache. + /// The firebase cache. /// /// Type of top-level entities in the cache. public class FirebaseCache : IEnumerable> @@ -17,13 +17,13 @@ namespace Firebase.Database.Streaming private readonly IDictionary dictionary; private readonly bool isDictionaryType; - private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings() + private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// public FirebaseCache() : this(new Dictionary()) @@ -31,7 +31,7 @@ namespace Firebase.Database.Streaming } /// - /// Initializes a new instance of the class and populates it with existing data. + /// Initializes a new instance of the class and populates it with existing data. /// /// The existing items. public FirebaseCache(IDictionary existingItems) @@ -41,10 +41,10 @@ namespace Firebase.Database.Streaming } /// - /// The push data. + /// The push data. /// - /// The path of incoming data, separated by slash. - /// The data in json format as returned by firebase. + /// The path of incoming data, separated by slash. + /// The data in json format as returned by firebase. /// Collection of top-level entities which were affected by the push. public IEnumerable> PushData(string path, string data, bool removeEmptyEntries = true) { @@ -63,7 +63,7 @@ namespace Firebase.Database.Streaming 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)) @@ -87,7 +87,7 @@ namespace Firebase.Database.Streaming element == p.GetCustomAttribute()?.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) { @@ -138,7 +138,7 @@ namespace Firebase.Database.Streaming // firebase sends strings without double quotes var targetObject = valueType == typeof(string) - ? data.ToString() + ? data : JsonConvert.DeserializeObject(data, valueType); if ((valueType.GetTypeInfo().IsPrimitive || valueType == typeof(string)) && primitiveObjSetter != null) @@ -161,8 +161,7 @@ namespace Firebase.Database.Streaming { if (type == typeof(string)) return string.Empty; - else - return Activator.CreateInstance(type); + return Activator.CreateInstance(type); } #region IEnumerable diff --git a/FireBase/Streaming/FirebaseEvent.cs b/FireBase/Streaming/FirebaseEvent.cs index e4fd238..1761a72 100644 --- a/FireBase/Streaming/FirebaseEvent.cs +++ b/FireBase/Streaming/FirebaseEvent.cs @@ -1,13 +1,13 @@ namespace Firebase.Database.Streaming { /// - /// Firebase event which hold and the object affected by the event. + /// Firebase event which hold and the object affected by the event. /// /// Type of object affected by the event. public class FirebaseEvent : FirebaseObject { /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The key of the object. /// The object. @@ -20,12 +20,12 @@ namespace Firebase.Database.Streaming } /// - /// Gets the source of the event. + /// Gets the source of the event. /// public FirebaseEventSource EventSource { get; } /// - /// Gets the event type. + /// Gets the event type. /// public FirebaseEventType EventType { get; } diff --git a/FireBase/Streaming/FirebaseEventSource.cs b/FireBase/Streaming/FirebaseEventSource.cs index 0a397ad..b1385ca 100644 --- a/FireBase/Streaming/FirebaseEventSource.cs +++ b/FireBase/Streaming/FirebaseEventSource.cs @@ -1,37 +1,37 @@ namespace Firebase.Database.Streaming { /// - /// Specifies the origin of given + /// Specifies the origin of given /// public enum FirebaseEventSource { /// - /// Event comes from an offline source. + /// Event comes from an offline source. /// Offline, /// - /// 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). /// OnlineInitial, /// - /// Event comes from online source received thru active stream. + /// Event comes from online source received thru active stream. /// OnlineStream, /// - /// Event comes from online source being fetched manually. + /// Event comes from online source being fetched manually. /// OnlinePull, /// - /// 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). /// OnlinePush, /// - /// Event comes from an online source. + /// Event comes from an online source. /// Online = OnlineInitial | OnlinePull | OnlinePush | OnlineStream } diff --git a/FireBase/Streaming/FirebaseEventType.cs b/FireBase/Streaming/FirebaseEventType.cs index d8c65b3..7606331 100644 --- a/FireBase/Streaming/FirebaseEventType.cs +++ b/FireBase/Streaming/FirebaseEventType.cs @@ -1,17 +1,17 @@ namespace Firebase.Database.Streaming { /// - /// The type of event. + /// The type of event. /// public enum FirebaseEventType { /// - /// Item was inserted or updated. + /// Item was inserted or updated. /// InsertOrUpdate, /// - /// Item was deleted. + /// Item was deleted. /// Delete } diff --git a/FireBase/Streaming/FirebaseSubscription.cs b/FireBase/Streaming/FirebaseSubscription.cs index acdc76c..fb0f403 100644 --- a/FireBase/Streaming/FirebaseSubscription.cs +++ b/FireBase/Streaming/FirebaseSubscription.cs @@ -1,30 +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 Query; - using Newtonsoft.Json.Linq; - using System.Net; - /// - /// The firebase subscription. + /// The firebase subscription. /// /// Type of object to be streaming back to the called. internal class FirebaseSubscription : IDisposable { + private static readonly HttpClient http; + private readonly FirebaseCache cache; private readonly CancellationTokenSource cancel; + private readonly FirebaseClient client; + private readonly string elementRoot; private readonly IObserver> observer; private readonly IFirebaseQuery query; - private readonly FirebaseCache cache; - private readonly string elementRoot; - private readonly FirebaseClient client; - - private static HttpClient http; static FirebaseSubscription() { @@ -43,7 +41,7 @@ namespace Firebase.Database.Streaming } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// The observer. /// The query. @@ -59,13 +57,13 @@ namespace Firebase.Database.Streaming client = query.Client; } - public event EventHandler> ExceptionThrown; - public void Dispose() { cancel.Cancel(); } + public event EventHandler> ExceptionThrown; + public IDisposable Run() { Task.Run(() => ReceiveThread()); diff --git a/FireBase/Streaming/NonBlockingStreamReader.cs b/FireBase/Streaming/NonBlockingStreamReader.cs index ab01510..8228e32 100644 --- a/FireBase/Streaming/NonBlockingStreamReader.cs +++ b/FireBase/Streaming/NonBlockingStreamReader.cs @@ -1,21 +1,24 @@ -namespace Firebase.Database.Streaming -{ - using System.IO; - using System.Text; +using System.IO; +using System.Text; +namespace Firebase.Database.Streaming +{ /// - /// When a regular is used in a UWP app its method tends to take a long - /// time for data larger then 2 KB. This extremly simple implementation of can be used instead to boost performance - /// in your UWP app. Use to inject an instance of this class into your . + /// When a regular is used in a UWP app its method + /// tends to take a long + /// time for data larger then 2 KB. This extremly simple implementation of can be used + /// instead to boost performance + /// in your UWP app. Use to inject an instance of this class into your + /// . /// 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) diff --git a/ZooBOTanica/CritCreate.cs b/ZooBOTanica/CritCreate.cs index c26f323..e79cff4 100644 --- a/ZooBOTanica/CritCreate.cs +++ b/ZooBOTanica/CritCreate.cs @@ -1,18 +1,11 @@ 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 Critter critter; diff --git a/ZooBOTanica/Program.cs b/ZooBOTanica/Program.cs index 0c1123e..59c7434 100644 --- a/ZooBOTanica/Program.cs +++ b/ZooBOTanica/Program.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using System.Windows.Forms; namespace ZooBOTanica @@ -9,7 +6,7 @@ namespace ZooBOTanica internal static class Program { /// - /// Der Haupteinstiegspunkt für die Anwendung. + /// Der Haupteinstiegspunkt für die Anwendung. /// [STAThread] private static void Main() diff --git a/ZooBOTanica/Properties/AssemblyInfo.cs b/ZooBOTanica/Properties/AssemblyInfo.cs index 8bba4bc..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 -- cgit v1.2.3-70-g09d2