From 304437b834e8c87687f68333ae67a13ee1377a73 Mon Sep 17 00:00:00 2001 From: Dennis Kobert Date: Wed, 12 Jun 2019 21:47:51 +0200 Subject: Adjust Codestyle --- dsa/FireBase/ExceptionEventArgs.cs | 15 +-- dsa/FireBase/Extensions/ObservableExtensions.cs | 12 +- dsa/FireBase/Extensions/TaskExtensions.cs | 15 +-- dsa/FireBase/FirebaseClient.cs | 15 +-- dsa/FireBase/FirebaseException.cs | 15 +-- dsa/FireBase/FirebaseKeyGenerator.cs | 21 ++-- dsa/FireBase/FirebaseObject.cs | 9 +- dsa/FireBase/FirebaseOptions.cs | 9 +- dsa/FireBase/Http/HttpClientExtensions.cs | 24 ++-- dsa/FireBase/Http/PostResult.cs | 6 +- dsa/FireBase/ObservableExtensions.cs | 18 +-- dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs | 51 +++----- dsa/FireBase/Offline/DatabaseExtensions.cs | 39 +++---- dsa/FireBase/Offline/ISetHandler.cs | 6 +- dsa/FireBase/Offline/InitialPullStrategy.cs | 6 +- .../Offline/Internals/MemberAccessVisitor.cs | 24 ++-- dsa/FireBase/Offline/OfflineCacheAdapter.cs | 72 ++++-------- dsa/FireBase/Offline/OfflineDatabase.cs | 51 +++----- dsa/FireBase/Offline/OfflineEntry.cs | 18 +-- dsa/FireBase/Offline/RealtimeDatabase.cs | 129 +++++++-------------- dsa/FireBase/Offline/SetHandler.cs | 12 +- dsa/FireBase/Offline/StreamingOptions.cs | 6 +- dsa/FireBase/Offline/SyncOptions.cs | 6 +- dsa/FireBase/Query/AuthQuery.cs | 12 +- dsa/FireBase/Query/ChildQuery.cs | 15 +-- dsa/FireBase/Query/FilterQuery.cs | 21 ++-- dsa/FireBase/Query/FirebaseQuery.cs | 99 ++++++---------- dsa/FireBase/Query/IFirebaseQuery.cs | 6 +- dsa/FireBase/Query/OrderQuery.cs | 12 +- dsa/FireBase/Query/ParameterQuery.cs | 12 +- dsa/FireBase/Query/QueryExtensions.cs | 60 ++++------ dsa/FireBase/Query/QueryFactoryExtensions.cs | 51 +++----- dsa/FireBase/Query/SilentQuery.cs | 12 +- dsa/FireBase/Streaming/FirebaseCache.cs | 60 ++++------ dsa/FireBase/Streaming/FirebaseEvent.cs | 12 +- dsa/FireBase/Streaming/FirebaseEventSource.cs | 6 +- dsa/FireBase/Streaming/FirebaseEventType.cs | 6 +- dsa/FireBase/Streaming/FirebaseServerEventType.cs | 6 +- dsa/FireBase/Streaming/FirebaseSubscription.cs | 66 ++++------- dsa/FireBase/Streaming/NonBlockingStreamReader.cs | 21 ++-- 40 files changed, 352 insertions(+), 704 deletions(-) (limited to 'dsa/FireBase') diff --git a/dsa/FireBase/ExceptionEventArgs.cs b/dsa/FireBase/ExceptionEventArgs.cs index 09c205a..a7ac506 100644 --- a/dsa/FireBase/ExceptionEventArgs.cs +++ b/dsa/FireBase/ExceptionEventArgs.cs @@ -1,28 +1,23 @@ using System; -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Event args holding the object. /// - public class ExceptionEventArgs : EventArgs where T : Exception - { + public class ExceptionEventArgs : EventArgs where T : Exception { public readonly T Exception; /// /// Initializes a new instance of the class. /// /// The exception. - public ExceptionEventArgs(T exception) - { + public ExceptionEventArgs(T exception) { Exception = exception; } } - public class ExceptionEventArgs : ExceptionEventArgs - { - public ExceptionEventArgs(Exception exception) : base(exception) - { + public class ExceptionEventArgs : ExceptionEventArgs { + public ExceptionEventArgs(Exception exception) : base(exception) { } } } \ No newline at end of file diff --git a/dsa/FireBase/Extensions/ObservableExtensions.cs b/dsa/FireBase/Extensions/ObservableExtensions.cs index 0a672d7..1dae7e9 100644 --- a/dsa/FireBase/Extensions/ObservableExtensions.cs +++ b/dsa/FireBase/Extensions/ObservableExtensions.cs @@ -1,10 +1,8 @@ using System; using System.Reactive.Linq; -namespace Firebase.Database.Extensions -{ - public static class ObservableExtensions - { +namespace Firebase.Database.Extensions { + public static class ObservableExtensions { /// /// Returns a cold observable which retries (re-subscribes to) the source observable on error until it successfully /// terminates. @@ -20,12 +18,10 @@ namespace Firebase.Database.Extensions this IObservable source, TimeSpan dueTime, Func retryOnError) - where TException : Exception - { + where TException : Exception { var attempt = 0; - return Observable.Defer(() => - { + return Observable.Defer(() => { return (++attempt == 1 ? source : source.DelaySubscription(dueTime)) .Select(item => new Tuple(true, item, null)) .Catch, TException>(e => retryOnError(e) diff --git a/dsa/FireBase/Extensions/TaskExtensions.cs b/dsa/FireBase/Extensions/TaskExtensions.cs index c955b3a..68d4538 100644 --- a/dsa/FireBase/Extensions/TaskExtensions.cs +++ b/dsa/FireBase/Extensions/TaskExtensions.cs @@ -1,21 +1,16 @@ using System; using System.Threading.Tasks; -namespace Firebase.Database.Extensions -{ - public static class TaskExtensions - { +namespace Firebase.Database.Extensions { + public static class TaskExtensions { /// /// Instead of unwrapping it throws it as it is. /// - public static async Task WithAggregateException(this Task source) - { - try - { + public static async Task WithAggregateException(this Task source) { + try { await source.ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw source.Exception ?? ex; } } diff --git a/dsa/FireBase/FirebaseClient.cs b/dsa/FireBase/FirebaseClient.cs index 3079f3b..e0e96d2 100644 --- a/dsa/FireBase/FirebaseClient.cs +++ b/dsa/FireBase/FirebaseClient.cs @@ -5,13 +5,11 @@ using Firebase.Database.Query; [assembly: InternalsVisibleTo("Firebase.Database.Tests")] -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Firebase client which acts as an entry point to the online database. /// - public class FirebaseClient : IDisposable - { + public class FirebaseClient : IDisposable { private readonly string baseUrl; internal readonly HttpClient HttpClient; internal readonly FirebaseOptions Options; @@ -21,8 +19,7 @@ namespace Firebase.Database /// /// The base url. /// Offline database. - public FirebaseClient(string baseUrl, FirebaseOptions options = null) - { + public FirebaseClient(string baseUrl, FirebaseOptions options = null) { HttpClient = new HttpClient(); Options = options ?? new FirebaseOptions(); @@ -31,8 +28,7 @@ namespace Firebase.Database if (!this.baseUrl.EndsWith("/")) this.baseUrl += "/"; } - public void Dispose() - { + public void Dispose() { HttpClient?.Dispose(); } @@ -41,8 +37,7 @@ namespace Firebase.Database /// /// Name of the child. /// . - public ChildQuery Child(string resourceName) - { + public ChildQuery Child(string resourceName) { return new ChildQuery(this, () => baseUrl + resourceName); } } diff --git a/dsa/FireBase/FirebaseException.cs b/dsa/FireBase/FirebaseException.cs index cfc09d3..f74c54e 100644 --- a/dsa/FireBase/FirebaseException.cs +++ b/dsa/FireBase/FirebaseException.cs @@ -1,13 +1,10 @@ using System; using System.Net; -namespace Firebase.Database -{ - public class FirebaseException : Exception - { +namespace Firebase.Database { + public class FirebaseException : Exception { public FirebaseException(string requestUrl, string requestData, string responseData, HttpStatusCode statusCode) - : base(GenerateExceptionMessage(requestUrl, requestData, responseData)) - { + : base(GenerateExceptionMessage(requestUrl, requestData, responseData)) { RequestUrl = requestUrl; RequestData = requestData; ResponseData = responseData; @@ -16,8 +13,7 @@ namespace Firebase.Database public FirebaseException(string requestUrl, string requestData, string responseData, HttpStatusCode statusCode, Exception innerException) - : base(GenerateExceptionMessage(requestUrl, requestData, responseData), innerException) - { + : base(GenerateExceptionMessage(requestUrl, requestData, responseData), innerException) { RequestUrl = requestUrl; RequestData = requestData; ResponseData = responseData; @@ -44,8 +40,7 @@ namespace Firebase.Database /// public HttpStatusCode StatusCode { get; } - private static string GenerateExceptionMessage(string requestUrl, string requestData, string responseData) - { + private static string GenerateExceptionMessage(string requestUrl, string requestData, string responseData) { return $"Exception occured while processing the request.\nUrl: {requestUrl}\nRequest Data: {requestData}\nResponse: {responseData}"; } diff --git a/dsa/FireBase/FirebaseKeyGenerator.cs b/dsa/FireBase/FirebaseKeyGenerator.cs index 37beed5..2139b7a 100644 --- a/dsa/FireBase/FirebaseKeyGenerator.cs +++ b/dsa/FireBase/FirebaseKeyGenerator.cs @@ -1,14 +1,12 @@ using System; using System.Text; -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Offline key generator which mimics the official Firebase generators. /// Credit: https://github.com/bubbafat/FirebaseSharp/blob/master/src/FirebaseSharp.Portable/FireBasePushIdGenerator.cs /// - public class FirebaseKeyGenerator - { + public class FirebaseKeyGenerator { // Modeled after base64 web-safe chars, but ordered by ASCII. private const string PushCharsString = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; private static readonly char[] PushChars; @@ -20,8 +18,7 @@ namespace Firebase.Database // Timestamp of last push, used to prevent local collisions if you push twice in one ms. private static long lastPushTime; - static FirebaseKeyGenerator() - { + static FirebaseKeyGenerator() { PushChars = Encoding.UTF8.GetChars(Encoding.UTF8.GetBytes(PushCharsString)); } @@ -31,8 +28,7 @@ namespace Firebase.Database /// /// The . /// - public static string Next() - { + public static string Next() { // We generate 72-bits of randomness which get turned into 12 characters and // appended to the timestamp to prevent collisions with other clients. We store the last // characters we generated because in the event of a collision, we'll use those same @@ -43,8 +39,7 @@ namespace Firebase.Database lastPushTime = now; var timeStampChars = new char[8]; - for (var i = 7; i >= 0; i--) - { + for (var i = 7; i >= 0; i--) { var index = (int) (now % PushChars.Length); timeStampChars[i] = PushChars[index]; now = (long) Math.Floor((double) now / PushChars.Length); @@ -54,12 +49,10 @@ namespace Firebase.Database id.Append(timeStampChars); - if (!duplicateTime) - { + if (!duplicateTime) { for (var i = 0; i < 12; i++) lastRandChars[i] = (byte) random.Next(0, PushChars.Length); } - else - { + else { // If the timestamp hasn't changed since last push, use the same random number, // except incremented by 1. var lastIndex = 11; diff --git a/dsa/FireBase/FirebaseObject.cs b/dsa/FireBase/FirebaseObject.cs index 2e0fd20..f53b2d4 100644 --- a/dsa/FireBase/FirebaseObject.cs +++ b/dsa/FireBase/FirebaseObject.cs @@ -1,15 +1,12 @@ -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Holds the object of type /// /// along with its key. /// /// Type of the underlying object. - public class FirebaseObject - { - internal FirebaseObject(string key, T obj) - { + public class FirebaseObject { + internal FirebaseObject(string key, T obj) { Key = key; Object = obj; } diff --git a/dsa/FireBase/FirebaseOptions.cs b/dsa/FireBase/FirebaseOptions.cs index b4a5e51..08f1935 100644 --- a/dsa/FireBase/FirebaseOptions.cs +++ b/dsa/FireBase/FirebaseOptions.cs @@ -5,12 +5,9 @@ using System.Threading.Tasks; using Firebase.Database.Offline; using Newtonsoft.Json; -namespace Firebase.Database -{ - public class FirebaseOptions - { - public FirebaseOptions() - { +namespace Firebase.Database { + public class FirebaseOptions { + public FirebaseOptions() { OfflineDatabaseFactory = (t, s) => new Dictionary(); SubscriptionStreamReaderFactory = s => new StreamReader(s); JsonSerializerSettings = new JsonSerializerSettings(); diff --git a/dsa/FireBase/Http/HttpClientExtensions.cs b/dsa/FireBase/Http/HttpClientExtensions.cs index 6582769..a4f1c11 100644 --- a/dsa/FireBase/Http/HttpClientExtensions.cs +++ b/dsa/FireBase/Http/HttpClientExtensions.cs @@ -7,13 +7,11 @@ using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json; -namespace Firebase.Database.Http -{ +namespace Firebase.Database.Http { /// /// The http client extensions for object deserializations. /// - internal static class HttpClientExtensions - { + internal static class HttpClientExtensions { /// /// The get object collection async. /// @@ -24,13 +22,11 @@ namespace Firebase.Database.Http /// The . public static async Task>> GetObjectCollectionAsync( this HttpClient client, string requestUri, - JsonSerializerSettings jsonSerializerSettings) - { + JsonSerializerSettings jsonSerializerSettings) { var responseData = string.Empty; var statusCode = HttpStatusCode.OK; - try - { + try { var response = await client.GetAsync(requestUri).ConfigureAwait(false); statusCode = response.StatusCode; responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -44,8 +40,7 @@ namespace Firebase.Database.Http return dictionary.Select(item => new FirebaseObject(item.Key, item.Value)).ToList(); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(requestUri, string.Empty, responseData, statusCode, ex); } } @@ -96,21 +91,18 @@ namespace Firebase.Database.Http /// The json data. /// The type of entities the collection should contain. /// The . - public static IEnumerable> GetObjectCollection(this string data, Type elementType) - { + public static IEnumerable> GetObjectCollection(this string data, Type elementType) { var dictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), elementType); IDictionary dictionary = null; - if (data.StartsWith("[")) - { + if (data.StartsWith("[")) { var listType = typeof(List<>).MakeGenericType(elementType); var list = JsonConvert.DeserializeObject(data, listType) as IList; dictionary = Activator.CreateInstance(dictionaryType) as IDictionary; var index = 0; foreach (var item in list) dictionary.Add(index++.ToString(), item); } - else - { + else { dictionary = JsonConvert.DeserializeObject(data, dictionaryType) as IDictionary; } diff --git a/dsa/FireBase/Http/PostResult.cs b/dsa/FireBase/Http/PostResult.cs index 15a4894..b6b8f09 100644 --- a/dsa/FireBase/Http/PostResult.cs +++ b/dsa/FireBase/Http/PostResult.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Http -{ +namespace Firebase.Database.Http { /// /// Represents data returned after a successful POST to firebase server. /// - public class PostResult - { + public class PostResult { /// /// Gets or sets the generated key after a successful post. /// diff --git a/dsa/FireBase/ObservableExtensions.cs b/dsa/FireBase/ObservableExtensions.cs index bc46261..69730df 100644 --- a/dsa/FireBase/ObservableExtensions.cs +++ b/dsa/FireBase/ObservableExtensions.cs @@ -2,34 +2,28 @@ using System.Collections.ObjectModel; using Firebase.Database.Streaming; -namespace Firebase.Database -{ +namespace Firebase.Database { /// /// Extensions for . /// - public static class ObservableExtensions - { + public static class ObservableExtensions { /// /// Starts observing on given firebase observable and propagates event into an . /// /// The observable. /// Type of entity. /// The . - public static ObservableCollection AsObservableCollection(this IObservable> observable) - { + public static ObservableCollection AsObservableCollection(this IObservable> observable) { var collection = new ObservableCollection(); - observable.Subscribe(f => - { - if (f.EventType == FirebaseEventType.InsertOrUpdate) - { + observable.Subscribe(f => { + if (f.EventType == FirebaseEventType.InsertOrUpdate) { var i = collection.IndexOf(f.Object); if (i >= 0) collection.RemoveAt(i); collection.Add(f.Object); } - else - { + else { collection.Remove(f.Object); } }); diff --git a/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs b/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs index 1a9e607..724115f 100644 --- a/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs +++ b/dsa/FireBase/Offline/ConcurrentOfflineDatabase.cs @@ -6,13 +6,11 @@ using System.IO; using System.Linq; using LiteDB; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// The offline database. /// - public class ConcurrentOfflineDatabase : IDictionary - { + public class ConcurrentOfflineDatabase : IDictionary { private readonly ConcurrentDictionary ccache; private readonly LiteRepository db; @@ -21,8 +19,7 @@ namespace Firebase.Database.Offline /// /// The item type which is used to determine the database file name. /// Custom string which will get appended to the file name. - public ConcurrentOfflineDatabase(Type itemType, string filenameModifier) - { + public ConcurrentOfflineDatabase(Type itemType, string filenameModifier) { var fullName = GetFileName(itemType.ToString()); if (fullName.Length > 100) fullName = fullName.Substring(0, 100); @@ -78,12 +75,10 @@ namespace Firebase.Database.Offline /// /// The key of the element to get or set. /// The element with the specified key. - public OfflineEntry this[string key] - { + public OfflineEntry this[string key] { get => ccache[key]; - set - { + set { ccache.AddOrUpdate(key, value, (k, existing) => value); db.Upsert(value); } @@ -93,13 +88,11 @@ namespace Firebase.Database.Offline /// Returns an enumerator that iterates through the collection. /// /// An enumerator that can be used to iterate through the collection. - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return ccache.GetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } @@ -107,16 +100,14 @@ namespace Firebase.Database.Offline /// Adds an item to the . /// /// The object to add to the . - public void Add(KeyValuePair item) - { + public void Add(KeyValuePair item) { Add(item.Key, item.Value); } /// /// Removes all items from the . /// - public void Clear() - { + public void Clear() { ccache.Clear(); db.Delete(LiteDB.Query.All()); } @@ -129,8 +120,7 @@ namespace Firebase.Database.Offline /// True if is found in the ; /// otherwise, false. /// - public bool Contains(KeyValuePair item) - { + public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } @@ -144,8 +134,7 @@ namespace Firebase.Database.Offline /// zero-based indexing. /// /// The zero-based index in at which copying begins. - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { + public void CopyTo(KeyValuePair[] array, int arrayIndex) { ccache.ToList().CopyTo(array, arrayIndex); } @@ -159,8 +148,7 @@ namespace Firebase.Database.Offline /// ; otherwise, false. This method also returns false if /// is not found in the original . /// - public bool Remove(KeyValuePair item) - { + public bool Remove(KeyValuePair item) { return Remove(item.Key); } @@ -173,8 +161,7 @@ namespace Firebase.Database.Offline /// True if the contains an element with the key; /// otherwise, false. /// - public bool ContainsKey(string key) - { + public bool ContainsKey(string key) { return ccache.ContainsKey(key); } @@ -183,8 +170,7 @@ namespace Firebase.Database.Offline /// /// The object to use as the key of the element to add. /// The object to use as the value of the element to add. - public void Add(string key, OfflineEntry value) - { + public void Add(string key, OfflineEntry value) { ccache.AddOrUpdate(key, value, (k, existing) => value); db.Upsert(value); } @@ -197,8 +183,7 @@ namespace Firebase.Database.Offline /// True if the element is successfully removed; otherwise, false. This method also returns false if /// was not found in the original . /// - public bool Remove(string key) - { + public bool Remove(string key) { ccache.TryRemove(key, out _); return db.Delete(key); } @@ -216,13 +201,11 @@ namespace Firebase.Database.Offline /// True if the object that implements contains an /// element with the specified key; otherwise, false. /// - public bool TryGetValue(string key, out OfflineEntry value) - { + public bool TryGetValue(string key, out OfflineEntry value) { return ccache.TryGetValue(key, out value); } - private string GetFileName(string fileName) - { + private string GetFileName(string fileName) { var invalidChars = new[] {'`', '[', ',', '='}; foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct()) fileName = fileName.Replace(c, '_'); diff --git a/dsa/FireBase/Offline/DatabaseExtensions.cs b/dsa/FireBase/Offline/DatabaseExtensions.cs index e7c4074..75624f1 100644 --- a/dsa/FireBase/Offline/DatabaseExtensions.cs +++ b/dsa/FireBase/Offline/DatabaseExtensions.cs @@ -4,10 +4,8 @@ using System.Linq.Expressions; using System.Reflection; using Firebase.Database.Query; -namespace Firebase.Database.Offline -{ - public static class DatabaseExtensions - { +namespace Firebase.Database.Offline { + public static class DatabaseExtensions { /// /// Create new instances of the . /// @@ -24,8 +22,7 @@ namespace Firebase.Database.Offline public static RealtimeDatabase AsRealtimeDatabase(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) - where T : class - { + where T : class { return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges); } @@ -49,8 +46,7 @@ namespace Firebase.Database.Offline StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class - where TSetHandler : ISetHandler, new() - { + where TSetHandler : ISetHandler, new() { return new RealtimeDatabase(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges, Activator.CreateInstance()); @@ -68,8 +64,7 @@ namespace Firebase.Database.Offline /// public static void Patch(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -85,8 +80,7 @@ namespace Firebase.Database.Offline /// public static void Put(this RealtimeDatabase db, string key, T obj, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -101,8 +95,7 @@ namespace Firebase.Database.Offline /// /// The generated key for this object. public static string Post(this RealtimeDatabase db, T obj, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { var key = FirebaseKeyGenerator.Next(); db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); @@ -120,8 +113,7 @@ namespace Firebase.Database.Offline /// priority. /// public static void Delete(this RealtimeDatabase db, string key, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -143,8 +135,7 @@ namespace Firebase.Database.Offline public static void Put(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -166,8 +157,7 @@ namespace Firebase.Database.Offline public static void Patch(this RealtimeDatabase db, string key, Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -189,8 +179,7 @@ namespace Firebase.Database.Offline public static void Delete(this RealtimeDatabase db, string key, Expression> propertyExpression, bool syncOnline = true, int priority = 1) where T : class - where TProperty : class - { + where TProperty : class { db.Set(key, propertyExpression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -215,8 +204,7 @@ namespace Firebase.Database.Offline Expression> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) where T : class - where TSelector : IDictionary - { + where TSelector : IDictionary { var nextKey = FirebaseKeyGenerator.Next(); var expression = Expression.Lambda>( Expression.Call(propertyExpression.Body, @@ -245,8 +233,7 @@ namespace Firebase.Database.Offline public static void Delete(this RealtimeDatabase db, string key, Expression>> propertyExpression, string dictionaryKey, bool syncOnline = true, int priority = 1) - where T : class - { + where T : class { var expression = Expression.Lambda>( Expression.Call(propertyExpression.Body, typeof(IDictionary).GetRuntimeMethod("get_Item", new[] {typeof(string)}), diff --git a/dsa/FireBase/Offline/ISetHandler.cs b/dsa/FireBase/Offline/ISetHandler.cs index c04bd41..699d33a 100644 --- a/dsa/FireBase/Offline/ISetHandler.cs +++ b/dsa/FireBase/Offline/ISetHandler.cs @@ -1,10 +1,8 @@ using System.Threading.Tasks; using Firebase.Database.Query; -namespace Firebase.Database.Offline -{ - public interface ISetHandler - { +namespace Firebase.Database.Offline { + public interface ISetHandler { Task SetAsync(ChildQuery query, string key, OfflineEntry entry); } } \ No newline at end of file diff --git a/dsa/FireBase/Offline/InitialPullStrategy.cs b/dsa/FireBase/Offline/InitialPullStrategy.cs index ca2bebf..292c716 100644 --- a/dsa/FireBase/Offline/InitialPullStrategy.cs +++ b/dsa/FireBase/Offline/InitialPullStrategy.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// Specifies the strategy for initial pull of server data. /// - public enum InitialPullStrategy - { + public enum InitialPullStrategy { /// /// Don't pull anything. /// diff --git a/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs b/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs index 89a77da..fe888ac 100644 --- a/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs +++ b/dsa/FireBase/Offline/Internals/MemberAccessVisitor.cs @@ -3,37 +3,29 @@ using System.Linq.Expressions; using System.Reflection; using Newtonsoft.Json; -namespace Firebase.Database.Offline.Internals -{ - public class MemberAccessVisitor : ExpressionVisitor - { +namespace Firebase.Database.Offline.Internals { + public class MemberAccessVisitor : ExpressionVisitor { private readonly IList propertyNames = new List(); private bool wasDictionaryAccess; public IEnumerable PropertyNames => propertyNames; - public override Expression Visit(Expression expr) - { - if (expr?.NodeType == ExpressionType.MemberAccess) - { - if (wasDictionaryAccess) - { + public override Expression Visit(Expression expr) { + if (expr?.NodeType == ExpressionType.MemberAccess) { + if (wasDictionaryAccess) { wasDictionaryAccess = false; } - else - { + else { var memberExpr = (MemberExpression) expr; var jsonAttr = memberExpr.Member.GetCustomAttribute(); propertyNames.Add(jsonAttr?.PropertyName ?? memberExpr.Member.Name); } } - else if (expr?.NodeType == ExpressionType.Call) - { + else if (expr?.NodeType == ExpressionType.Call) { var callExpr = (MethodCallExpression) expr; - if (callExpr.Method.Name == "get_Item" && callExpr.Arguments.Count == 1) - { + if (callExpr.Method.Name == "get_Item" && callExpr.Arguments.Count == 1) { var e = Expression.Lambda(callExpr.Arguments[0]).Compile(); propertyNames.Add(e.DynamicInvoke().ToString()); wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess; diff --git a/dsa/FireBase/Offline/OfflineCacheAdapter.cs b/dsa/FireBase/Offline/OfflineCacheAdapter.cs index 3153d1b..9881c78 100644 --- a/dsa/FireBase/Offline/OfflineCacheAdapter.cs +++ b/dsa/FireBase/Offline/OfflineCacheAdapter.cs @@ -3,19 +3,15 @@ using System.Collections; using System.Collections.Generic; using System.Linq; -namespace Firebase.Database.Offline -{ - internal class OfflineCacheAdapter : IDictionary, IDictionary - { +namespace Firebase.Database.Offline { + internal class OfflineCacheAdapter : IDictionary, IDictionary { private readonly IDictionary database; - public OfflineCacheAdapter(IDictionary database) - { + public OfflineCacheAdapter(IDictionary database) { this.database = database; } - public void CopyTo(Array array, int index) - { + public void CopyTo(Array array, int index) { throw new NotImplementedException(); } @@ -23,12 +19,10 @@ namespace Firebase.Database.Offline public object SyncRoot { get; } - object IDictionary.this[object key] - { + object IDictionary.this[object key] { get => database[key.ToString()].Deserialize(); - set - { + set { var keyString = key.ToString(); if (database.ContainsKey(keyString)) database[keyString] = new OfflineEntry(keyString, value, database[keyString].Priority, @@ -42,25 +36,21 @@ namespace Firebase.Database.Offline ICollection IDictionary.Keys { get; } - public bool Contains(object key) - { + public bool Contains(object key) { return ContainsKey(key.ToString()); } - IDictionaryEnumerator IDictionary.GetEnumerator() - { + IDictionaryEnumerator IDictionary.GetEnumerator() { throw new NotImplementedException(); } - public void Remove(object key) - { + public void Remove(object key) { Remove(key.ToString()); } public bool IsFixedSize => false; - public void Add(object key, object value) - { + public void Add(object key, object value) { Add(key.ToString(), (T) value); } @@ -72,12 +62,10 @@ namespace Firebase.Database.Offline public ICollection Values => database.Values.Select(o => o.Deserialize()).ToList(); - public T this[string key] - { + public T this[string key] { get => database[key].Deserialize(); - set - { + set { if (database.ContainsKey(key)) database[key] = new OfflineEntry(key, value, database[key].Priority, database[key].SyncOptions); else @@ -85,62 +73,50 @@ namespace Firebase.Database.Offline } } - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return database.Select(d => new KeyValuePair(d.Key, d.Value.Deserialize())).GetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } - public void Add(KeyValuePair item) - { + public void Add(KeyValuePair item) { Add(item.Key, item.Value); } - public void Clear() - { + public void Clear() { database.Clear(); } - public bool Contains(KeyValuePair item) - { + public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { + public void CopyTo(KeyValuePair[] array, int arrayIndex) { throw new NotImplementedException(); } - public bool Remove(KeyValuePair item) - { + public bool Remove(KeyValuePair item) { return database.Remove(item.Key); } - public void Add(string key, T value) - { + public void Add(string key, T value) { database.Add(key, new OfflineEntry(key, value, 1, SyncOptions.None)); } - public bool ContainsKey(string key) - { + public bool ContainsKey(string key) { return database.ContainsKey(key); } - public bool Remove(string key) - { + public bool Remove(string key) { return database.Remove(key); } - public bool TryGetValue(string key, out T value) - { + public bool TryGetValue(string key, out T value) { OfflineEntry val; - if (database.TryGetValue(key, out val)) - { + if (database.TryGetValue(key, out val)) { value = val.Deserialize(); return true; } diff --git a/dsa/FireBase/Offline/OfflineDatabase.cs b/dsa/FireBase/Offline/OfflineDatabase.cs index be0380b..5820dc6 100644 --- a/dsa/FireBase/Offline/OfflineDatabase.cs +++ b/dsa/FireBase/Offline/OfflineDatabase.cs @@ -5,13 +5,11 @@ using System.IO; using System.Linq; using LiteDB; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// The offline database. /// - public class OfflineDatabase : IDictionary - { + public class OfflineDatabase : IDictionary { private readonly IDictionary cache; private readonly LiteRepository db; @@ -20,8 +18,7 @@ namespace Firebase.Database.Offline /// /// The item type which is used to determine the database file name. /// Custom string which will get appended to the file name. - public OfflineDatabase(Type itemType, string filenameModifier) - { + public OfflineDatabase(Type itemType, string filenameModifier) { var fullName = GetFileName(itemType.ToString()); if (fullName.Length > 100) fullName = fullName.Substring(0, 100); @@ -73,12 +70,10 @@ namespace Firebase.Database.Offline /// /// The key of the element to get or set. /// The element with the specified key. - public OfflineEntry this[string key] - { + public OfflineEntry this[string key] { get => cache[key]; - set - { + set { cache[key] = value; db.Upsert(value); } @@ -88,13 +83,11 @@ namespace Firebase.Database.Offline /// Returns an enumerator that iterates through the collection. /// /// An enumerator that can be used to iterate through the collection. - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return cache.GetEnumerator(); } - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } @@ -102,16 +95,14 @@ namespace Firebase.Database.Offline /// Adds an item to the . /// /// The object to add to the . - public void Add(KeyValuePair item) - { + public void Add(KeyValuePair item) { Add(item.Key, item.Value); } /// /// Removes all items from the . /// - public void Clear() - { + public void Clear() { cache.Clear(); db.Delete(LiteDB.Query.All()); } @@ -124,8 +115,7 @@ namespace Firebase.Database.Offline /// True if is found in the ; /// otherwise, false. /// - public bool Contains(KeyValuePair item) - { + public bool Contains(KeyValuePair item) { return ContainsKey(item.Key); } @@ -139,8 +129,7 @@ namespace Firebase.Database.Offline /// zero-based indexing. /// /// The zero-based index in at which copying begins. - public void CopyTo(KeyValuePair[] array, int arrayIndex) - { + public void CopyTo(KeyValuePair[] array, int arrayIndex) { cache.CopyTo(array, arrayIndex); } @@ -154,8 +143,7 @@ namespace Firebase.Database.Offline /// ; otherwise, false. This method also returns false if /// is not found in the original . /// - public bool Remove(KeyValuePair item) - { + public bool Remove(KeyValuePair item) { return Remove(item.Key); } @@ -168,8 +156,7 @@ namespace Firebase.Database.Offline /// True if the contains an element with the key; /// otherwise, false. /// - public bool ContainsKey(string key) - { + public bool ContainsKey(string key) { return cache.ContainsKey(key); } @@ -178,8 +165,7 @@ namespace Firebase.Database.Offline /// /// The object to use as the key of the element to add. /// The object to use as the value of the element to add. - public void Add(string key, OfflineEntry value) - { + public void Add(string key, OfflineEntry value) { cache.Add(key, value); db.Insert(value); } @@ -192,8 +178,7 @@ namespace Firebase.Database.Offline /// True if the element is successfully removed; otherwise, false. This method also returns false if /// was not found in the original . /// - public bool Remove(string key) - { + public bool Remove(string key) { cache.Remove(key); return db.Delete(key); } @@ -211,13 +196,11 @@ namespace Firebase.Database.Offline /// True if the object that implements contains an /// element with the specified key; otherwise, false. /// - public bool TryGetValue(string key, out OfflineEntry value) - { + public bool TryGetValue(string key, out OfflineEntry value) { return cache.TryGetValue(key, out value); } - private string GetFileName(string fileName) - { + private string GetFileName(string fileName) { var invalidChars = new[] {'`', '[', ',', '='}; foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct()) fileName = fileName.Replace(c, '_'); diff --git a/dsa/FireBase/Offline/OfflineEntry.cs b/dsa/FireBase/Offline/OfflineEntry.cs index 9feffa3..c959510 100644 --- a/dsa/FireBase/Offline/OfflineEntry.cs +++ b/dsa/FireBase/Offline/OfflineEntry.cs @@ -1,13 +1,11 @@ using System; using Newtonsoft.Json; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// Represents an object stored in offline storage. /// - public class OfflineEntry - { + public class OfflineEntry { private object dataInstance; /// @@ -21,8 +19,7 @@ namespace Firebase.Database.Offline /// /// The sync options. public OfflineEntry(string key, object obj, string data, int priority, SyncOptions syncOptions, - bool isPartial = false) - { + bool isPartial = false) { Key = key; Priority = priority; Data = data; @@ -44,15 +41,13 @@ namespace Firebase.Database.Offline /// /// The sync options. public OfflineEntry(string key, object obj, int priority, SyncOptions syncOptions, bool isPartial = false) - : this(key, obj, JsonConvert.SerializeObject(obj), priority, syncOptions, isPartial) - { + : this(key, obj, JsonConvert.SerializeObject(obj), priority, syncOptions, isPartial) { } /// /// Initializes a new instance of the class. /// - public OfflineEntry() - { + public OfflineEntry() { } /// @@ -91,8 +86,7 @@ namespace Firebase.Database.Offline /// /// Type of object to deserialize into. /// Instance of . - public T Deserialize() - { + public T Deserialize() { return (T) (dataInstance ?? (dataInstance = JsonConvert.DeserializeObject(Data))); } } diff --git a/dsa/FireBase/Offline/RealtimeDatabase.cs b/dsa/FireBase/Offline/RealtimeDatabase.cs index 973db46..e66a1f1 100644 --- a/dsa/FireBase/Offline/RealtimeDatabase.cs +++ b/dsa/FireBase/Offline/RealtimeDatabase.cs @@ -16,14 +16,12 @@ using Firebase.Database.Query; using Firebase.Database.Streaming; using Newtonsoft.Json; -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// The real-time Database which synchronizes online and offline data. /// /// Type of entities. - public class RealtimeDatabase : IDisposable where T : class - { + public class RealtimeDatabase : IDisposable where T : class { private readonly ChildQuery childQuery; private readonly string elementRoot; private readonly FirebaseCache firebaseCache; @@ -55,8 +53,7 @@ namespace Firebase.Database.Offline public RealtimeDatabase(ChildQuery childQuery, string elementRoot, Func> offlineDatabaseFactory, string filenameModifier, StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, - ISetHandler setHandler = null) - { + ISetHandler setHandler = null) { this.childQuery = childQuery; this.elementRoot = elementRoot; this.streamingOptions = streamingOptions; @@ -80,8 +77,7 @@ namespace Firebase.Database.Offline public ISetHandler PutHandler { private get; set; } - public void Dispose() - { + public void Dispose() { subject.OnCompleted(); firebaseSubscription?.Dispose(); } @@ -102,19 +98,16 @@ namespace Firebase.Database.Offline /// The priority. Objects with higher priority will be synced first. Higher number indicates higher /// priority. /// - public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1) - { + public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1) { SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions)); } public void Set(string key, Expression> propertyExpression, object value, - SyncOptions syncOptions, int priority = 1) - { + SyncOptions syncOptions, int priority = 1) { var fullKey = GenerateFullKey(key, propertyExpression, syncOptions); var serializedObject = JsonConvert.SerializeObject(value).Trim('"', '\\'); - if (fullKey.Item3) - { + if (fullKey.Item3) { if (typeof(TProperty) != typeof(string) || value == null) // don't escape non-string primitives and null; serializedObject = $"{{ \"{fullKey.Item2}\" : {serializedObject} }}"; @@ -142,8 +135,7 @@ namespace Firebase.Database.Offline /// The priority. Objects with higher priority will be synced first. Higher number indicates higher /// priority. /// - public void Pull(string key, int priority = 1) - { + public void Pull(string key, int priority = 1) { if (!Database.ContainsKey(key)) Database[key] = new OfflineEntry(key, null, priority, SyncOptions.Pull); else if (Database[key].SyncOptions == SyncOptions.None) @@ -154,8 +146,7 @@ namespace Firebase.Database.Offline /// /// Fetches everything from the remote database. /// - public async Task PullAsync() - { + public async Task PullAsync() { var existingEntries = await childQuery .OnceAsync() .ToObservable() @@ -166,8 +157,7 @@ namespace Firebase.Database.Offline .OK) // OK implies the request couldn't complete due to network error. .Select(e => ResetDatabaseFromInitial(e, false)) .SelectMany(e => e) - .Do(e => - { + .Do(e => { Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None); subject.OnNext(new FirebaseEvent(e.Key, e.Object, FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePull)); @@ -175,8 +165,7 @@ namespace Firebase.Database.Offline .ToList(); // Remove items not stored online - foreach (var item in Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList()) - { + foreach (var item in Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList()) { Database.Remove(item); subject.OnNext(new FirebaseEvent(item, null, FirebaseEventType.Delete, FirebaseEventSource.OnlinePull)); @@ -186,8 +175,7 @@ namespace Firebase.Database.Offline /// /// Retrieves all offline items currently stored in local database. /// - public IEnumerable> Once() - { + public IEnumerable> Once() { return Database .Where(kvp => !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial) .Select(kvp => new FirebaseObject(kvp.Key, kvp.Value.Deserialize())) @@ -198,17 +186,14 @@ namespace Firebase.Database.Offline /// Starts observing the real-time Database. Events will be fired both when change is done locally and remotely. /// /// Stream of . - public IObservable> AsObservable() - { - if (!isSyncRunning) - { + public IObservable> AsObservable() { + if (!isSyncRunning) { isSyncRunning = true; Task.Factory.StartNew(SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } - if (observable == null) - { + if (observable == null) { var initialData = Observable.Return(FirebaseEvent.Empty(FirebaseEventSource.Offline)); if (Database.TryGetValue(elementRoot, out var oe)) initialData = Observable.Return(oe) @@ -251,8 +236,7 @@ namespace Firebase.Database.Offline } private IReadOnlyCollection> ResetDatabaseFromInitial( - IReadOnlyCollection> collection, bool onlyWhenInitialEverything = true) - { + IReadOnlyCollection> collection, bool onlyWhenInitialEverything = true) { if (onlyWhenInitialEverything && initialPullStrategy != InitialPullStrategy.Everything) return collection; // items which are in local db, but not in the online collection @@ -264,8 +248,7 @@ namespace Firebase.Database.Offline return collection.Concat(extra).ToList(); } - private void SetObjectFromInitialPull(FirebaseObject e) - { + private void SetObjectFromInitialPull(FirebaseObject e) { // set object with no sync only if it doesn't exist yet // and the InitialPullStrategy != Everything // this attempts to deal with scenario when you are offline, have local changes and go online @@ -276,11 +259,9 @@ namespace Firebase.Database.Offline Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None); } - private IObservable>> GetInitialPullObservable() - { + private IObservable>> GetInitialPullObservable() { FirebaseQuery query; - switch (initialPullStrategy) - { + switch (initialPullStrategy) { case InitialPullStrategy.MissingOnly: query = childQuery.OrderByKey().StartAt(() => GetLatestKey()); break; @@ -301,12 +282,10 @@ namespace Firebase.Database.Offline .Select(e => new[] {new FirebaseObject(elementRoot, e)})); } - private IDisposable InitializeStreamingSubscription(IObserver> observer) - { + private IDisposable InitializeStreamingSubscription(IObserver> observer) { var completeDisposable = Disposable.Create(() => isSyncRunning = false); - switch (streamingOptions) - { + switch (streamingOptions) { case StreamingOptions.LatestOnly: // stream since the latest key var queryLatest = childQuery.OrderByKey().StartAt(() => GetLatestKey()); @@ -328,8 +307,7 @@ namespace Firebase.Database.Offline } private void SetAndRaise(string key, OfflineEntry obj, - FirebaseEventSource eventSource = FirebaseEventSource.Offline) - { + FirebaseEventSource eventSource = FirebaseEventSource.Offline) { Database[key] = obj; subject.OnNext(new FirebaseEvent(key, obj?.Deserialize(), string.IsNullOrEmpty(obj?.Data) || obj?.Data == "null" @@ -337,12 +315,9 @@ namespace Firebase.Database.Offline : FirebaseEventType.InsertOrUpdate, eventSource)); } - private async void SynchronizeThread() - { - while (isSyncRunning) - { - try - { + private async void SynchronizeThread() { + while (isSyncRunning) { + try { var validEntries = Database.Where(e => e.Value != null); await PullEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Pull)); @@ -350,8 +325,7 @@ namespace Firebase.Database.Offline await PushEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Put || kvp.Value.SyncOptions == SyncOptions.Patch)); } - catch (Exception ex) - { + catch (Exception ex) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } @@ -359,8 +333,7 @@ namespace Firebase.Database.Offline } } - private string GetLatestKey() - { + private string GetLatestKey() { var key = Database.OrderBy(o => o.Key, StringComparer.Ordinal).LastOrDefault().Key ?? string.Empty; if (!string.IsNullOrWhiteSpace(key)) @@ -369,60 +342,50 @@ namespace Firebase.Database.Offline return key; } - private async Task PushEntriesAsync(IEnumerable> pushEntries) - { + private async Task PushEntriesAsync(IEnumerable> pushEntries) { var groups = pushEntries.GroupBy(pair => pair.Value.Priority).OrderByDescending(kvp => kvp.Key).ToList(); - foreach (var group in groups) - { + foreach (var group in groups) { var tasks = group.OrderBy(kvp => kvp.Value.IsPartial).Select(kvp => kvp.Value.IsPartial ? ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key) : ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key, kvp.Value.Deserialize())); - try - { + try { await Task.WhenAll(tasks).WithAggregateException(); } - catch (Exception ex) - { + catch (Exception ex) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } } } - private async Task PullEntriesAsync(IEnumerable> pullEntries) - { + private async Task PullEntriesAsync(IEnumerable> pullEntries) { var taskGroups = pullEntries.GroupBy(pair => pair.Value.Priority).OrderByDescending(kvp => kvp.Key); - foreach (var group in taskGroups) - { + foreach (var group in taskGroups) { var tasks = group.Select(pair => ResetAfterPull( childQuery.Child(pair.Key == elementRoot ? string.Empty : pair.Key).OnceSingleAsync(), pair.Key, pair.Value)); - try - { + try { await Task.WhenAll(tasks).WithAggregateException(); } - catch (Exception ex) - { + catch (Exception ex) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } } } - private async Task ResetAfterPull(Task task, string key, OfflineEntry entry) - { + private async Task ResetAfterPull(Task task, string key, OfflineEntry entry) { await task; SetAndRaise(key, new OfflineEntry(key, task.Result, entry.Priority, SyncOptions.None), FirebaseEventSource.OnlinePull); } - private async Task ResetSyncAfterPush(Task task, string key, T obj) - { + private async Task ResetSyncAfterPush(Task task, string key, T obj) { await ResetSyncAfterPush(task, key); if (streamingOptions == StreamingOptions.None) @@ -431,35 +394,29 @@ namespace Firebase.Database.Offline FirebaseEventSource.OnlinePush)); } - private async Task ResetSyncAfterPush(Task task, string key) - { + private async Task ResetSyncAfterPush(Task task, string key) { await task; ResetSyncOptions(key); } - private void ResetSyncOptions(string key) - { + private void ResetSyncOptions(string key) { var item = Database[key]; - if (item.IsPartial) - { + if (item.IsPartial) { Database.Remove(key); } - else - { + else { item.SyncOptions = SyncOptions.None; Database[key] = item; } } - private void StreamingExceptionThrown(object sender, ExceptionEventArgs e) - { + private void StreamingExceptionThrown(object sender, ExceptionEventArgs e) { SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception)); } private Tuple GenerateFullKey(string key, - Expression> propertyGetter, SyncOptions syncOptions) - { + Expression> propertyGetter, SyncOptions syncOptions) { var visitor = new MemberAccessVisitor(); visitor.Visit(propertyGetter); var propertyType = typeof(TProperty).GetTypeInfo(); diff --git a/dsa/FireBase/Offline/SetHandler.cs b/dsa/FireBase/Offline/SetHandler.cs index 6314c3c..c683fdd 100644 --- a/dsa/FireBase/Offline/SetHandler.cs +++ b/dsa/FireBase/Offline/SetHandler.cs @@ -1,14 +1,10 @@ using System.Threading.Tasks; using Firebase.Database.Query; -namespace Firebase.Database.Offline -{ - public class SetHandler : ISetHandler - { - public virtual async Task SetAsync(ChildQuery query, string key, OfflineEntry entry) - { - using (var child = query.Child(key)) - { +namespace Firebase.Database.Offline { + public class SetHandler : ISetHandler { + public virtual async Task SetAsync(ChildQuery query, string key, OfflineEntry entry) { + using (var child = query.Child(key)) { if (entry.SyncOptions == SyncOptions.Put) await child.PutAsync(entry.Data); else diff --git a/dsa/FireBase/Offline/StreamingOptions.cs b/dsa/FireBase/Offline/StreamingOptions.cs index a420cbb..205118d 100644 --- a/dsa/FireBase/Offline/StreamingOptions.cs +++ b/dsa/FireBase/Offline/StreamingOptions.cs @@ -1,7 +1,5 @@ -namespace Firebase.Database.Offline -{ - public enum StreamingOptions - { +namespace Firebase.Database.Offline { + public enum StreamingOptions { /// /// No realtime streaming. /// diff --git a/dsa/FireBase/Offline/SyncOptions.cs b/dsa/FireBase/Offline/SyncOptions.cs index ca68d0a..3b6e9c8 100644 --- a/dsa/FireBase/Offline/SyncOptions.cs +++ b/dsa/FireBase/Offline/SyncOptions.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Offline -{ +namespace Firebase.Database.Offline { /// /// Specifies type of sync requested for given data. /// - public enum SyncOptions - { + public enum SyncOptions { /// /// No sync needed for given data. /// diff --git a/dsa/FireBase/Query/AuthQuery.cs b/dsa/FireBase/Query/AuthQuery.cs index 2cfda3c..a3b06bd 100644 --- a/dsa/FireBase/Query/AuthQuery.cs +++ b/dsa/FireBase/Query/AuthQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents an auth parameter in firebase query, e.g. "?auth=xyz". /// - public class AuthQuery : ParameterQuery - { + public class AuthQuery : ParameterQuery { private readonly Func tokenFactory; /// @@ -16,8 +14,7 @@ namespace Firebase.Database.Query /// The authentication token factory. /// The owner. public AuthQuery(FirebaseQuery parent, Func tokenFactory, FirebaseClient client) : base(parent, - () => client.Options.AsAccessToken ? "access_token" : "auth", client) - { + () => client.Options.AsAccessToken ? "access_token" : "auth", client) { this.tokenFactory = tokenFactory; } @@ -26,8 +23,7 @@ namespace Firebase.Database.Query /// /// The child of this child. /// The . - protected override string BuildUrlParameter(FirebaseQuery child) - { + protected override string BuildUrlParameter(FirebaseQuery child) { return tokenFactory(); } } diff --git a/dsa/FireBase/Query/ChildQuery.cs b/dsa/FireBase/Query/ChildQuery.cs index 014fe09..579bd0a 100644 --- a/dsa/FireBase/Query/ChildQuery.cs +++ b/dsa/FireBase/Query/ChildQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Firebase query which references the child of current node. /// - public class ChildQuery : FirebaseQuery - { + public class ChildQuery : FirebaseQuery { private readonly Func pathFactory; /// @@ -16,8 +14,7 @@ namespace Firebase.Database.Query /// The path to the child node. /// The owner. public ChildQuery(FirebaseQuery parent, Func pathFactory, FirebaseClient client) - : base(parent, client) - { + : base(parent, client) { this.pathFactory = pathFactory; } @@ -27,8 +24,7 @@ namespace Firebase.Database.Query /// The client. /// The path to the child node. public ChildQuery(FirebaseClient client, Func pathFactory) - : this(null, pathFactory, client) - { + : this(null, pathFactory, client) { } /// @@ -36,8 +32,7 @@ namespace Firebase.Database.Query /// /// The child of this child. /// The . - protected override string BuildUrlSegment(FirebaseQuery child) - { + protected override string BuildUrlSegment(FirebaseQuery child) { var s = pathFactory(); if (s != string.Empty && !s.EndsWith("/")) s += '/'; diff --git a/dsa/FireBase/Query/FilterQuery.cs b/dsa/FireBase/Query/FilterQuery.cs index 3434d1d..c0c4dc2 100644 --- a/dsa/FireBase/Query/FilterQuery.cs +++ b/dsa/FireBase/Query/FilterQuery.cs @@ -1,13 +1,11 @@ using System; using System.Globalization; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a firebase filtering query, e.g. "?LimitToLast=10". /// - public class FilterQuery : ParameterQuery - { + public class FilterQuery : ParameterQuery { private readonly Func boolValueFactory; private readonly Func doubleValueFactory; private readonly Func valueFactory; @@ -21,8 +19,7 @@ namespace Firebase.Database.Query /// The owning client. public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) - : base(parent, filterFactory, client) - { + : base(parent, filterFactory, client) { this.valueFactory = valueFactory; } @@ -35,8 +32,7 @@ namespace Firebase.Database.Query /// The owning client. public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) - : base(parent, filterFactory, client) - { + : base(parent, filterFactory, client) { doubleValueFactory = valueFactory; } @@ -49,8 +45,7 @@ namespace Firebase.Database.Query /// The owning client. public FilterQuery(FirebaseQuery parent, Func filterFactory, Func valueFactory, FirebaseClient client) - : base(parent, filterFactory, client) - { + : base(parent, filterFactory, client) { boolValueFactory = valueFactory; } @@ -59,10 +54,8 @@ namespace Firebase.Database.Query /// /// The child. /// Url parameter part of the resulting path. - protected override string BuildUrlParameter(FirebaseQuery child) - { - if (valueFactory != null) - { + protected override string BuildUrlParameter(FirebaseQuery child) { + if (valueFactory != null) { if (valueFactory() == null) return "null"; return $"\"{valueFactory()}\""; } diff --git a/dsa/FireBase/Query/FirebaseQuery.cs b/dsa/FireBase/Query/FirebaseQuery.cs index 60d0289..91e7afa 100644 --- a/dsa/FireBase/Query/FirebaseQuery.cs +++ b/dsa/FireBase/Query/FirebaseQuery.cs @@ -8,13 +8,11 @@ using Firebase.Database.Http; using Firebase.Database.Streaming; using Newtonsoft.Json; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a firebase query. /// - public abstract class FirebaseQuery : IFirebaseQuery, IDisposable - { + public abstract class FirebaseQuery : IFirebaseQuery, IDisposable { protected readonly FirebaseQuery Parent; private HttpClient client; @@ -25,8 +23,7 @@ namespace Firebase.Database.Query /// /// The parent of this query. /// The owning client. - protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client) - { + protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client) { Client = client; Parent = parent; } @@ -34,8 +31,7 @@ namespace Firebase.Database.Query /// /// Disposes this instance. /// - public void Dispose() - { + public void Dispose() { client?.Dispose(); } @@ -50,16 +46,13 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of elements. /// Collection of holding the entities returned by server. - public async Task>> OnceAsync(TimeSpan? timeout = null) - { + public async Task>> OnceAsync(TimeSpan? timeout = null) { var url = string.Empty; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", string.Empty, string.Empty, HttpStatusCode.OK, ex); } @@ -75,10 +68,8 @@ namespace Firebase.Database.Query /// Optional custom root element of received json items. /// Observable stream of . public IObservable> AsObservable( - EventHandler> exceptionHandler = null, string elementRoot = "") - { - return Observable.Create>(observer => - { + EventHandler> exceptionHandler = null, string elementRoot = "") { + return Observable.Create>(observer => { var sub = new FirebaseSubscription(observer, this, elementRoot, new FirebaseCache()); sub.ExceptionThrown += exceptionHandler; return sub.Run(); @@ -89,11 +80,9 @@ namespace Firebase.Database.Query /// Builds the actual URL of this query. /// /// The . - public async Task BuildUrlAsync() - { + public async Task BuildUrlAsync() { // if token factory is present on the parent then use it to generate auth token - if (Client.Options.AuthTokenAsyncFactory != null) - { + if (Client.Options.AuthTokenAsyncFactory != null) { var token = await Client.Options.AuthTokenAsyncFactory().ConfigureAwait(false); return this.WithAuth(token).BuildUrl(null); } @@ -124,23 +113,19 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of elements. /// Single object of type . - public async Task OnceSingleAsync(TimeSpan? timeout = null) - { + public async Task OnceSingleAsync(TimeSpan? timeout = null) { var responseData = string.Empty; var statusCode = HttpStatusCode.OK; var url = string.Empty; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", string.Empty, responseData, statusCode, ex); } - try - { + try { var response = await GetClient(timeout).GetAsync(url).ConfigureAwait(false); statusCode = response.StatusCode; responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -150,8 +135,7 @@ namespace Firebase.Database.Query return JsonConvert.DeserializeObject(responseData, Client.Options.JsonSerializerSettings); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(url, string.Empty, responseData, statusCode, ex); } } @@ -165,11 +149,9 @@ namespace Firebase.Database.Query /// Type of /// Resulting firebase object with populated key. public async Task> PostAsync(string data, bool generateKeyOffline = true, - TimeSpan? timeout = null) - { + TimeSpan? timeout = null) { // post generates a new key server-side, while put can be used with an already generated local key - if (generateKeyOffline) - { + if (generateKeyOffline) { var key = FirebaseKeyGenerator.Next(); await new ChildQuery(this, () => key, Client).PutAsync(data).ConfigureAwait(false); @@ -190,8 +172,7 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of /// The . - public async Task PatchAsync(string data, TimeSpan? timeout = null) - { + public async Task PatchAsync(string data, TimeSpan? timeout = null) { var c = GetClient(timeout); await this.Silent().SendAsync(c, data, new HttpMethod("PATCH")).ConfigureAwait(false); @@ -204,8 +185,7 @@ namespace Firebase.Database.Query /// Optional timeout value. /// Type of /// The . - public async Task PutAsync(string data, TimeSpan? timeout = null) - { + public async Task PutAsync(string data, TimeSpan? timeout = null) { var c = GetClient(timeout); await this.Silent().SendAsync(c, data, HttpMethod.Put).ConfigureAwait(false); @@ -216,32 +196,27 @@ namespace Firebase.Database.Query /// /// Optional timeout value. /// The . - public async Task DeleteAsync(TimeSpan? timeout = null) - { + public async Task DeleteAsync(TimeSpan? timeout = null) { var c = GetClient(timeout); var url = string.Empty; var responseData = string.Empty; var statusCode = HttpStatusCode.OK; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", string.Empty, responseData, statusCode, ex); } - try - { + try { var result = await c.DeleteAsync(url).ConfigureAwait(false); statusCode = result.StatusCode; responseData = await result.Content.ReadAsStringAsync().ConfigureAwait(false); result.EnsureSuccessStatusCode(); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(url, string.Empty, responseData, statusCode, ex); } } @@ -253,8 +228,7 @@ namespace Firebase.Database.Query /// The . protected abstract string BuildUrlSegment(FirebaseQuery child); - private string BuildUrl(FirebaseQuery child) - { + private string BuildUrl(FirebaseQuery child) { var url = BuildUrlSegment(child); if (Parent != null) url = Parent.BuildUrl(this) + url; @@ -262,8 +236,7 @@ namespace Firebase.Database.Query return url; } - private HttpClient GetClient(TimeSpan? timeout = null) - { + private HttpClient GetClient(TimeSpan? timeout = null) { if (client == null) client = new HttpClient(); if (!timeout.HasValue) @@ -274,29 +247,24 @@ namespace Firebase.Database.Query return client; } - private async Task SendAsync(HttpClient client, string data, HttpMethod method) - { + private async Task SendAsync(HttpClient client, string data, HttpMethod method) { var responseData = string.Empty; var statusCode = HttpStatusCode.OK; var requestData = data; var url = string.Empty; - try - { + try { url = await BuildUrlAsync().ConfigureAwait(false); } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException("Couldn't build the url", requestData, responseData, statusCode, ex); } - var message = new HttpRequestMessage(method, url) - { + var message = new HttpRequestMessage(method, url) { Content = new StringContent(requestData) }; - try - { + try { var result = await client.SendAsync(message).ConfigureAwait(false); statusCode = result.StatusCode; responseData = await result.Content.ReadAsStringAsync().ConfigureAwait(false); @@ -305,8 +273,7 @@ namespace Firebase.Database.Query return responseData; } - catch (Exception ex) - { + catch (Exception ex) { throw new FirebaseException(url, requestData, responseData, statusCode, ex); } } diff --git a/dsa/FireBase/Query/IFirebaseQuery.cs b/dsa/FireBase/Query/IFirebaseQuery.cs index 0da4b15..f31e39e 100644 --- a/dsa/FireBase/Query/IFirebaseQuery.cs +++ b/dsa/FireBase/Query/IFirebaseQuery.cs @@ -3,13 +3,11 @@ using System.Collections.Generic; using System.Threading.Tasks; using Firebase.Database.Streaming; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// The FirebaseQuery interface. /// - public interface IFirebaseQuery - { + public interface IFirebaseQuery { /// /// Gets the owning client of this query. /// diff --git a/dsa/FireBase/Query/OrderQuery.cs b/dsa/FireBase/Query/OrderQuery.cs index 302d1a3..bb5a536 100644 --- a/dsa/FireBase/Query/OrderQuery.cs +++ b/dsa/FireBase/Query/OrderQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a firebase ordering query, e.g. "?OrderBy=Foo". /// - public class OrderQuery : ParameterQuery - { + public class OrderQuery : ParameterQuery { private readonly Func propertyNameFactory; /// @@ -16,8 +14,7 @@ namespace Firebase.Database.Query /// The property name. /// The owning client. public OrderQuery(ChildQuery parent, Func propertyNameFactory, FirebaseClient client) - : base(parent, () => "orderBy", client) - { + : base(parent, () => "orderBy", client) { this.propertyNameFactory = propertyNameFactory; } @@ -26,8 +23,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - protected override string BuildUrlParameter(FirebaseQuery child) - { + protected override string BuildUrlParameter(FirebaseQuery child) { return $"\"{propertyNameFactory()}\""; } } diff --git a/dsa/FireBase/Query/ParameterQuery.cs b/dsa/FireBase/Query/ParameterQuery.cs index 572224c..84adc17 100644 --- a/dsa/FireBase/Query/ParameterQuery.cs +++ b/dsa/FireBase/Query/ParameterQuery.cs @@ -1,12 +1,10 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Represents a parameter in firebase query, e.g. "?data=foo". /// - public abstract class ParameterQuery : FirebaseQuery - { + public abstract class ParameterQuery : FirebaseQuery { private readonly Func parameterFactory; private readonly string separator; @@ -17,8 +15,7 @@ namespace Firebase.Database.Query /// The parameter. /// The owning client. protected ParameterQuery(FirebaseQuery parent, Func parameterFactory, FirebaseClient client) - : base(parent, client) - { + : base(parent, client) { this.parameterFactory = parameterFactory; separator = Parent is ChildQuery ? "?" : "&"; } @@ -28,8 +25,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - protected override string BuildUrlSegment(FirebaseQuery child) - { + protected override string BuildUrlSegment(FirebaseQuery child) { return $"{separator}{parameterFactory()}={BuildUrlParameter(child)}"; } diff --git a/dsa/FireBase/Query/QueryExtensions.cs b/dsa/FireBase/Query/QueryExtensions.cs index df2edfc..b86a877 100644 --- a/dsa/FireBase/Query/QueryExtensions.cs +++ b/dsa/FireBase/Query/QueryExtensions.cs @@ -3,21 +3,18 @@ using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Query extensions providing linq like syntax for firebase server methods. /// - public static class QueryExtensions - { + public static class QueryExtensions { /// /// Adds an auth parameter to the query. /// /// The child. /// The auth token. /// The . - internal static AuthQuery WithAuth(this FirebaseQuery node, string token) - { + internal static AuthQuery WithAuth(this FirebaseQuery node, string token) { return node.WithAuth(() => token); } @@ -26,8 +23,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - internal static SilentQuery Silent(this FirebaseQuery node) - { + internal static SilentQuery Silent(this FirebaseQuery node) { return new SilentQuery(node, node.Client); } @@ -37,8 +33,7 @@ namespace Firebase.Database.Query /// The child. /// The path of sub child. /// The . - public static ChildQuery Child(this ChildQuery node, string path) - { + public static ChildQuery Child(this ChildQuery node, string path) { return node.Child(() => path); } @@ -50,8 +45,7 @@ namespace Firebase.Database.Query /// The child. /// The property name. /// The . - public static OrderQuery OrderBy(this ChildQuery child, string propertyName) - { + public static OrderQuery OrderBy(this ChildQuery child, string propertyName) { return child.OrderBy(() => propertyName); } @@ -62,8 +56,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, string value) - { + public static FilterQuery StartAt(this ParameterQuery child, string value) { return child.StartAt(() => value); } @@ -74,8 +67,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, string value) - { + public static FilterQuery EndAt(this ParameterQuery child, string value) { return child.EndAt(() => value); } @@ -85,8 +77,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, string value) - { + public static FilterQuery EqualTo(this ParameterQuery child, string value) { return child.EqualTo(() => value); } @@ -97,8 +88,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, double value) - { + public static FilterQuery StartAt(this ParameterQuery child, double value) { return child.StartAt(() => value); } @@ -109,8 +99,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, double value) - { + public static FilterQuery EndAt(this ParameterQuery child, double value) { return child.EndAt(() => value); } @@ -120,8 +109,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, double value) - { + public static FilterQuery EqualTo(this ParameterQuery child, double value) { return child.EqualTo(() => value); } @@ -131,8 +119,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, bool value) - { + public static FilterQuery EqualTo(this ParameterQuery child, bool value) { return child.EqualTo(() => value); } @@ -141,8 +128,7 @@ namespace Firebase.Database.Query /// /// Current node. /// The . - public static FilterQuery EqualTo(this ParameterQuery child) - { + public static FilterQuery EqualTo(this ParameterQuery child) { return child.EqualTo(() => null); } @@ -152,8 +138,7 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToFirst(this ParameterQuery child, int count) - { + public static FilterQuery LimitToFirst(this ParameterQuery child, int count) { return child.LimitToFirst(() => count); } @@ -163,24 +148,20 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToLast(this ParameterQuery child, int count) - { + public static FilterQuery LimitToLast(this ParameterQuery child, int count) { return child.LimitToLast(() => count); } - public static Task PutAsync(this FirebaseQuery query, T obj) - { + public static Task PutAsync(this FirebaseQuery query, T obj) { return query.PutAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } - public static Task PatchAsync(this FirebaseQuery query, T obj) - { + public static Task PatchAsync(this FirebaseQuery query, T obj) { return query.PatchAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } public static async Task> PostAsync(this FirebaseQuery query, T obj, - bool generateKeyOffline = true) - { + bool generateKeyOffline = true) { var result = await query.PostAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings), generateKeyOffline); @@ -196,8 +177,7 @@ namespace Firebase.Database.Query /// Current node. /// Object to fan out. /// Locations where to store the item. - public static async Task FanOut(this ChildQuery child, T item, params string[] relativePaths) - { + public static async Task FanOut(this ChildQuery child, T item, params string[] relativePaths) { if (relativePaths == null) throw new ArgumentNullException(nameof(relativePaths)); var fanoutObject = new Dictionary(relativePaths.Length); diff --git a/dsa/FireBase/Query/QueryFactoryExtensions.cs b/dsa/FireBase/Query/QueryFactoryExtensions.cs index 71dae5c..879affc 100644 --- a/dsa/FireBase/Query/QueryFactoryExtensions.cs +++ b/dsa/FireBase/Query/QueryFactoryExtensions.cs @@ -1,20 +1,17 @@ using System; -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Query extensions providing linq like syntax for firebase server methods. /// - public static class QueryFactoryExtensions - { + public static class QueryFactoryExtensions { /// /// Adds an auth parameter to the query. /// /// The child. /// The auth token. /// The . - internal static AuthQuery WithAuth(this FirebaseQuery node, Func tokenFactory) - { + internal static AuthQuery WithAuth(this FirebaseQuery node, Func tokenFactory) { return new AuthQuery(node, tokenFactory, node.Client); } @@ -24,8 +21,7 @@ namespace Firebase.Database.Query /// The child. /// The path of sub child. /// The . - public static ChildQuery Child(this ChildQuery node, Func pathFactory) - { + public static ChildQuery Child(this ChildQuery node, Func pathFactory) { return new ChildQuery(node, pathFactory, node.Client); } @@ -37,8 +33,7 @@ namespace Firebase.Database.Query /// The child. /// The property name. /// The . - public static OrderQuery OrderBy(this ChildQuery child, Func propertyNameFactory) - { + public static OrderQuery OrderBy(this ChildQuery child, Func propertyNameFactory) { return new OrderQuery(child, propertyNameFactory, child.Client); } @@ -49,8 +44,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - public static OrderQuery OrderByKey(this ChildQuery child) - { + public static OrderQuery OrderByKey(this ChildQuery child) { return child.OrderBy("$key"); } @@ -61,8 +55,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - public static OrderQuery OrderByValue(this ChildQuery child) - { + public static OrderQuery OrderByValue(this ChildQuery child) { return child.OrderBy("$value"); } @@ -73,8 +66,7 @@ namespace Firebase.Database.Query /// /// The child. /// The . - public static OrderQuery OrderByPriority(this ChildQuery child) - { + public static OrderQuery OrderByPriority(this ChildQuery child) { return child.OrderBy("$priority"); } @@ -85,8 +77,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "startAt", valueFactory, child.Client); } @@ -97,8 +88,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "endAt", valueFactory, child.Client); } @@ -109,8 +99,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } @@ -121,8 +110,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery StartAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "startAt", valueFactory, child.Client); } @@ -133,8 +121,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EndAt(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "endAt", valueFactory, child.Client); } @@ -145,8 +132,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } @@ -157,8 +143,7 @@ namespace Firebase.Database.Query /// Current node. /// Value to start at. /// The . - public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) - { + public static FilterQuery EqualTo(this ParameterQuery child, Func valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); } @@ -168,8 +153,7 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToFirst(this ParameterQuery child, Func countFactory) - { + public static FilterQuery LimitToFirst(this ParameterQuery child, Func countFactory) { return new FilterQuery(child, () => "limitToFirst", () => countFactory(), child.Client); } @@ -179,8 +163,7 @@ namespace Firebase.Database.Query /// Current node. /// Number of elements. /// The . - public static FilterQuery LimitToLast(this ParameterQuery child, Func countFactory) - { + public static FilterQuery LimitToLast(this ParameterQuery child, Func countFactory) { return new FilterQuery(child, () => "limitToLast", () => countFactory(), child.Client); } } diff --git a/dsa/FireBase/Query/SilentQuery.cs b/dsa/FireBase/Query/SilentQuery.cs index d09d38b..525826a 100644 --- a/dsa/FireBase/Query/SilentQuery.cs +++ b/dsa/FireBase/Query/SilentQuery.cs @@ -1,17 +1,13 @@ -namespace Firebase.Database.Query -{ +namespace Firebase.Database.Query { /// /// Appends print=silent to the url. /// - public class SilentQuery : ParameterQuery - { + public class SilentQuery : ParameterQuery { public SilentQuery(FirebaseQuery parent, FirebaseClient client) - : base(parent, () => "print", client) - { + : base(parent, () => "print", client) { } - protected override string BuildUrlParameter(FirebaseQuery child) - { + protected override string BuildUrlParameter(FirebaseQuery child) { return "silent"; } } diff --git a/dsa/FireBase/Streaming/FirebaseCache.cs b/dsa/FireBase/Streaming/FirebaseCache.cs index 66241e0..be6f2c7 100644 --- a/dsa/FireBase/Streaming/FirebaseCache.cs +++ b/dsa/FireBase/Streaming/FirebaseCache.cs @@ -6,19 +6,16 @@ using System.Reflection; using Firebase.Database.Http; using Newtonsoft.Json; -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// The firebase cache. /// /// Type of top-level entities in the cache. - public class FirebaseCache : IEnumerable> - { + public class FirebaseCache : IEnumerable> { private readonly IDictionary dictionary; private readonly bool isDictionaryType; - private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings - { + private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace }; @@ -26,16 +23,14 @@ namespace Firebase.Database.Streaming /// Initializes a new instance of the class. /// public FirebaseCache() - : this(new Dictionary()) - { + : this(new Dictionary()) { } /// /// Initializes a new instance of the class and populates it with existing data. /// /// The existing items. - public FirebaseCache(IDictionary existingItems) - { + public FirebaseCache(IDictionary existingItems) { dictionary = existingItems; isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); } @@ -46,8 +41,7 @@ namespace Firebase.Database.Streaming /// The path of incoming data, separated by slash. /// The data in json format as returned by firebase. /// Collection of top-level entities which were affected by the push. - public IEnumerable> PushData(string path, string data, bool removeEmptyEntries = true) - { + public IEnumerable> PushData(string path, string data, bool removeEmptyEntries = true) { object obj = this.dictionary; Action primitiveObjSetter = null; Action objDeleter = null; @@ -57,8 +51,7 @@ namespace Firebase.Database.Streaming // first find where we should insert the data to foreach (var element in pathElements) - if (obj is IDictionary) - { + if (obj is IDictionary) { // if it's a dictionary, then it's just a matter of inserting into it / accessing existing object by key var dictionary = obj as IDictionary; var valueType = obj.GetType().GenericTypeArguments[1]; @@ -66,18 +59,15 @@ namespace Firebase.Database.Streaming primitiveObjSetter = d => dictionary[element] = d; objDeleter = () => dictionary.Remove(element); - if (dictionary.Contains(element)) - { + if (dictionary.Contains(element)) { obj = dictionary[element]; } - else - { + else { dictionary[element] = CreateInstance(valueType); obj = dictionary[element]; } } - else - { + else { // if it's not a dictionary, try to find the property of current object with the matching name var objParent = obj; var property = objParent @@ -89,16 +79,14 @@ namespace Firebase.Database.Streaming objDeleter = () => property.SetValue(objParent, null); primitiveObjSetter = d => property.SetValue(objParent, d); obj = property.GetValue(obj); - if (obj == null) - { + if (obj == null) { obj = CreateInstance(property.PropertyType); property.SetValue(objParent, obj); } } // if data is null (=empty string) delete it - if (string.IsNullOrWhiteSpace(data) || data == "null") - { + if (string.IsNullOrWhiteSpace(data) || data == "null") { var key = pathElements[0]; var target = dictionary[key]; @@ -109,15 +97,13 @@ namespace Firebase.Database.Streaming } // now insert the data - if (obj is IDictionary && !isDictionaryType) - { + if (obj is IDictionary && !isDictionaryType) { // insert data into dictionary and return it as a collection of FirebaseObject var dictionary = obj as IDictionary; var valueType = obj.GetType().GenericTypeArguments[1]; var objectCollection = data.GetObjectCollection(valueType); - foreach (var item in objectCollection) - { + foreach (var item in objectCollection) { dictionary[item.Key] = item.Object; // top level dictionary changed @@ -125,14 +111,12 @@ namespace Firebase.Database.Streaming } // nested dictionary changed - if (pathElements.Any()) - { + if (pathElements.Any()) { this.dictionary[pathElements[0]] = this.dictionary[pathElements[0]]; yield return new FirebaseObject(pathElements[0], this.dictionary[pathElements[0]]); } } - else - { + else { // set the data on a property of the given object var valueType = obj.GetType(); @@ -152,13 +136,11 @@ namespace Firebase.Database.Streaming } } - public bool Contains(string key) - { + public bool Contains(string key) { return dictionary.Keys.Contains(key); } - private object CreateInstance(Type type) - { + private object CreateInstance(Type type) { if (type == typeof(string)) return string.Empty; return Activator.CreateInstance(type); @@ -166,13 +148,11 @@ namespace Firebase.Database.Streaming #region IEnumerable - IEnumerator IEnumerable.GetEnumerator() - { + IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } - public IEnumerator> GetEnumerator() - { + public IEnumerator> GetEnumerator() { return dictionary.Select(p => new FirebaseObject(p.Key, p.Value)).GetEnumerator(); } diff --git a/dsa/FireBase/Streaming/FirebaseEvent.cs b/dsa/FireBase/Streaming/FirebaseEvent.cs index 1761a72..2a1ec6d 100644 --- a/dsa/FireBase/Streaming/FirebaseEvent.cs +++ b/dsa/FireBase/Streaming/FirebaseEvent.cs @@ -1,11 +1,9 @@ -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// Firebase event which hold and the object affected by the event. /// /// Type of object affected by the event. - public class FirebaseEvent : FirebaseObject - { + public class FirebaseEvent : FirebaseObject { /// /// Initializes a new instance of the class. /// @@ -13,8 +11,7 @@ namespace Firebase.Database.Streaming /// The object. /// The event type. public FirebaseEvent(string key, T obj, FirebaseEventType eventType, FirebaseEventSource eventSource) - : base(key, obj) - { + : base(key, obj) { EventType = eventType; EventSource = eventSource; } @@ -29,8 +26,7 @@ namespace Firebase.Database.Streaming /// public FirebaseEventType EventType { get; } - public static FirebaseEvent Empty(FirebaseEventSource source) - { + public static FirebaseEvent Empty(FirebaseEventSource source) { return new FirebaseEvent(string.Empty, default(T), FirebaseEventType.InsertOrUpdate, source); } } diff --git a/dsa/FireBase/Streaming/FirebaseEventSource.cs b/dsa/FireBase/Streaming/FirebaseEventSource.cs index b1385ca..9c14f83 100644 --- a/dsa/FireBase/Streaming/FirebaseEventSource.cs +++ b/dsa/FireBase/Streaming/FirebaseEventSource.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// Specifies the origin of given /// - public enum FirebaseEventSource - { + public enum FirebaseEventSource { /// /// Event comes from an offline source. /// diff --git a/dsa/FireBase/Streaming/FirebaseEventType.cs b/dsa/FireBase/Streaming/FirebaseEventType.cs index 7606331..e6127bf 100644 --- a/dsa/FireBase/Streaming/FirebaseEventType.cs +++ b/dsa/FireBase/Streaming/FirebaseEventType.cs @@ -1,10 +1,8 @@ -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// The type of event. /// - public enum FirebaseEventType - { + public enum FirebaseEventType { /// /// Item was inserted or updated. /// diff --git a/dsa/FireBase/Streaming/FirebaseServerEventType.cs b/dsa/FireBase/Streaming/FirebaseServerEventType.cs index 79c816d..9abdb43 100644 --- a/dsa/FireBase/Streaming/FirebaseServerEventType.cs +++ b/dsa/FireBase/Streaming/FirebaseServerEventType.cs @@ -1,7 +1,5 @@ -namespace Firebase.Database.Streaming -{ - internal enum FirebaseServerEventType - { +namespace Firebase.Database.Streaming { + internal enum FirebaseServerEventType { Put, Patch, diff --git a/dsa/FireBase/Streaming/FirebaseSubscription.cs b/dsa/FireBase/Streaming/FirebaseSubscription.cs index fb0f403..6488815 100644 --- a/dsa/FireBase/Streaming/FirebaseSubscription.cs +++ b/dsa/FireBase/Streaming/FirebaseSubscription.cs @@ -8,14 +8,12 @@ using System.Threading.Tasks; using Firebase.Database.Query; using Newtonsoft.Json.Linq; -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// The firebase subscription. /// /// Type of object to be streaming back to the called. - internal class FirebaseSubscription : IDisposable - { + internal class FirebaseSubscription : IDisposable { private static readonly HttpClient http; private readonly FirebaseCache cache; private readonly CancellationTokenSource cancel; @@ -24,10 +22,8 @@ namespace Firebase.Database.Streaming private readonly IObserver> observer; private readonly IFirebaseQuery query; - static FirebaseSubscription() - { - var handler = new HttpClientHandler - { + static FirebaseSubscription() { + var handler = new HttpClientHandler { AllowAutoRedirect = true, MaxAutomaticRedirections = 10, CookieContainer = new CookieContainer() @@ -47,8 +43,7 @@ namespace Firebase.Database.Streaming /// The query. /// The cache. public FirebaseSubscription(IObserver> observer, IFirebaseQuery query, string elementRoot, - FirebaseCache cache) - { + FirebaseCache cache) { this.observer = observer; this.query = query; this.elementRoot = elementRoot; @@ -57,30 +52,25 @@ namespace Firebase.Database.Streaming client = query.Client; } - public void Dispose() - { + public void Dispose() { cancel.Cancel(); } public event EventHandler> ExceptionThrown; - public IDisposable Run() - { + public IDisposable Run() { Task.Run(() => ReceiveThread()); return this; } - private async void ReceiveThread() - { - while (true) - { + private async void ReceiveThread() { + while (true) { var url = string.Empty; var line = string.Empty; var statusCode = HttpStatusCode.OK; - try - { + try { cancel.Token.ThrowIfCancellationRequested(); // initialize network connection @@ -97,10 +87,8 @@ namespace Firebase.Database.Streaming response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) - using (var reader = this.client.Options.SubscriptionStreamReaderFactory(stream)) - { - while (true) - { + using (var reader = this.client.Options.SubscriptionStreamReaderFactory(stream)) { + while (true) { cancel.Token.ThrowIfCancellationRequested(); line = reader.ReadLine()?.Trim(); @@ -110,8 +98,7 @@ namespace Firebase.Database.Streaming var tuple = line.Split(new[] {':'}, 2, StringSplitOptions.RemoveEmptyEntries) .Select(s => s.Trim()).ToArray(); - switch (tuple[0].ToLower()) - { + switch (tuple[0].ToLower()) { case "event": serverEvent = ParseServerEvent(serverEvent, tuple[1]); break; @@ -126,18 +113,15 @@ namespace Firebase.Database.Streaming } } } - catch (OperationCanceledException) - { + catch (OperationCanceledException) { break; } - catch (Exception ex) when (statusCode != HttpStatusCode.OK) - { + catch (Exception ex) when (statusCode != HttpStatusCode.OK) { observer.OnError(new FirebaseException(url, string.Empty, line, statusCode, ex)); Dispose(); break; } - catch (Exception ex) - { + catch (Exception ex) { ExceptionThrown?.Invoke(this, new ExceptionEventArgs(new FirebaseException(url, string.Empty, line, statusCode, ex))); @@ -147,10 +131,8 @@ namespace Firebase.Database.Streaming } } - private FirebaseServerEventType ParseServerEvent(FirebaseServerEventType serverEvent, string eventName) - { - switch (eventName) - { + private FirebaseServerEventType ParseServerEvent(FirebaseServerEventType serverEvent, string eventName) { + switch (eventName) { case "put": serverEvent = FirebaseServerEventType.Put; break; @@ -171,10 +153,8 @@ namespace Firebase.Database.Streaming return serverEvent; } - private void ProcessServerData(string url, FirebaseServerEventType serverEvent, string serverData) - { - switch (serverEvent) - { + private void ProcessServerData(string url, FirebaseServerEventType serverEvent, string serverData) { + switch (serverEvent) { case FirebaseServerEventType.Put: case FirebaseServerEventType.Patch: var result = JObject.Parse(serverData); @@ -183,8 +163,7 @@ namespace Firebase.Database.Streaming // If an elementRoot parameter is provided, but it's not in the cache, it was already deleted. So we can return an empty object. if (string.IsNullOrWhiteSpace(elementRoot) || !cache.Contains(elementRoot)) - if (path == "/" && data == string.Empty) - { + if (path == "/" && data == string.Empty) { observer.OnNext(FirebaseEvent.Empty(FirebaseEventSource.OnlineStream)); return; } @@ -209,8 +188,7 @@ namespace Firebase.Database.Streaming } } - private HttpClient GetHttpClient() - { + private HttpClient GetHttpClient() { return http; } } diff --git a/dsa/FireBase/Streaming/NonBlockingStreamReader.cs b/dsa/FireBase/Streaming/NonBlockingStreamReader.cs index 8228e32..805716b 100644 --- a/dsa/FireBase/Streaming/NonBlockingStreamReader.cs +++ b/dsa/FireBase/Streaming/NonBlockingStreamReader.cs @@ -1,8 +1,7 @@ using System.IO; using System.Text; -namespace Firebase.Database.Streaming -{ +namespace Firebase.Database.Streaming { /// /// When a regular is used in a UWP app its method /// tends to take a long @@ -11,8 +10,7 @@ namespace Firebase.Database.Streaming /// in your UWP app. Use to inject an instance of this class into your /// . /// - public class NonBlockingStreamReader : TextReader - { + public class NonBlockingStreamReader : TextReader { private const int DefaultBufferSize = 16000; private readonly byte[] buffer; private readonly int bufferSize; @@ -21,8 +19,7 @@ namespace Firebase.Database.Streaming private string cachedData; - public NonBlockingStreamReader(Stream stream, int bufferSize = DefaultBufferSize) - { + public NonBlockingStreamReader(Stream stream, int bufferSize = DefaultBufferSize) { this.stream = stream; this.bufferSize = bufferSize; buffer = new byte[bufferSize]; @@ -30,12 +27,10 @@ namespace Firebase.Database.Streaming cachedData = string.Empty; } - public override string ReadLine() - { + public override string ReadLine() { var currentString = TryGetNewLine(); - while (currentString == null) - { + while (currentString == null) { var read = stream.Read(buffer, 0, bufferSize); var str = Encoding.UTF8.GetString(buffer, 0, read); @@ -46,12 +41,10 @@ namespace Firebase.Database.Streaming return currentString; } - private string TryGetNewLine() - { + private string TryGetNewLine() { var newLine = cachedData.IndexOf('\n'); - if (newLine >= 0) - { + if (newLine >= 0) { var r = cachedData.Substring(0, newLine + 1); cachedData = cachedData.Remove(0, r.Length); return r.Trim(); -- cgit v1.2.3-70-g09d2