diff options
Diffstat (limited to 'FireBase')
40 files changed, 594 insertions, 737 deletions
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 @@ /// <param name="exception"> The exception. </param> public ExceptionEventArgs(T exception) { - this.Exception = exception; + Exception = exception; } } @@ -25,4 +25,4 @@ { } } -} +}
\ No newline at end of file diff --git a/FireBase/Extensions/ObservableExtensions.cs b/FireBase/Extensions/ObservableExtensions.cs index 12cd5f3..cb41bcc 100644 --- a/FireBase/Extensions/ObservableExtensions.cs +++ b/FireBase/Extensions/ObservableExtensions.cs @@ -19,22 +19,22 @@ this IObservable<T> source, TimeSpan dueTime, Func<TException, bool> retryOnError) - where TException: Exception + where TException : Exception { - int attempt = 0; + var attempt = 0; return Observable.Defer(() => - { - return ((++attempt == 1) ? source : source.DelaySubscription(dueTime)) - .Select(item => new Tuple<bool, T, Exception>(true, item, null)) - .Catch<Tuple<bool, T, Exception>, TException>(e => retryOnError(e) - ? Observable.Throw<Tuple<bool, T, Exception>>(e) - : Observable.Return(new Tuple<bool, T, Exception>(false, default(T), e))); - }) - .Retry() - .SelectMany(t => t.Item1 - ? Observable.Return(t.Item2) - : Observable.Throw<T>(t.Item3)); + { + return (++attempt == 1 ? source : source.DelaySubscription(dueTime)) + .Select(item => new Tuple<bool, T, Exception>(true, item, null)) + .Catch<Tuple<bool, T, Exception>, TException>(e => retryOnError(e) + ? Observable.Throw<Tuple<bool, T, Exception>>(e) + : Observable.Return(new Tuple<bool, T, Exception>(false, default(T), e))); + }) + .Retry() + .SelectMany(t => t.Item1 + ? Observable.Return(t.Item2) + : Observable.Throw<T>(t.Item3)); } } -} +}
\ No newline at end of file diff --git a/FireBase/Extensions/TaskExtensions.cs b/FireBase/Extensions/TaskExtensions.cs index 26bbde6..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; /// <summary> /// Firebase client which acts as an entry point to the online database. @@ -28,15 +27,12 @@ namespace Firebase.Database /// <param name="offlineDatabaseFactory"> Offline database. </param> public FirebaseClient(string baseUrl, FirebaseOptions options = null) { - this.HttpClient = new HttpClient(); - this.Options = options ?? new FirebaseOptions(); + HttpClient = new HttpClient(); + Options = options ?? new FirebaseOptions(); this.baseUrl = baseUrl; - if (!this.baseUrl.EndsWith("/")) - { - this.baseUrl += "/"; - } + if (!this.baseUrl.EndsWith("/")) this.baseUrl += "/"; } /// <summary> @@ -46,7 +42,7 @@ namespace Firebase.Database /// <returns> <see cref="ChildQuery"/>. </returns> 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; } /// <summary> /// Post data passed to the authentication service. /// </summary> - public string RequestData - { - get; - } + public string RequestData { get; } /// <summary> /// Original url of the request. /// </summary> - public string RequestUrl - { - get; - } + public string RequestUrl { get; } /// <summary> /// Response from the authentication service. /// </summary> - public string ResponseData - { - get; - } + public string ResponseData { get; } /// <summary> /// Status code of the response. /// </summary> - public HttpStatusCode StatusCode - { - get; - } + public HttpStatusCode StatusCode { get; } private static string GenerateExceptionMessage(string requestUrl, string requestData, string responseData) { - return $"Exception occured while processing the request.\nUrl: {requestUrl}\nRequest Data: {requestData}\nResponse: {responseData}"; + return + $"Exception occured while processing the request.\nUrl: {requestUrl}\nRequest Data: {requestData}\nResponse: {responseData}"; } } -} +}
\ No newline at end of file diff --git a/FireBase/FirebaseKeyGenerator.cs b/FireBase/FirebaseKeyGenerator.cs index acad399..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 /// </summary> - 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 <typeparam name="T" /> along with its key. /// </summary> /// <typeparam name="T"> Type of the underlying object. </typeparam> - public class FirebaseObject<T> + public class FirebaseObject<T> { internal FirebaseObject(string key, T obj) { - this.Key = key; - this.Object = obj; + Key = key; + Object = obj; } /// <summary> /// Gets the key of <see cref="Object"/>. /// </summary> - public string Key - { - get; - } + public string Key { get; } /// <summary> /// Gets the underlying object. /// </summary> - public T Object - { - get; - } + public T Object { get; } } -} +}
\ No newline at end of file diff --git a/FireBase/FirebaseOptions.cs b/FireBase/FirebaseOptions.cs index 9905956..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<string, OfflineEntry>(); - this.SubscriptionStreamReaderFactory = s => new StreamReader(s); - this.JsonSerializerSettings = new JsonSerializerSettings(); - this.SyncPeriod = TimeSpan.FromSeconds(10); + OfflineDatabaseFactory = (t, s) => new Dictionary<string, OfflineEntry>(); + SubscriptionStreamReaderFactory = s => new StreamReader(s); + JsonSerializerSettings = new JsonSerializerSettings(); + SyncPeriod = TimeSpan.FromSeconds(10); } /// <summary> /// Gets or sets the factory for Firebase offline database. Default is in-memory dictionary. /// </summary> - public Func<Type, string, IDictionary<string, OfflineEntry>> OfflineDatabaseFactory - { - get; - set; - } + public Func<Type, string, IDictionary<string, OfflineEntry>> OfflineDatabaseFactory { get; set; } /// <summary> /// Gets or sets the method for retrieving auth tokens. Default is null. /// </summary> - public Func<Task<string>> AuthTokenAsyncFactory - { - get; - set; - } + public Func<Task<string>> AuthTokenAsyncFactory { get; set; } /// <summary> /// Gets or sets the factory for <see cref="TextReader"/> used for reading online streams. Default is <see cref="StreamReader"/>. /// </summary> - public Func<Stream, TextReader> SubscriptionStreamReaderFactory - { - get; - set; - } + public Func<Stream, TextReader> SubscriptionStreamReaderFactory { get; set; } /// <summary> /// Gets or sets the json serializer settings. /// </summary> - public JsonSerializerSettings JsonSerializerSettings - { - get; - set; - } + public JsonSerializerSettings JsonSerializerSettings { get; set; } /// <summary> /// Gets or sets the time between synchronization attempts for pulling and pushing offline entities. Default is 10 seconds. /// </summary> - public TimeSpan SyncPeriod - { - get; - set; - } + public TimeSpan SyncPeriod { get; set; } /// <summary> /// Specify if token returned by factory will be used as "auth" url parameter or "access_token". /// </summary> - public bool AsAccessToken - { - get; - set; - } + public bool AsAccessToken { get; set; } } -} +}
\ No newline at end of file diff --git a/FireBase/Http/HttpClientExtensions.cs b/FireBase/Http/HttpClientExtensions.cs index 5d15c59..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 /// <param name="jsonSerializerSettings"> The specific JSON Serializer Settings. </param> /// <typeparam name="T"> The type of entities the collection should contain. </typeparam> /// <returns> The <see cref="Task"/>. </returns> - public static async Task<IReadOnlyCollection<FirebaseObject<T>>> GetObjectCollectionAsync<T>(this HttpClient client, string requestUri, + public static async Task<IReadOnlyCollection<FirebaseObject<T>>> GetObjectCollectionAsync<T>( + this HttpClient client, string requestUri, JsonSerializerSettings jsonSerializerSettings) { var responseData = string.Empty; @@ -37,12 +37,10 @@ namespace Firebase.Database.Http response.EnsureSuccessStatusCode(); - var dictionary = JsonConvert.DeserializeObject<Dictionary<string, T>>(responseData, jsonSerializerSettings); + var dictionary = + JsonConvert.DeserializeObject<Dictionary<string, T>>(responseData, jsonSerializerSettings); - if (dictionary == null) - { - return new FirebaseObject<T>[0]; - } + if (dictionary == null) return new FirebaseObject<T>[0]; return dictionary.Select(item => new FirebaseObject<T>(item.Key, item.Value)).ToList(); } @@ -116,15 +114,10 @@ namespace Firebase.Database.Http dictionary = JsonConvert.DeserializeObject(data, dictionaryType) as IDictionary; } - if (dictionary == null) - { - yield break; - } + if (dictionary == null) yield break; foreach (DictionaryEntry item in dictionary) - { - yield return new FirebaseObject<object>((string)item.Key, item.Value); - } + yield return new FirebaseObject<object>((string) item.Key, item.Value); } } -} +}
\ No newline at end of file diff --git a/FireBase/Http/PostResult.cs b/FireBase/Http/PostResult.cs index 3f010d4..5a779ed 100644 --- a/FireBase/Http/PostResult.cs +++ b/FireBase/Http/PostResult.cs @@ -8,10 +8,6 @@ namespace Firebase.Database.Http /// <summary> /// Gets or sets the generated key after a successful post. /// </summary> - public string Name - { - get; - set; - } + public string Name { get; set; } } -} +}
\ No newline at end of file diff --git a/FireBase/ObservableExtensions.cs b/FireBase/ObservableExtensions.cs index 37c3ef7..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; /// <summary> /// Extensions for <see cref="IObservable{T}"/>. @@ -25,10 +24,7 @@ if (f.EventType == FirebaseEventType.InsertOrUpdate) { var i = collection.IndexOf(f.Object); - if (i >= 0) - { - collection.RemoveAt(i); - } + if (i >= 0) collection.RemoveAt(i); collection.Add(f.Object); } @@ -41,4 +37,4 @@ return collection; } } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/ConcurrentOfflineDatabase.cs b/FireBase/Offline/ConcurrentOfflineDatabase.cs index 226892d..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; /// <summary> @@ -24,34 +23,30 @@ /// <param name="filenameModifier"> Custom string which will get appended to the file name. </param> public ConcurrentOfflineDatabase(Type itemType, string filenameModifier) { - var fullName = this.GetFileName(itemType.ToString()); - if(fullName.Length > 100) - { - fullName = fullName.Substring(0, 100); - } + var fullName = GetFileName(itemType.ToString()); + if (fullName.Length > 100) fullName = fullName.Substring(0, 100); - BsonMapper mapper = BsonMapper.Global; + var mapper = BsonMapper.Global; mapper.Entity<OfflineEntry>().Id(o => o.Key); - string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - string filename = fullName + filenameModifier + ".db"; + var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var filename = fullName + filenameModifier + ".db"; var path = Path.Combine(root, filename); - this.db = new LiteRepository(new LiteDatabase(path, mapper)); + db = new LiteRepository(new LiteDatabase(path, mapper)); var cache = db.Database .GetCollection<OfflineEntry>() .FindAll() .ToDictionary(o => o.Key, o => o); - this.ccache = new ConcurrentDictionary<string, OfflineEntry>(cache); - + ccache = new ConcurrentDictionary<string, OfflineEntry>(cache); } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns> - public int Count => this.ccache.Count; + public int Count => ccache.Count; /// <summary> /// Gets a value indicating whether this is a read-only collection. @@ -62,13 +57,13 @@ /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns> - public ICollection<string> Keys => this.ccache.Keys; + public ICollection<string> Keys => ccache.Keys; /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns> - public ICollection<OfflineEntry> Values => this.ccache.Values; + public ICollection<OfflineEntry> Values => ccache.Values; /// <summary> /// Gets or sets the element with the specified key. @@ -77,15 +72,12 @@ /// <returns> The element with the specified key. </returns> public OfflineEntry this[string key] { - get - { - return this.ccache[key]; - } + get => ccache[key]; set { - this.ccache.AddOrUpdate(key, value, (k, existing) => value); - this.db.Upsert(value); + ccache.AddOrUpdate(key, value, (k, existing) => value); + db.Upsert(value); } } @@ -95,12 +87,12 @@ /// <returns> An enumerator that can be used to iterate through the collection. </returns> public IEnumerator<KeyValuePair<string, OfflineEntry>> GetEnumerator() { - return this.ccache.GetEnumerator(); + return ccache.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } /// <summary> @@ -109,7 +101,7 @@ /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> public void Add(KeyValuePair<string, OfflineEntry> item) { - this.Add(item.Key, item.Value); + Add(item.Key, item.Value); } /// <summary> @@ -117,8 +109,8 @@ /// </summary> public void Clear() { - this.ccache.Clear(); - this.db.Delete<OfflineEntry>(Query.All()); + ccache.Clear(); + db.Delete<OfflineEntry>(Query.All()); } /// <summary> @@ -128,7 +120,7 @@ /// <returns> True if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. </returns> public bool Contains(KeyValuePair<string, OfflineEntry> item) { - return this.ContainsKey(item.Key); + return ContainsKey(item.Key); } /// <summary> @@ -138,7 +130,7 @@ /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> public void CopyTo(KeyValuePair<string, OfflineEntry>[] array, int arrayIndex) { - this.ccache.ToList().CopyTo(array, arrayIndex); + ccache.ToList().CopyTo(array, arrayIndex); } /// <summary> @@ -148,7 +140,7 @@ /// <returns> True if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns> public bool Remove(KeyValuePair<string, OfflineEntry> item) { - return this.Remove(item.Key); + return Remove(item.Key); } /// <summary> @@ -158,7 +150,7 @@ /// <returns> True if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. </returns> public bool ContainsKey(string key) { - return this.ccache.ContainsKey(key); + return ccache.ContainsKey(key); } /// <summary> @@ -168,8 +160,8 @@ /// <param name="value">The object to use as the value of the element to add.</param> public void Add(string key, OfflineEntry value) { - this.ccache.AddOrUpdate(key, value, (k, existing) => value); - this.db.Upsert(value); + ccache.AddOrUpdate(key, value, (k, existing) => value); + db.Upsert(value); } /// <summary> @@ -179,8 +171,8 @@ /// <returns> True if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns> public bool Remove(string key) { - this.ccache.TryRemove(key, out OfflineEntry _); - return this.db.Delete<OfflineEntry>(key); + ccache.TryRemove(key, out _); + return db.Delete<OfflineEntry>(key); } /// <summary> @@ -190,18 +182,16 @@ /// <returns> True if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. </returns> public bool TryGetValue(string key, out OfflineEntry value) { - return this.ccache.TryGetValue(key, out value); + return ccache.TryGetValue(key, out value); } private string GetFileName(string fileName) { - var invalidChars = new[] { '`', '[', ',', '=' }; - foreach(char c in invalidChars.Concat(System.IO.Path.GetInvalidFileNameChars()).Distinct()) - { + var invalidChars = new[] {'`', '[', ',', '='}; + foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct()) fileName = fileName.Replace(c, '_'); - } return fileName; } } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/DatabaseExtensions.cs b/FireBase/Offline/DatabaseExtensions.cs index 4b04314..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 @@ /// <param name="initialPullStrategy"> Specifies what strategy should be used for initial pulling of server data. </param> /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. </param> /// <returns> The <see cref="RealtimeDatabase{T}"/>. </returns> - public static RealtimeDatabase<T> AsRealtimeDatabase<T>(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) + public static RealtimeDatabase<T> AsRealtimeDatabase<T>(this ChildQuery query, string filenameModifier = "", + string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, + InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class { - return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges); + return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, + filenameModifier, streamingOptions, initialPullStrategy, pushChanges); } /// <summary> @@ -36,11 +39,16 @@ /// <param name="initialPullStrategy"> Specifies what strategy should be used for initial pulling of server data. </param> /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. It this is false, then Put / Post / Delete will not affect server data. </param> /// <returns> The <see cref="RealtimeDatabase{T}"/>. </returns> - public static RealtimeDatabase<T> AsRealtimeDatabase<T, TSetHandler>(this ChildQuery query, string filenameModifier = "", string elementRoot = "", StreamingOptions streamingOptions = StreamingOptions.LatestOnly, InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) + public static RealtimeDatabase<T> AsRealtimeDatabase<T, TSetHandler>(this ChildQuery query, + string filenameModifier = "", string elementRoot = "", + StreamingOptions streamingOptions = StreamingOptions.LatestOnly, + InitialPullStrategy initialPullStrategy = InitialPullStrategy.MissingOnly, bool pushChanges = true) where T : class where TSetHandler : ISetHandler<T>, new() { - return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, filenameModifier, streamingOptions, initialPullStrategy, pushChanges, Activator.CreateInstance<TSetHandler>()); + return new RealtimeDatabase<T>(query, elementRoot, query.Client.Options.OfflineDatabaseFactory, + filenameModifier, streamingOptions, initialPullStrategy, pushChanges, + Activator.CreateInstance<TSetHandler>()); } /// <summary> @@ -50,8 +58,9 @@ /// <param name="obj"> The object to set. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> - public static void Patch<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, int priority = 1) - where T: class + public static void Patch<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -63,8 +72,9 @@ /// <param name="obj"> The object to set. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> - public static void Put<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, int priority = 1) - where T: class + public static void Put<T>(this RealtimeDatabase<T> db, string key, T obj, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, obj, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -77,7 +87,7 @@ /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> /// <returns> The generated key for this object. </returns> public static string Post<T>(this RealtimeDatabase<T> db, T obj, bool syncOnline = true, int priority = 1) - where T: class + where T : class { var key = FirebaseKeyGenerator.Next(); @@ -93,7 +103,7 @@ /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public static void Delete<T>(this RealtimeDatabase<T> db, string key, bool syncOnline = true, int priority = 1) - where T: class + where T : class { db.Set(key, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -109,8 +119,10 @@ /// <param name="value"> Value to put. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> - public static void Put<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T: class + public static void Put<T, TProperty>(this RealtimeDatabase<T> db, string key, + Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -126,8 +138,10 @@ /// <param name="value"> Value to patch. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> - public static void Patch<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T: class + public static void Patch<T, TProperty>(this RealtimeDatabase<T> db, string key, + Expression<Func<T, TProperty>> propertyExpression, TProperty value, bool syncOnline = true, + int priority = 1) + where T : class { db.Set(key, propertyExpression, value, syncOnline ? SyncOptions.Patch : SyncOptions.None, priority); } @@ -143,9 +157,10 @@ /// <param name="value"> Value to put. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> - public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TProperty>> propertyExpression, bool syncOnline = true, int priority = 1) - where T: class - where TProperty: class + public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, + Expression<Func<T, TProperty>> propertyExpression, bool syncOnline = true, int priority = 1) + where T : class + where TProperty : class { db.Set(key, propertyExpression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -163,12 +178,17 @@ /// <param name="value"> Value to put. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> - public static void Post<T, TSelector, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, TSelector>> propertyExpression, TProperty value, bool syncOnline = true, int priority = 1) - where T: class - where TSelector: IDictionary<string, TProperty> + public static void Post<T, TSelector, TProperty>(this RealtimeDatabase<T> db, string key, + Expression<Func<T, TSelector>> propertyExpression, TProperty value, bool syncOnline = true, + int priority = 1) + where T : class + where TSelector : IDictionary<string, TProperty> { var nextKey = FirebaseKeyGenerator.Next(); - var expression = Expression.Lambda<Func<T, TProperty>>(Expression.Call(propertyExpression.Body, typeof(TSelector).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(nextKey)), propertyExpression.Parameters); + var expression = Expression.Lambda<Func<T, TProperty>>( + Expression.Call(propertyExpression.Body, + typeof(TSelector).GetRuntimeMethod("get_Item", new[] {typeof(string)}), + Expression.Constant(nextKey)), propertyExpression.Parameters); db.Set(key, expression, value, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } @@ -185,11 +205,16 @@ /// <param name="dictionaryKey"> Key within the nested dictionary to delete. </param> /// <param name="syncOnline"> Indicates whether the item should be synced online. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> - public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, Expression<Func<T, IDictionary<string, TProperty>>> propertyExpression, string dictionaryKey, bool syncOnline = true, int priority = 1) - where T: class + public static void Delete<T, TProperty>(this RealtimeDatabase<T> db, string key, + Expression<Func<T, IDictionary<string, TProperty>>> propertyExpression, string dictionaryKey, + bool syncOnline = true, int priority = 1) + where T : class { - var expression = Expression.Lambda<Func<T, TProperty>>(Expression.Call(propertyExpression.Body, typeof(IDictionary<string, TProperty>).GetRuntimeMethod("get_Item", new[] { typeof(string) }), Expression.Constant(dictionaryKey)), propertyExpression.Parameters); + var expression = Expression.Lambda<Func<T, TProperty>>( + Expression.Call(propertyExpression.Body, + typeof(IDictionary<string, TProperty>).GetRuntimeMethod("get_Item", new[] {typeof(string)}), + Expression.Constant(dictionaryKey)), propertyExpression.Parameters); db.Set(key, expression, null, syncOnline ? SyncOptions.Put : SyncOptions.None, priority); } } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/ISetHandler.cs b/FireBase/Offline/ISetHandler.cs index 477c36b..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<in T> { Task SetAsync(ChildQuery query, string key, OfflineEntry entry); } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/InitialPullStrategy.cs b/FireBase/Offline/InitialPullStrategy.cs index 70f6b8c..a1ae3f7 100644 --- a/FireBase/Offline/InitialPullStrategy.cs +++ b/FireBase/Offline/InitialPullStrategy.cs @@ -8,7 +8,7 @@ /// <summary> /// Don't pull anything. /// </summary> - None, + None, /// <summary> /// Pull only what isn't already stored offline. @@ -20,4 +20,4 @@ /// </summary> 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<string> PropertyNames => this.propertyNames; + public IEnumerable<string> 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<JsonPropertyAttribute>(); - this.propertyNames.Add(jsonAttr?.PropertyName ?? memberExpr.Member.Name); + propertyNames.Add(jsonAttr?.PropertyName ?? memberExpr.Member.Name); } } else if (expr?.NodeType == ExpressionType.Call) { - var callExpr = (MethodCallExpression)expr; + var callExpr = (MethodCallExpression) expr; if (callExpr.Method.Name == "get_Item" && callExpr.Arguments.Count == 1) { var e = Expression.Lambda(callExpr.Arguments[0]).Compile(); - this.propertyNames.Add(e.DynamicInvoke().ToString()); - this.wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess; + propertyNames.Add(e.DynamicInvoke().ToString()); + wasDictionaryAccess = callExpr.Arguments[0].NodeType == ExpressionType.MemberAccess; } } return base.Visit(expr); } } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/OfflineCacheAdapter.cs b/FireBase/Offline/OfflineCacheAdapter.cs index a3761a0..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<TKey, T> : IDictionary<string, T>, IDictionary + internal class OfflineCacheAdapter<TKey, T> : IDictionary<string, T>, IDictionary { private readonly IDictionary<string, OfflineEntry> 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<T>(); - } + get => database[key.ToString()].Deserialize<T>(); set { var keyString = key.ToString(); - if (this.database.ContainsKey(keyString)) - { - this.database[keyString] = new OfflineEntry(keyString, value, this.database[keyString].Priority, this.database[keyString].SyncOptions); - } + if (database.ContainsKey(keyString)) + database[keyString] = new OfflineEntry(keyString, value, database[keyString].Priority, + database[keyString].SyncOptions); else - { - this.database[keyString] = new OfflineEntry(keyString, value, 1, SyncOptions.None); - } + database[keyString] = new OfflineEntry(keyString, value, 1, SyncOptions.None); } } - public ICollection<string> Keys => this.database.Keys; + public ICollection<string> Keys => database.Keys; ICollection IDictionary.Values { get; } ICollection IDictionary.Keys { get; } - public ICollection<T> Values => this.database.Values.Select(o => o.Deserialize<T>()).ToList(); + public ICollection<T> Values => database.Values.Select(o => o.Deserialize<T>()).ToList(); public T this[string key] { - get - { - return this.database[key].Deserialize<T>(); - } + get => database[key].Deserialize<T>(); set { - if (this.database.ContainsKey(key)) - { - this.database[key] = new OfflineEntry(key, value, this.database[key].Priority, this.database[key].SyncOptions); - } + 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<KeyValuePair<string, T>> GetEnumerator() { - return this.database.Select(d => new KeyValuePair<string, T>(d.Key, d.Value.Deserialize<T>())).GetEnumerator(); + return database.Select(d => new KeyValuePair<string, T>(d.Key, d.Value.Deserialize<T>())).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } public void Add(KeyValuePair<string, T> 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<string, T> item) { - return this.ContainsKey(item.Key); + return ContainsKey(item.Key); } public void CopyTo(KeyValuePair<string, T>[] array, int arrayIndex) @@ -130,29 +117,29 @@ public bool Remove(KeyValuePair<string, T> item) { - return this.database.Remove(item.Key); + return database.Remove(item.Key); } public void Add(string key, T value) { - this.database.Add(key, new OfflineEntry(key, value, 1, SyncOptions.None)); + database.Add(key, new OfflineEntry(key, value, 1, SyncOptions.None)); } public bool ContainsKey(string key) { - return this.database.ContainsKey(key); + return database.ContainsKey(key); } public bool Remove(string key) { - return this.database.Remove(key); + return database.Remove(key); } public bool TryGetValue(string key, out T value) { OfflineEntry val; - if (this.database.TryGetValue(key, out val)) + if (database.TryGetValue(key, out val)) { value = val.Deserialize<T>(); return true; @@ -162,4 +149,4 @@ return false; } } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/OfflineDatabase.cs b/FireBase/Offline/OfflineDatabase.cs index 9cebf9c..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; /// <summary> @@ -23,21 +22,18 @@ /// <param name="filenameModifier"> Custom string which will get appended to the file name. </param> public OfflineDatabase(Type itemType, string filenameModifier) { - var fullName = this.GetFileName(itemType.ToString()); - if(fullName.Length > 100) - { - fullName = fullName.Substring(0, 100); - } + var fullName = GetFileName(itemType.ToString()); + if (fullName.Length > 100) fullName = fullName.Substring(0, 100); - BsonMapper mapper = BsonMapper.Global; + var mapper = BsonMapper.Global; mapper.Entity<OfflineEntry>().Id(o => o.Key); - string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - string filename = fullName + filenameModifier + ".db"; + var root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var filename = fullName + filenameModifier + ".db"; var path = Path.Combine(root, filename); - this.db = new LiteRepository(new LiteDatabase(path, mapper)); + db = new LiteRepository(new LiteDatabase(path, mapper)); - this.cache = db.Database.GetCollection<OfflineEntry>().FindAll() + cache = db.Database.GetCollection<OfflineEntry>().FindAll() .ToDictionary(o => o.Key, o => o); } @@ -45,24 +41,24 @@ /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns> - public int Count => this.cache.Count; + public int Count => cache.Count; /// <summary> /// Gets a value indicating whether this is a read-only collection. /// </summary> - public bool IsReadOnly => this.cache.IsReadOnly; + public bool IsReadOnly => cache.IsReadOnly; /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns> - public ICollection<string> Keys => this.cache.Keys; + public ICollection<string> Keys => cache.Keys; /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns> - public ICollection<OfflineEntry> Values => this.cache.Values; + public ICollection<OfflineEntry> Values => cache.Values; /// <summary> /// Gets or sets the element with the specified key. @@ -71,15 +67,12 @@ /// <returns> The element with the specified key. </returns> public OfflineEntry this[string key] { - get - { - return this.cache[key]; - } + get => cache[key]; set { - this.cache[key] = value; - this.db.Upsert(value); + cache[key] = value; + db.Upsert(value); } } @@ -89,12 +82,12 @@ /// <returns> An enumerator that can be used to iterate through the collection. </returns> public IEnumerator<KeyValuePair<string, OfflineEntry>> GetEnumerator() { - return this.cache.GetEnumerator(); + return cache.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } /// <summary> @@ -103,7 +96,7 @@ /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> public void Add(KeyValuePair<string, OfflineEntry> item) { - this.Add(item.Key, item.Value); + Add(item.Key, item.Value); } /// <summary> @@ -111,8 +104,8 @@ /// </summary> public void Clear() { - this.cache.Clear(); - this.db.Delete<OfflineEntry>(Query.All()); + cache.Clear(); + db.Delete<OfflineEntry>(Query.All()); } /// <summary> @@ -122,7 +115,7 @@ /// <returns> True if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. </returns> public bool Contains(KeyValuePair<string, OfflineEntry> item) { - return this.ContainsKey(item.Key); + return ContainsKey(item.Key); } /// <summary> @@ -132,7 +125,7 @@ /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> public void CopyTo(KeyValuePair<string, OfflineEntry>[] array, int arrayIndex) { - this.cache.CopyTo(array, arrayIndex); + cache.CopyTo(array, arrayIndex); } /// <summary> @@ -142,7 +135,7 @@ /// <returns> True if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. </returns> public bool Remove(KeyValuePair<string, OfflineEntry> item) { - return this.Remove(item.Key); + return Remove(item.Key); } /// <summary> @@ -152,7 +145,7 @@ /// <returns> True if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. </returns> public bool ContainsKey(string key) { - return this.cache.ContainsKey(key); + return cache.ContainsKey(key); } /// <summary> @@ -162,8 +155,8 @@ /// <param name="value">The object to use as the value of the element to add.</param> public void Add(string key, OfflineEntry value) { - this.cache.Add(key, value); - this.db.Insert(value); + cache.Add(key, value); + db.Insert(value); } /// <summary> @@ -173,8 +166,8 @@ /// <returns> True if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. </returns> public bool Remove(string key) { - this.cache.Remove(key); - return this.db.Delete<OfflineEntry>(key); + cache.Remove(key); + return db.Delete<OfflineEntry>(key); } /// <summary> @@ -184,18 +177,16 @@ /// <returns> True if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. </returns> public bool TryGetValue(string key, out OfflineEntry value) { - return this.cache.TryGetValue(key, out value); + return cache.TryGetValue(key, out value); } private string GetFileName(string fileName) { - var invalidChars = new[] { '`', '[', ',', '=' }; - foreach(char c in invalidChars.Concat(System.IO.Path.GetInvalidFileNameChars()).Distinct()) - { + var invalidChars = new[] {'`', '[', ',', '='}; + foreach (var c in invalidChars.Concat(Path.GetInvalidFileNameChars()).Distinct()) fileName = fileName.Replace(c, '_'); - } return fileName; } } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/OfflineEntry.cs b/FireBase/Offline/OfflineEntry.cs index 3b862cb..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; /// <summary> @@ -18,16 +17,17 @@ /// <param name="obj"> The object. </param> /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> /// <param name="syncOptions"> The sync options. </param> - public OfflineEntry(string key, object obj, string data, int priority, SyncOptions syncOptions, bool isPartial = false) + public OfflineEntry(string key, object obj, string data, int priority, SyncOptions syncOptions, + bool isPartial = false) { - this.Key = key; - this.Priority = priority; - this.Data = data; - this.Timestamp = DateTime.UtcNow; - this.SyncOptions = syncOptions; - this.IsPartial = isPartial; + Key = key; + Priority = priority; + Data = data; + Timestamp = DateTime.UtcNow; + SyncOptions = syncOptions; + IsPartial = isPartial; - this.dataInstance = obj; + dataInstance = obj; } /// <summary> @@ -45,63 +45,39 @@ /// <summary> /// Initializes a new instance of the <see cref="OfflineEntry"/> class. /// </summary> - public OfflineEntry() + public OfflineEntry() { } /// <summary> /// Gets or sets the key of this entry. /// </summary> - public string Key - { - get; - set; - } + public string Key { get; set; } /// <summary> /// Gets or sets the priority. Objects with higher priority will be synced first. Higher number indicates higher priority. /// </summary> - public int Priority - { - get; - set; - } + public int Priority { get; set; } /// <summary> /// Gets or sets the timestamp when this entry was last touched. /// </summary> - public DateTime Timestamp - { - get; - set; - } + public DateTime Timestamp { get; set; } /// <summary> /// Gets or sets the <see cref="SyncOptions"/> which define what sync state this entry is in. /// </summary> - public SyncOptions SyncOptions - { - get; - set; - } + public SyncOptions SyncOptions { get; set; } /// <summary> /// Gets or sets serialized JSON data. /// </summary> - public string Data - { - get; - set; - } + public string Data { get; set; } /// <summary> /// Specifies whether this is only a partial object. /// </summary> - public bool IsPartial - { - get; - set; - } + public bool IsPartial { get; set; } /// <summary> /// Deserializes <see cref="Data"/> into <typeparamref name="T"/>. The result is cached. @@ -110,7 +86,7 @@ /// <returns> Instance of <typeparamref name="T"/>. </returns> public T Deserialize<T>() { - return (T)(this.dataInstance ?? (this.dataInstance = JsonConvert.DeserializeObject<T>(this.Data))); + return (T) (dataInstance ?? (dataInstance = JsonConvert.DeserializeObject<T>(Data))); } } -} +}
\ No newline at end of file diff --git a/FireBase/Offline/RealtimeDatabase.cs b/FireBase/Offline/RealtimeDatabase.cs index 61a7010..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 @@ /// <param name="streamChanges"> Specifies whether changes should be streamed from the server. </param> /// <param name="pullEverythingOnStart"> Specifies if everything should be pull from the online storage on start. It only makes sense when <see cref="streamChanges"/> is set to true. </param> /// <param name="pushChanges"> Specifies whether changed items should actually be pushed to the server. If this is false, then Put / Post / Delete will not affect server data. </param> - public RealtimeDatabase(ChildQuery childQuery, string elementRoot, Func<Type, string, IDictionary<string, OfflineEntry>> offlineDatabaseFactory, string filenameModifier, StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, ISetHandler<T> setHandler = null) + public RealtimeDatabase(ChildQuery childQuery, string elementRoot, + Func<Type, string, IDictionary<string, OfflineEntry>> offlineDatabaseFactory, string filenameModifier, + StreamingOptions streamingOptions, InitialPullStrategy initialPullStrategy, bool pushChanges, + ISetHandler<T> setHandler = null) { this.childQuery = childQuery; this.elementRoot = elementRoot; this.streamingOptions = streamingOptions; this.initialPullStrategy = initialPullStrategy; this.pushChanges = pushChanges; - this.Database = offlineDatabaseFactory(typeof(T), filenameModifier); - this.firebaseCache = new FirebaseCache<T>(new OfflineCacheAdapter<string, T>(this.Database)); - this.subject = new Subject<FirebaseEvent<T>>(); + Database = offlineDatabaseFactory(typeof(T), filenameModifier); + firebaseCache = new FirebaseCache<T>(new OfflineCacheAdapter<string, T>(Database)); + subject = new Subject<FirebaseEvent<T>>(); - this.PutHandler = setHandler ?? new SetHandler<T>(); + PutHandler = setHandler ?? new SetHandler<T>(); - this.isSyncRunning = true; - Task.Factory.StartNew(this.SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + isSyncRunning = true; + Task.Factory.StartNew(SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, + TaskScheduler.Default); } /// <summary> @@ -71,17 +74,9 @@ /// <summary> /// Gets the backing Database. /// </summary> - public IDictionary<string, OfflineEntry> Database - { - get; - private set; - } + public IDictionary<string, OfflineEntry> Database { get; private set; } - public ISetHandler<T> PutHandler - { - private get; - set; - } + public ISetHandler<T> PutHandler { private get; set; } /// <summary> /// Overwrites existing object with given key. @@ -92,35 +87,34 @@ /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public void Set(string key, T obj, SyncOptions syncOptions, int priority = 1) { - this.SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions)); + SetAndRaise(key, new OfflineEntry(key, obj, priority, syncOptions)); } - public void Set<TProperty>(string key, Expression<Func<T, TProperty>> propertyExpression, object value, SyncOptions syncOptions, int priority = 1) + public void Set<TProperty>(string key, Expression<Func<T, TProperty>> propertyExpression, object value, + SyncOptions syncOptions, int priority = 1) { - var fullKey = this.GenerateFullKey(key, propertyExpression, syncOptions); + var fullKey = GenerateFullKey(key, propertyExpression, syncOptions); var serializedObject = JsonConvert.SerializeObject(value).Trim('"', '\\'); if (fullKey.Item3) { if (typeof(TProperty) != typeof(string) || value == null) - { // don't escape non-string primitives and null; serializedObject = $"{{ \"{fullKey.Item2}\" : {serializedObject} }}"; - } else - { serializedObject = $"{{ \"{fullKey.Item2}\" : \"{serializedObject}\" }}"; - } } - var setObject = this.firebaseCache.PushData("/" + fullKey.Item1, serializedObject).First(); + var setObject = firebaseCache.PushData("/" + fullKey.Item1, serializedObject).First(); - if (!this.Database.ContainsKey(key) || this.Database[key].SyncOptions != SyncOptions.Patch && this.Database[key].SyncOptions != SyncOptions.Put) - { - this.Database[fullKey.Item1] = new OfflineEntry(fullKey.Item1, value, serializedObject, priority, syncOptions, true); - } + if (!Database.ContainsKey(key) || Database[key].SyncOptions != SyncOptions.Patch && + Database[key].SyncOptions != SyncOptions.Put) + Database[fullKey.Item1] = + new OfflineEntry(fullKey.Item1, value, serializedObject, priority, syncOptions, true); - this.subject.OnNext(new FirebaseEvent<T>(key, setObject.Object, setObject == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)); + subject.OnNext(new FirebaseEvent<T>(key, setObject.Object, + setObject == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, + FirebaseEventSource.Offline)); } /// <summary> @@ -130,15 +124,11 @@ /// <param name="priority"> The priority. Objects with higher priority will be synced first. Higher number indicates higher priority. </param> public void Pull(string key, int priority = 1) { - if (!this.Database.ContainsKey(key)) - { - this.Database[key] = new OfflineEntry(key, null, priority, SyncOptions.Pull); - } - else if (this.Database[key].SyncOptions == SyncOptions.None) - { + if (!Database.ContainsKey(key)) + Database[key] = new OfflineEntry(key, null, priority, SyncOptions.Pull); + else if (Database[key].SyncOptions == SyncOptions.None) // pull only if push isn't pending - this.Database[key].SyncOptions = SyncOptions.Pull; - } + Database[key].SyncOptions = SyncOptions.Pull; } /// <summary> @@ -146,26 +136,30 @@ /// </summary> public async Task PullAsync() { - var existingEntries = await this.childQuery + var existingEntries = await childQuery .OnceAsync<T>() .ToObservable() .RetryAfterDelay<IReadOnlyCollection<FirebaseObject<T>>, FirebaseException>( - this.childQuery.Client.Options.SyncPeriod, - ex => ex.StatusCode == System.Net.HttpStatusCode.OK) // OK implies the request couldn't complete due to network error. - .Select(e => this.ResetDatabaseFromInitial(e, false)) + childQuery.Client.Options.SyncPeriod, + ex => ex.StatusCode == + 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<T>(e.Key, e.Object, FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePull)); + Database[e.Key] = new OfflineEntry(e.Key, e.Object, 1, SyncOptions.None); + subject.OnNext(new FirebaseEvent<T>(e.Key, e.Object, FirebaseEventType.InsertOrUpdate, + FirebaseEventSource.OnlinePull)); }) .ToList(); // Remove items not stored online - foreach (var item in this.Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList()) + foreach (var item in Database.Keys.Except(existingEntries.Select(f => f.Key)).ToList()) { - this.Database.Remove(item); - this.subject.OnNext(new FirebaseEvent<T>(item, null, FirebaseEventType.Delete, FirebaseEventSource.OnlinePull)); + Database.Remove(item); + subject.OnNext(new FirebaseEvent<T>(item, null, FirebaseEventType.Delete, + FirebaseEventSource.OnlinePull)); } } @@ -174,7 +168,7 @@ /// </summary> public IEnumerable<FirebaseObject<T>> Once() { - return this.Database + return Database .Where(kvp => !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial) .Select(kvp => new FirebaseObject<T>(kvp.Key, kvp.Value.Deserialize<T>())) .ToList(); @@ -186,67 +180,72 @@ /// <returns> Stream of <see cref="FirebaseEvent{T}"/>. </returns> public IObservable<FirebaseEvent<T>> AsObservable() { - if (!this.isSyncRunning) + if (!isSyncRunning) { - this.isSyncRunning = true; - Task.Factory.StartNew(this.SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); + isSyncRunning = true; + Task.Factory.StartNew(SynchronizeThread, CancellationToken.None, TaskCreationOptions.LongRunning, + TaskScheduler.Default); } - if (this.observable == null) + if (observable == null) { var initialData = Observable.Return(FirebaseEvent<T>.Empty(FirebaseEventSource.Offline)); - if(this.Database.TryGetValue(this.elementRoot, out OfflineEntry oe)) - { + if (Database.TryGetValue(elementRoot, out var oe)) initialData = Observable.Return(oe) - .Where(offlineEntry => !string.IsNullOrEmpty(offlineEntry.Data) && offlineEntry.Data != "null" && !offlineEntry.IsPartial) - .Select(offlineEntry => new FirebaseEvent<T>(offlineEntry.Key, offlineEntry.Deserialize<T>(), FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)); - } - else if(this.Database.Count > 0) - { - initialData = this.Database - .Where(kvp => !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial) - .Select(kvp => new FirebaseEvent<T>(kvp.Key, kvp.Value.Deserialize<T>(), FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)) + .Where(offlineEntry => + !string.IsNullOrEmpty(offlineEntry.Data) && offlineEntry.Data != "null" && + !offlineEntry.IsPartial) + .Select(offlineEntry => new FirebaseEvent<T>(offlineEntry.Key, offlineEntry.Deserialize<T>(), + FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)); + else if (Database.Count > 0) + initialData = Database + .Where(kvp => + !string.IsNullOrEmpty(kvp.Value.Data) && kvp.Value.Data != "null" && !kvp.Value.IsPartial) + .Select(kvp => new FirebaseEvent<T>(kvp.Key, kvp.Value.Deserialize<T>(), + FirebaseEventType.InsertOrUpdate, FirebaseEventSource.Offline)) .ToList() .ToObservable(); - } - this.observable = initialData - .Merge(this.subject) - .Merge(this.GetInitialPullObservable() - .RetryAfterDelay<IReadOnlyCollection<FirebaseObject<T>>, FirebaseException>( - this.childQuery.Client.Options.SyncPeriod, - ex => ex.StatusCode == System.Net.HttpStatusCode.OK) // OK implies the request couldn't complete due to network error. - .Select(e => this.ResetDatabaseFromInitial(e)) - .SelectMany(e => e) - .Do(this.SetObjectFromInitialPull) - .Select(e => new FirebaseEvent<T>(e.Key, e.Object, e.Object == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlineInitial)) - .Concat(Observable.Create<FirebaseEvent<T>>(observer => this.InitializeStreamingSubscription(observer)))) - .Do(next => { }, e => this.observable = null, () => this.observable = null) + observable = initialData + .Merge(subject) + .Merge(GetInitialPullObservable() + .RetryAfterDelay<IReadOnlyCollection<FirebaseObject<T>>, FirebaseException>( + childQuery.Client.Options.SyncPeriod, + ex => ex.StatusCode == + 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<T>(e.Key, e.Object, + e.Object == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, + FirebaseEventSource.OnlineInitial)) + .Concat(Observable.Create<FirebaseEvent<T>>(observer => + InitializeStreamingSubscription(observer)))) + .Do(next => { }, e => observable = null, () => observable = null) .Replay() .RefCount(); } - return this.observable; + return observable; } public void Dispose() { - this.subject.OnCompleted(); - this.firebaseSubscription?.Dispose(); + subject.OnCompleted(); + firebaseSubscription?.Dispose(); } - private IReadOnlyCollection<FirebaseObject<T>> ResetDatabaseFromInitial(IReadOnlyCollection<FirebaseObject<T>> collection, bool onlyWhenInitialEverything = true) + private IReadOnlyCollection<FirebaseObject<T>> ResetDatabaseFromInitial( + IReadOnlyCollection<FirebaseObject<T>> collection, bool onlyWhenInitialEverything = true) { - if (onlyWhenInitialEverything && this.initialPullStrategy != InitialPullStrategy.Everything) - { - return collection; - } + if (onlyWhenInitialEverything && initialPullStrategy != InitialPullStrategy.Everything) return collection; // items which are in local db, but not in the online collection - var extra = this.Once() - .Select(f => f.Key) - .Except(collection.Select(c => c.Key)) - .Select(k => new FirebaseObject<T>(k, null)); + var extra = Once() + .Select(f => f.Key) + .Except(collection.Select(c => c.Key)) + .Select(k => new FirebaseObject<T>(k, null)); return collection.Concat(extra).ToList(); } @@ -257,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<IReadOnlyCollection<FirebaseObject<T>>> GetInitialPullObservable() { FirebaseQuery query; - switch (this.initialPullStrategy) + switch (initialPullStrategy) { case InitialPullStrategy.MissingOnly: - query = this.childQuery.OrderByKey().StartAt(() => this.GetLatestKey()); + query = childQuery.OrderByKey().StartAt(() => GetLatestKey()); break; case InitialPullStrategy.Everything: - query = this.childQuery; + query = childQuery; break; case InitialPullStrategy.None: default: return Observable.Empty<IReadOnlyCollection<FirebaseEvent<T>>>(); } - if (string.IsNullOrWhiteSpace(this.elementRoot)) - { + if (string.IsNullOrWhiteSpace(elementRoot)) return Observable.Defer(() => query.OnceAsync<T>().ToObservable()); - } - + // there is an element root, which indicates the target location is not a collection but a single element - return Observable.Defer(async () => Observable.Return(await query.OnceSingleAsync<T>()).Select(e => new[] { new FirebaseObject<T>(this.elementRoot, e) })); + return Observable.Defer(async () => + Observable.Return(await query.OnceSingleAsync<T>()) + .Select(e => new[] {new FirebaseObject<T>(elementRoot, e)})); } private IDisposable InitializeStreamingSubscription(IObserver<FirebaseEvent<T>> observer) { - var completeDisposable = Disposable.Create(() => this.isSyncRunning = false); + var completeDisposable = Disposable.Create(() => isSyncRunning = false); - switch (this.streamingOptions) + switch (streamingOptions) { case StreamingOptions.LatestOnly: // stream since the latest key - var queryLatest = this.childQuery.OrderByKey().StartAt(() => this.GetLatestKey()); - this.firebaseSubscription = new FirebaseSubscription<T>(observer, queryLatest, this.elementRoot, this.firebaseCache); - this.firebaseSubscription.ExceptionThrown += this.StreamingExceptionThrown; + var queryLatest = childQuery.OrderByKey().StartAt(() => GetLatestKey()); + firebaseSubscription = + new FirebaseSubscription<T>(observer, queryLatest, elementRoot, firebaseCache); + firebaseSubscription.ExceptionThrown += StreamingExceptionThrown; - return new CompositeDisposable(this.firebaseSubscription.Run(), completeDisposable); + return new CompositeDisposable(firebaseSubscription.Run(), completeDisposable); case StreamingOptions.Everything: // stream everything - var queryAll = this.childQuery; - this.firebaseSubscription = new FirebaseSubscription<T>(observer, queryAll, this.elementRoot, this.firebaseCache); - this.firebaseSubscription.ExceptionThrown += this.StreamingExceptionThrown; + var queryAll = childQuery; + firebaseSubscription = new FirebaseSubscription<T>(observer, queryAll, elementRoot, firebaseCache); + firebaseSubscription.ExceptionThrown += StreamingExceptionThrown; - return new CompositeDisposable(this.firebaseSubscription.Run(), completeDisposable); + 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<T>(key, obj?.Deserialize<T>(), string.IsNullOrEmpty(obj?.Data) || obj?.Data == "null" ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, eventSource)); + Database[key] = obj; + subject.OnNext(new FirebaseEvent<T>(key, obj?.Deserialize<T>(), + string.IsNullOrEmpty(obj?.Data) || obj?.Data == "null" + ? FirebaseEventType.Delete + : FirebaseEventType.InsertOrUpdate, eventSource)); } private async void SynchronizeThread() { - while (this.isSyncRunning) + while (isSyncRunning) { try { - var validEntries = this.Database.Where(e => e.Value != null); - await this.PullEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Pull)); + var validEntries = Database.Where(e => e.Value != null); + await PullEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Pull)); - if (this.pushChanges) - { - await this.PushEntriesAsync(validEntries.Where(kvp => kvp.Value.SyncOptions == SyncOptions.Put || kvp.Value.SyncOptions == SyncOptions.Patch)); - } + if (pushChanges) + await PushEntriesAsync(validEntries.Where(kvp => + kvp.Value.SyncOptions == SyncOptions.Put || kvp.Value.SyncOptions == SyncOptions.Patch)); } catch (Exception ex) { - this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); + SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } - await Task.Delay(this.childQuery.Client.Options.SyncPeriod); + await Task.Delay(childQuery.Client.Options.SyncPeriod); } } private string GetLatestKey() { - var key = this.Database.OrderBy(o => o.Key, StringComparer.Ordinal).LastOrDefault().Key ?? string.Empty; + var key = Database.OrderBy(o => o.Key, StringComparer.Ordinal).LastOrDefault().Key ?? string.Empty; if (!string.IsNullOrWhiteSpace(key)) - { - key = key.Substring(0, key.Length - 1) + (char)(key[key.Length - 1] + 1); - } + key = key.Substring(0, key.Length - 1) + (char) (key[key.Length - 1] + 1); return key; } @@ -362,10 +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<T>())); + var tasks = group.OrderBy(kvp => kvp.Value.IsPartial).Select(kvp => + kvp.Value.IsPartial + ? ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key) + : ResetSyncAfterPush(PutHandler.SetAsync(childQuery, kvp.Key, kvp.Value), kvp.Key, + kvp.Value.Deserialize<T>())); try { @@ -373,7 +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<T>(), pair.Key, pair.Value)); + var tasks = group.Select(pair => + ResetAfterPull( + childQuery.Child(pair.Key == elementRoot ? string.Empty : pair.Key).OnceSingleAsync<T>(), + pair.Key, pair.Value)); try - { + { await Task.WhenAll(tasks).WithAggregateException(); } catch (Exception ex) { - this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); + SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex)); } } } @@ -400,46 +405,48 @@ private async Task ResetAfterPull(Task<T> task, string key, OfflineEntry entry) { await task; - this.SetAndRaise(key, new OfflineEntry(key, task.Result, entry.Priority, SyncOptions.None), FirebaseEventSource.OnlinePull); + SetAndRaise(key, new OfflineEntry(key, task.Result, entry.Priority, SyncOptions.None), + FirebaseEventSource.OnlinePull); } private async Task ResetSyncAfterPush(Task task, string key, T obj) { - await this.ResetSyncAfterPush(task, key); + await ResetSyncAfterPush(task, key); - if (this.streamingOptions == StreamingOptions.None) - { - this.subject.OnNext(new FirebaseEvent<T>(key, obj, obj == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, FirebaseEventSource.OnlinePush)); - } + if (streamingOptions == StreamingOptions.None) + subject.OnNext(new FirebaseEvent<T>(key, obj, + obj == null ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate, + FirebaseEventSource.OnlinePush)); } private async Task ResetSyncAfterPush(Task task, string key) { await task; - this.ResetSyncOptions(key); + ResetSyncOptions(key); } private void ResetSyncOptions(string key) { - var item = this.Database[key]; + var item = Database[key]; if (item.IsPartial) { - this.Database.Remove(key); + Database.Remove(key); } else { item.SyncOptions = SyncOptions.None; - this.Database[key] = item; + Database[key] = item; } } private void StreamingExceptionThrown(object sender, ExceptionEventArgs<FirebaseException> e) { - this.SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception)); + SyncExceptionThrown?.Invoke(this, new ExceptionEventArgs(e.Exception)); } - private Tuple<string, string, bool> GenerateFullKey<TProperty>(string key, Expression<Func<T, TProperty>> propertyGetter, SyncOptions syncOptions) + private Tuple<string, string, bool> GenerateFullKey<TProperty>(string key, + Expression<Func<T, TProperty>> propertyGetter, SyncOptions syncOptions) { var visitor = new MemberAccessVisitor(); visitor.Visit(propertyGetter); @@ -447,13 +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<T> : ISetHandler<T> @@ -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 @@ /// </summary> 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 @@ /// </summary> 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 /// <param name="parent"> The parent. </param> /// <param name="tokenFactory"> The authentication token factory. </param> /// <param name="client"> The owner. </param> - public AuthQuery(FirebaseQuery parent, Func<string> tokenFactory, FirebaseClient client) : base(parent, () => client.Options.AsAccessToken ? "access_token" : "auth", client) + public AuthQuery(FirebaseQuery parent, Func<string> tokenFactory, FirebaseClient client) : base(parent, + () => client.Options.AsAccessToken ? "access_token" : "auth", client) { this.tokenFactory = tokenFactory; } @@ -27,7 +28,7 @@ namespace Firebase.Database.Query /// <returns> The <see cref="string"/>. </returns> protected override string BuildUrlParameter(FirebaseQuery child) { - return this.tokenFactory(); + return tokenFactory(); } } -} +}
\ No newline at end of file diff --git a/FireBase/Query/ChildQuery.cs b/FireBase/Query/ChildQuery.cs index 1696ea8..510ae75 100644 --- a/FireBase/Query/ChildQuery.cs +++ b/FireBase/Query/ChildQuery.cs @@ -1,7 +1,7 @@ namespace Firebase.Database.Query { using System; - + /// <summary> /// Firebase query which references the child of current node. /// </summary> @@ -38,19 +38,13 @@ namespace Firebase.Database.Query /// <returns> The <see cref="string"/>. </returns> protected override string BuildUrlSegment(FirebaseQuery child) { - var s = this.pathFactory(); + var s = pathFactory(); - if (s != string.Empty && !s.EndsWith("/")) - { - s += '/'; - } + if (s != string.Empty && !s.EndsWith("/")) s += '/'; - if (!(child is ChildQuery)) - { - return s + ".json"; - } + if (!(child is ChildQuery)) return s + ".json"; return s; } } -} +}
\ No newline at end of file diff --git a/FireBase/Query/FilterQuery.cs b/FireBase/Query/FilterQuery.cs index f9f6271..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 /// <summary> /// Represents a firebase filtering query, e.g. "?LimitToLast=10". /// </summary> - public class FilterQuery : ParameterQuery + public class FilterQuery : ParameterQuery { private readonly Func<string> valueFactory; private readonly Func<double> doubleValueFactory; @@ -19,7 +19,8 @@ namespace Firebase.Database.Query /// <param name="filterFactory"> The filter. </param> /// <param name="valueFactory"> The value for filter. </param> /// <param name="client"> The owning client. </param> - public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<string> valueFactory, FirebaseClient client) + public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<string> valueFactory, + FirebaseClient client) : base(parent, filterFactory, client) { this.valueFactory = valueFactory; @@ -32,10 +33,11 @@ namespace Firebase.Database.Query /// <param name="filterFactory"> The filter. </param> /// <param name="valueFactory"> The value for filter. </param> /// <param name="client"> The owning client. </param> - public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<double> valueFactory, FirebaseClient client) + public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<double> valueFactory, + FirebaseClient client) : base(parent, filterFactory, client) { - this.doubleValueFactory = valueFactory; + doubleValueFactory = valueFactory; } /// <summary> @@ -45,10 +47,11 @@ namespace Firebase.Database.Query /// <param name="filterFactory"> The filter. </param> /// <param name="valueFactory"> The value for filter. </param> /// <param name="client"> The owning client. </param> - public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<bool> valueFactory, FirebaseClient client) + public FilterQuery(FirebaseQuery parent, Func<string> filterFactory, Func<bool> valueFactory, + FirebaseClient client) : base(parent, filterFactory, client) { - this.boolValueFactory = valueFactory; + boolValueFactory = valueFactory; } /// <summary> @@ -58,24 +61,21 @@ namespace Firebase.Database.Query /// <returns> Url parameter part of the resulting path. </returns> 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 /// <param name="client"> The owning client. </param> protected FirebaseQuery(FirebaseQuery parent, FirebaseClient client) { - this.Client = client; - this.Parent = parent; + Client = client; + Parent = parent; } /// <summary> /// Gets the client. /// </summary> - public FirebaseClient Client - { - get; - } + public FirebaseClient Client { get; } /// <summary> /// 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<T>(url, Client.Options.JsonSerializerSettings) + return await GetClient(timeout).GetObjectCollectionAsync<T>(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 /// <typeparam name="T"> Type of elements. </typeparam> /// <param name="elementRoot"> Optional custom root element of received json items. </param> /// <returns> Observable stream of <see cref="FirebaseEvent{T}"/>. </returns> - public IObservable<FirebaseEvent<T>> AsObservable<T>(EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler = null, string elementRoot = "") + public IObservable<FirebaseEvent<T>> AsObservable<T>( + EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler = null, string elementRoot = "") { return Observable.Create<FirebaseEvent<T>>(observer => { @@ -144,13 +141,13 @@ namespace Firebase.Database.Query public async Task<string> BuildUrlAsync() { // if token factory is present on the parent then use it to generate auth token - if (this.Client.Options.AuthTokenAsyncFactory != null) + 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); } /// <summary> @@ -161,20 +158,21 @@ namespace Firebase.Database.Query /// <param name="timeout"> Optional timeout value. </param> /// <typeparam name="T"> Type of <see cref="obj"/> </typeparam> /// <returns> Resulting firebase object with populated key. </returns> - public async Task<FirebaseObject<string>> PostAsync(string data, bool generateKeyOffline = true, TimeSpan? timeout = null) + public async Task<FirebaseObject<string>> PostAsync(string data, bool generateKeyOffline = true, + TimeSpan? timeout = null) { // post generates a new key server-side, while put can be used with an already generated local key if (generateKeyOffline) { var key = FirebaseKeyGenerator.Next(); - await new ChildQuery(this, () => key, this.Client).PutAsync(data).ConfigureAwait(false); + await new ChildQuery(this, () => key, Client).PutAsync(data).ConfigureAwait(false); return new FirebaseObject<string>(key, data); } else { - var c = this.GetClient(timeout); - var sendData = await this.SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false); + var c = GetClient(timeout); + var sendData = await SendAsync(c, data, HttpMethod.Post).ConfigureAwait(false); var result = JsonConvert.DeserializeObject<PostResult>(sendData, Client.Options.JsonSerializerSettings); return new FirebaseObject<string>(result.Name, data); @@ -190,7 +188,7 @@ namespace Firebase.Database.Query /// <returns> The <see cref="Task"/>. </returns> public async Task PatchAsync(string data, TimeSpan? timeout = null) { - var c = this.GetClient(timeout); + var c = GetClient(timeout); await this.Silent().SendAsync(c, data, new HttpMethod("PATCH")).ConfigureAwait(false); } @@ -204,7 +202,7 @@ namespace Firebase.Database.Query /// <returns> The <see cref="Task"/>. </returns> public async Task PutAsync(string data, TimeSpan? timeout = null) { - var c = this.GetClient(timeout); + var c = GetClient(timeout); await this.Silent().SendAsync(c, data, HttpMethod.Put).ConfigureAwait(false); } @@ -216,14 +214,14 @@ namespace Firebase.Database.Query /// <returns> The <see cref="Task"/>. </returns> public async Task DeleteAsync(TimeSpan? timeout = null) { - var c = this.GetClient(timeout); + var c = GetClient(timeout); var url = string.Empty; var responseData = string.Empty; var statusCode = HttpStatusCode.OK; try { - url = await this.BuildUrlAsync().ConfigureAwait(false); + url = await BuildUrlAsync().ConfigureAwait(false); } catch (Exception ex) { @@ -249,7 +247,7 @@ namespace Firebase.Database.Query /// </summary> public void Dispose() { - this.client?.Dispose(); + client?.Dispose(); } /// <summary> @@ -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<string> 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; /// <summary> /// The FirebaseQuery interface. @@ -14,10 +13,7 @@ /// <summary> /// Gets the owning client of this query. /// </summary> - FirebaseClient Client - { - get; - } + FirebaseClient Client { get; } /// <summary> /// Retrieves items which exist on the location specified by this query instance. @@ -32,7 +28,8 @@ /// </summary> /// <typeparam name="T"> Type of the items. </typeparam> /// <returns> Cold observable of <see cref="FirebaseEvent{T}"/>. </returns> - IObservable<FirebaseEvent<T>> AsObservable<T>(EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler, string elementRoot = ""); + IObservable<FirebaseEvent<T>> AsObservable<T>( + EventHandler<ExceptionEventArgs<FirebaseException>> exceptionHandler, string elementRoot = ""); /// <summary> /// Builds the actual url of this query. @@ -40,4 +37,4 @@ /// <returns> The <see cref="string"/>. </returns> Task<string> BuildUrlAsync(); } -} +}
\ No newline at end of file diff --git a/FireBase/Query/OrderQuery.cs b/FireBase/Query/OrderQuery.cs index 46ebd2c..16adba7 100644 --- a/FireBase/Query/OrderQuery.cs +++ b/FireBase/Query/OrderQuery.cs @@ -28,7 +28,7 @@ namespace Firebase.Database.Query /// <returns> The <see cref="string"/>. </returns> protected override string BuildUrlParameter(FirebaseQuery child) { - return $"\"{this.propertyNameFactory()}\""; + return $"\"{propertyNameFactory()}\""; } } -} +}
\ No newline at end of file diff --git a/FireBase/Query/ParameterQuery.cs b/FireBase/Query/ParameterQuery.cs index e3d9717..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 ? "?" : "&"; } /// <summary> @@ -30,7 +30,7 @@ namespace Firebase.Database.Query /// <returns> The <see cref="string"/>. </returns> protected override string BuildUrlSegment(FirebaseQuery child) { - return $"{this.separator}{this.parameterFactory()}={this.BuildUrlParameter(child)}"; + return $"{separator}{parameterFactory()}={BuildUrlParameter(child)}"; } /// <summary> @@ -40,4 +40,4 @@ namespace Firebase.Database.Query /// <returns> The <see cref="string"/>. </returns> protected abstract string BuildUrlParameter(FirebaseQuery child); } -} +}
\ No newline at end of file diff --git a/FireBase/Query/QueryExtensions.cs b/FireBase/Query/QueryExtensions.cs index 77db644..735fe0a 100644 --- a/FireBase/Query/QueryExtensions.cs +++ b/FireBase/Query/QueryExtensions.cs @@ -119,7 +119,7 @@ namespace Firebase.Database.Query { return child.EqualTo(() => value); } - + /// <summary> /// Instructs firebase to send data equal to the <see cref="value"/>. This must be preceded by an OrderBy query. /// </summary> @@ -129,7 +129,7 @@ namespace Firebase.Database.Query public static FilterQuery EqualTo(this ParameterQuery child, bool value) { return child.EqualTo(() => value); - } + } /// <summary> /// Instructs firebase to send data equal to null. This must be preceded by an OrderBy query. @@ -139,7 +139,7 @@ namespace Firebase.Database.Query public static FilterQuery EqualTo(this ParameterQuery child) { return child.EqualTo(() => null); - } + } /// <summary> /// Limits the result to first <see cref="count"/> items. @@ -173,9 +173,12 @@ namespace Firebase.Database.Query return query.PatchAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings)); } - public static async Task<FirebaseObject<T>> PostAsync<T>(this FirebaseQuery query, T obj, bool generateKeyOffline = true) + public static async Task<FirebaseObject<T>> PostAsync<T>(this FirebaseQuery query, T obj, + bool generateKeyOffline = true) { - var result = await query.PostAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings), generateKeyOffline); + var result = + await query.PostAsync(JsonConvert.SerializeObject(obj, query.Client.Options.JsonSerializerSettings), + generateKeyOffline); return new FirebaseObject<T>(result.Key, obj); } @@ -189,19 +192,13 @@ namespace Firebase.Database.Query /// <param name="relativePaths"> Locations where to store the item. </param> public static async Task FanOut<T>(this ChildQuery child, T item, params string[] relativePaths) { - if (relativePaths == null) - { - throw new ArgumentNullException(nameof(relativePaths)); - } + if (relativePaths == null) throw new ArgumentNullException(nameof(relativePaths)); var fanoutObject = new Dictionary<string, T>(relativePaths.Length); - foreach (var path in relativePaths) - { - fanoutObject.Add(path, item); - } + foreach (var path in relativePaths) fanoutObject.Add(path, item); await child.PatchAsync(fanoutObject); } } -} +}
\ No newline at end of file diff --git a/FireBase/Query/QueryFactoryExtensions.cs b/FireBase/Query/QueryFactoryExtensions.cs index b36e74a..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); } - + /// <summary> /// Instructs firebase to send data equal to the <see cref="valueFactory"/>. This must be preceded by an OrderBy query. /// </summary> @@ -149,7 +149,7 @@ namespace Firebase.Database.Query public static FilterQuery EqualTo(this ParameterQuery child, Func<bool> valueFactory) { return new FilterQuery(child, () => "equalTo", valueFactory, child.Client); - } + } /// <summary> /// Limits the result to first <see cref="countFactory"/> items. @@ -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 @@ /// </summary> public class SilentQuery : ParameterQuery { - public SilentQuery(FirebaseQuery parent, FirebaseClient client) + public SilentQuery(FirebaseQuery parent, FirebaseClient client) : base(parent, () => "print", client) { } @@ -15,4 +15,4 @@ return "silent"; } } -} +}
\ No newline at end of file diff --git a/FireBase/Streaming/FirebaseCache.cs b/FireBase/Streaming/FirebaseCache.cs index ba7990b..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; /// <summary> @@ -18,6 +16,7 @@ namespace Firebase.Database.Streaming { private readonly IDictionary<string, T> dictionary; private readonly bool isDictionaryType; + private readonly JsonSerializerSettings serializerSettings = new JsonSerializerSettings() { ObjectCreationHandling = ObjectCreationHandling.Replace @@ -26,7 +25,7 @@ namespace Firebase.Database.Streaming /// <summary> /// Initializes a new instance of the <see cref="FirebaseCache{T}"/> class. /// </summary> - public FirebaseCache() + public FirebaseCache() : this(new Dictionary<string, T>()) { } @@ -37,8 +36,8 @@ namespace Firebase.Database.Streaming /// <param name="existingItems"> The existing items. </param> public FirebaseCache(IDictionary<string, T> existingItems) { - this.dictionary = existingItems; - this.isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); + dictionary = existingItems; + isDictionaryType = typeof(IDictionary).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo()); } /// <summary> @@ -53,11 +52,11 @@ namespace Firebase.Database.Streaming Action<object> primitiveObjSetter = null; Action objDeleter = null; - var pathElements = path.Split(new[] { "/" }, removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None); + var pathElements = path.Split(new[] {"/"}, + removeEmptyEntries ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None); // first find where we should insert the data to foreach (var element in pathElements) - { if (obj is IDictionary) { // if it's a dictionary, then it's just a matter of inserting into it / accessing existing object by key @@ -73,7 +72,7 @@ namespace Firebase.Database.Streaming } else { - dictionary[element] = this.CreateInstance(valueType); + dictionary[element] = CreateInstance(valueType); obj = dictionary[element]; } } @@ -84,24 +83,24 @@ namespace Firebase.Database.Streaming var property = objParent .GetType() .GetRuntimeProperties() - .First(p => p.Name.Equals(element, StringComparison.OrdinalIgnoreCase) || element == p.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName); + .First(p => p.Name.Equals(element, StringComparison.OrdinalIgnoreCase) || + element == p.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName); objDeleter = () => property.SetValue(objParent, null); primitiveObjSetter = (d) => property.SetValue(objParent, d); obj = property.GetValue(obj); if (obj == null) { - obj = this.CreateInstance(property.PropertyType); + obj = CreateInstance(property.PropertyType); property.SetValue(objParent, obj); } } - } // if data is null (=empty string) delete it if (string.IsNullOrWhiteSpace(data) || data == "null") { var key = pathElements[0]; - var target = this.dictionary[key]; + var target = dictionary[key]; objDeleter(); @@ -110,7 +109,7 @@ namespace Firebase.Database.Streaming } // now insert the data - if (obj is IDictionary && !this.isDictionaryType) + if (obj is IDictionary && !isDictionaryType) { // insert data into dictionary and return it as a collection of FirebaseObject var dictionary = obj as IDictionary; @@ -122,10 +121,7 @@ namespace Firebase.Database.Streaming dictionary[item.Key] = item.Object; // top level dictionary changed - if (!pathElements.Any()) - { - yield return new FirebaseObject<T>(item.Key, (T)item.Object); - } + if (!pathElements.Any()) yield return new FirebaseObject<T>(item.Key, (T) item.Object); } // nested dictionary changed @@ -141,52 +137,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<T>(pathElements[0], this.dictionary[pathElements[0]]); + dictionary[pathElements[0]] = dictionary[pathElements[0]]; + yield return new FirebaseObject<T>(pathElements[0], dictionary[pathElements[0]]); } } public bool Contains(string key) { - return this.dictionary.Keys.Contains(key); + return dictionary.Keys.Contains(key); } private object CreateInstance(Type type) { if (type == typeof(string)) - { return string.Empty; - } else - { return Activator.CreateInstance(type); - } } #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { - return this.GetEnumerator(); + return GetEnumerator(); } public IEnumerator<FirebaseObject<T>> GetEnumerator() { - return this.dictionary.Select(p => new FirebaseObject<T>(p.Key, p.Value)).GetEnumerator(); + return dictionary.Select(p => new FirebaseObject<T>(p.Key, p.Value)).GetEnumerator(); } #endregion } -} +}
\ No newline at end of file diff --git a/FireBase/Streaming/FirebaseEvent.cs b/FireBase/Streaming/FirebaseEvent.cs index c2338ca..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; } /// <summary> /// Gets the source of the event. /// </summary> - public FirebaseEventSource EventSource - { - get; - } + public FirebaseEventSource EventSource { get; } /// <summary> /// Gets the event type. /// </summary> - public FirebaseEventType EventType + public FirebaseEventType EventType { get; } + + public static FirebaseEvent<T> Empty(FirebaseEventSource source) { - get; + return new FirebaseEvent<T>(string.Empty, default(T), FirebaseEventType.InsertOrUpdate, source); } - - public static FirebaseEvent<T> Empty(FirebaseEventSource source) => new FirebaseEvent<T>(string.Empty, default(T), FirebaseEventType.InsertOrUpdate, source); } -} +}
\ No newline at end of file diff --git a/FireBase/Streaming/FirebaseEventSource.cs b/FireBase/Streaming/FirebaseEventSource.cs index 98df977..0a397ad 100644 --- a/FireBase/Streaming/FirebaseEventSource.cs +++ b/FireBase/Streaming/FirebaseEventSource.cs @@ -35,4 +35,4 @@ /// </summary> Online = OnlineInitial | OnlinePull | OnlinePush | OnlineStream } -} +}
\ No newline at end of file diff --git a/FireBase/Streaming/FirebaseEventType.cs b/FireBase/Streaming/FirebaseEventType.cs index 5fb21ef..d8c65b3 100644 --- a/FireBase/Streaming/FirebaseEventType.cs +++ b/FireBase/Streaming/FirebaseEventType.cs @@ -15,4 +15,4 @@ namespace Firebase.Database.Streaming /// </summary> Delete } -} +}
\ No newline at end of file diff --git a/FireBase/Streaming/FirebaseServerEventType.cs b/FireBase/Streaming/FirebaseServerEventType.cs index 1f10bc8..79c816d 100644 --- a/FireBase/Streaming/FirebaseServerEventType.cs +++ b/FireBase/Streaming/FirebaseServerEventType.cs @@ -12,4 +12,4 @@ namespace Firebase.Database.Streaming AuthRevoked } -} +}
\ No newline at end of file diff --git a/FireBase/Streaming/FirebaseSubscription.cs b/FireBase/Streaming/FirebaseSubscription.cs index 4b5e643..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 /// <param name="observer"> The observer. </param> /// <param name="query"> The query. </param> /// <param name="cache"> The cache. </param> - public FirebaseSubscription(IObserver<FirebaseEvent<T>> observer, IFirebaseQuery query, string elementRoot, FirebaseCache<T> cache) + public FirebaseSubscription(IObserver<FirebaseEvent<T>> observer, IFirebaseQuery query, string elementRoot, + FirebaseCache<T> cache) { this.observer = observer; this.query = query; this.elementRoot = elementRoot; - this.cancel = new CancellationTokenSource(); + cancel = new CancellationTokenSource(); this.cache = cache; - this.client = query.Client; + client = query.Client; } public event EventHandler<ExceptionEventArgs<FirebaseException>> ExceptionThrown; public void Dispose() { - this.cancel.Cancel(); + cancel.Cancel(); } public 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<FirebaseException>(new FirebaseException(url, string.Empty, line, statusCode, ex))); + ExceptionThrown?.Invoke(this, + new ExceptionEventArgs<FirebaseException>(new FirebaseException(url, string.Empty, line, + statusCode, ex))); await Task.Delay(2000).ConfigureAwait(false); } @@ -185,30 +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<T>.Empty(FirebaseEventSource.OnlineStream)); + observer.OnNext(FirebaseEvent<T>.Empty(FirebaseEventSource.OnlineStream)); return; } - } - var eventType = string.IsNullOrWhiteSpace(data) ? FirebaseEventType.Delete : FirebaseEventType.InsertOrUpdate; + var eventType = string.IsNullOrWhiteSpace(data) + ? FirebaseEventType.Delete + : FirebaseEventType.InsertOrUpdate; - var items = this.cache.PushData(this.elementRoot + path, data); + var items = cache.PushData(elementRoot + path, data); foreach (var i in items.ToList()) - { - this.observer.OnNext(new FirebaseEvent<T>(i.Key, i.Object, eventType, FirebaseEventSource.OnlineStream)); - } + observer.OnNext(new FirebaseEvent<T>(i.Key, i.Object, eventType, + FirebaseEventSource.OnlineStream)); break; case FirebaseServerEventType.KeepAlive: break; case FirebaseServerEventType.Cancel: - this.observer.OnError(new FirebaseException(url, string.Empty, serverData, HttpStatusCode.Unauthorized)); - this.Dispose(); + observer.OnError(new FirebaseException(url, string.Empty, serverData, HttpStatusCode.Unauthorized)); + Dispose(); break; } } @@ -218,4 +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 |