step-up-labs / firebase-database-dotnet Goto Github PK
View Code? Open in Web Editor NEWC# library for Firebase Realtime Database.
License: MIT License
C# library for Firebase Realtime Database.
License: MIT License
I can read ok - now trying to update a value. But I can't get over this compiler error:
"Cannot assign void to an implicitly-typed variable"
My firebase data:
104837
.....newMessage:
.............false
My code:
bool newval = true;
var result = await firebase
.Child("104837")
.Child("newMessage")
.WithAuth(auth.FirebaseToken)
.PutAsync(newval);
I must be doing something fundamentally wrong...
Thanks!
Steve
When I execute Post(new Client(){name = "client1"})
it gives
{ "parent" : { "clients" : { "a123" : { "-KbGy8X22UEbtUnTJNKh" : { "name" : "client1" } }, "info" : "data" } } }
But what I want is:
{ "parent" : { "clients" : { "a123" : { "name" : "client1" }, "info" : "data" } } }
What do I have to change?
I am trying to subscribe to the Firebase Database so that my Xamarin.Forms App's content is updated whenever some values are changed on Firebase Database ( Through direct modification on Firebase Database, or through other copies of the App using ".PutAsync" ). I want to do this so that I don't have to set a timer to make the App refreshes every second just to check if the value has been changed on Firebase Database ( The purpose of the App requires certain values to be refreshed and updated to "Current_Queue_Number.Text" as soon as the values have been updated on Firebase Database ).
I am able to "PutAsync" correctly to Firebase Database, so I don't think it is the problem of my pathing or data structure, however, the ".Subscribe" function just won't update the value in the App when the data is changed on Firebase Database, and there is not error or warning.
This is what my codes look like:
This is what my Firebase Database structure looks like:
Would you kindly help me out on this?
Thanks so much!
When I subscribe to the authorsDb like this:
authorsDb.AsObservable().Subscribe(x => Sub(x));
The Sub function is called for any offline entry of the authorsDb database. Also If I write a single chat message, Sub get's called first offline and then from online. So far so good. But after restarting the application, Sub get's called for all the entries within authorsDb and also there are some online changes firing the Sub function. Why is this? Again I'm new to firebase but I would expect that once the offline database is synced, and I do not change anything, the Sub function should not get called. Same holds for online change events I get after every restart of my application.
Why is this?
Hello,
Is it possible to do a PostAsync request with a manually defined key?
I want to follow the example below setting the auth.uid
as the key.
https://firebase.google.com/docs/database/security/user-security
Thanks!
Please see my comment on this commit.
Hi auth, i see the second param on client var firebase = new FirebaseClient(uri, ... );
but how to use it ?
please help !
If to subscribe to a non existing path in Firebase it will invoke callback with null value. However FirebaseDatabase library does not notify subscribers at all.
ProcessServerData method of FirebaseSubscription class must call this.observer.OnNext also when items collection is empty.
The library Firebase.Database.dll can not be used in a signed solution because it does not have a strong name. You will get this exception on application load : "A strongly-named assembly is required. (Exception from HRESULT: 0x80131044)"
I have a test project and I want to retrieve a list of items on a firebaseUser. I have this working on my Cordova hybred mobile app using angularfire. How would I do the same thing with you database package?
Javascript:
var root = firebase.database().ref();
// uid is the authenticated user's uid
locations = $firebaseArray(root.child('users').child(uid).child('locations'));
C#:
var config = new FirebaseConfig("my application key");
var authProvider = new FirebaseAuthProvider(config);
var auth = await authProvider.SignInWithEmailAndPasswordAsync("[email protected]", "password");
var firebase = new FirebaseClient("https://myapp-at.firebaseio.com");
var locations = firebase.Child("users").???
I don't see any of the linq methods with intellisense, am I missing some using statements.
Jay
If you would like to get all dinosaurus objects with order property equal to "pterosauria" how would you write that with this library?
I tried:
await firebase.Child("dinosaurs").OrderBy("order").EqualTo("pterosauria").OnceAsync<Dinosaurus>();
But I get bad request for this query, what I did wrong?
Hi,
Your library it sounds promising, but unfortunately I don't see how it can be used for a web server. The usage of profile 111 it is very limited. I see that one of the reason is the usage of Rx library. Since this library does not seems to have support for .NET core, do you plan to migrate your library to .NET core and eventually get rid of Rx library ?
Hi, i found good library after googling on Firebase Database API from C#. this library is working fine.
I want to push my data into Firebase Real Time Database with our specified key (not automated generated key). Please suggest solution of my problem.
Thanks in advance.
When new data is "pushed" to firebase, there appears to be a double "put" received when using the streaming api, after inspecting the result at FirebaseSubscription.cs:170
var result = JObject.Parse(serverData);
The first "put" contains only the new data:
{"path":"/list/-KS-k0EWj76Oc3gtnVx0","data":{"name":"New Item 00:41:54 GMT-0400 (EDT)"}}
The second "put" contains the entire data set:
{"path":"/","data":{"list":{"-KS-esW1NFCmzLO_gu-_":{"name":"Old Item 00:19:25 GMT-0400 (EDT)"},"-KS-k0EWj76Oc3gtnVx0":{"name":"New Item 00:41:54 GMT-0400 (EDT)"}}}}
Is this normal? Is the firebase REST API sending these back?
Thanks.
Hi, I am currently having an issue when trying to retrieve a node in my firebase DB. When there are multiple children, everything works fine, however, if there is only one child I get a "Cannot deserialize the current JSON array error.
The return data looks like: [{"835c442d-b5ae-42e5-8a13-b57aefe31d43":{"jobno":"0","partdescription":"","partid":"835c442d-b5ae-42e5-8a13-b57aefe31d43","partimagelocation":"n/a","partmake":"40 gallon cwt","partmodel":"","timestamp":"2017-03-28 16:28:19"}}]
My code looks like:
var rpresult = await firebase
.Child("returnpartsreqdata")
.OnceAsync();
Any thoughts please ?
I am writing the program for delete the node but no work
Here's my code.
FirebasClient client2 =new FirebaseClient("http://XXXXXX.firebaseio.com/");
var nodelist= client2.Child("log");
await nodelist.DeleteAsync();
Also, may I know how to update or delete the values base on the where clause?
It would be nice to be able to change the serializer setting to use camelCase instead of PascalCase for storing object to Firebase. Maybe as a new option in FirebaseOptions
?
PascalCase
{
"FirstName": "John",
"LastName": "Doe"
}
camelCase
{
"firstName": "John",
"lastName": "Doe"
}
If you need a hand, I will be happy to help. Cheers!
Is there a way to push a collection of items at once, e.g. PostAsync(IEnumerable<Dinosaur>)
with online or offline -generated object keys?
Hello,
I have been testing the ConsoleChat sample, and discovered that when you manually modify a message in the Firebase Console (like changing the value of "Content"), no further notifications occur on the observable.
The following exception is being thrown:
System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add) at System.Collections.Generic.Dictionary
2.System.Collections.IDictionary.Add(Object key, Object value)
at Firebase.Database.Streaming.FirebaseCache1.<PushData>d__3.MoveNext() at System.Collections.Generic.List
1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable
1 source)
at Firebase.Database.Streaming.FirebaseSubscription1.ProcessServerData(FirebaseServerEventType serverEvent, String serverData) at Firebase.Database.Streaming.FirebaseSubscription
1.d__9.MoveNext()
Thanks!
WACK does not like dependencies build in Debug mode.
In file FirebaseSubscription line 176
var data = result["data"].ToString();
If the data is a boolean in firebase the value of result["data"] is {True} and the string representation is "True". It will then fail in file FirebaseCache.cs at line 131 when attempting to deserialize "True" to a boolean value
var targetObject = valueType == typeof(string) ? data.ToString() : JsonConvert.DeserializeObject(data, valueType);
Are those transactions already implemented? I guess they are quite helpful.
Hi! I need remove an item.
How can do it?
I have some database rules setup and the simulator recognizes them but the api never returns error with a request that violates the Firebase Realtime Database Rules.
Thank
AuthQuery parameter name should be "access_token" instead of "auth" to use service account.
Sorry it's me again. I would like to write the query to search the member who is female and height is greater than 170cm.
In URL query, it should look like that
https://xxxx.firebaseio.com/profiles/.json?orderBy="sex"&equalTo="f"&orderBy="height"&startwith="170"
But I can't write more than two conditions in c# like that
var ddd = client
.Child("profiles")
.OrderBy("sex")
.equalTo("f")
OrderBy("height")
.startwith("170")
.OnceAsync();
Do you consider it possible to adopt in the future implementation of paging tools as does the firebase-util library?
https://github.com/firebase/firebase-util/tree/master/src/Paginate
How can I use EqualTo to query a boolean property.
EqualTo() only accepts a bool or a double. But I'm trying to do something like this:
var appointments = await client
.Child("appointments")
.OrderBy("isBooked")
.EqualTo(true)
.OnceAsync();
Hi, First of all let me congratulate you for the initiative on this project. I am currently doing tests with the library installed from nuget and have detected unusual behavior in searches using the OnceSingleAsync () method. The result is always the same, returning one object with its properties initialized by default.
var result = await ctx.Child("Clients") .OrderByKey() .EqualTo("V223") .OnceSingleAsync<Client>();
But if the same query using the OnceAsync () function returns me the expected results.
var result = await ctx.Child("Clients") .OrderByKey() .EqualTo("V223") .OnceAsync<Client>();
Hello,
I'm trying to listen to Firebase event with the following code:
var child = firebase.Child("Devices").Child("Status");
var observable = child.AsObservable<string>();
var subscription = observable.Where(f => f.Key == "Muted").Subscribe(d => test(d.Object));
It's pulling the right value from the database when it's first called. But later when the value is updated, it will throw the following exception:
For example if the value is '000f'
Exception thrown: 'System.FormatException' in mscorlib.ni.dll
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
************************************************************
Newtonsoft.Json.JsonReaderException: Input string '000f' is not a valid number. Path '', line 1, position 4. ---> System.FormatException: Additional non-parsable characters are at the end of the string.
at System.ParseNumbers.StringToLong(String s, Int32 radix, Int32 flags, Int32* currPos)
at System.Convert.ToInt64(String value, Int32 fromBase)
at Newtonsoft.Json.JsonTextReader.ParseNumber(ReadType readType)
--- End of inner exception stack trace ---
at Newtonsoft.Json.JsonTextReader.ParseNumber(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadAsString()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type)
at Firebase.Database.Streaming.FirebaseCache`1.<PushData>d__3.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Firebase.Database.Streaming.FirebaseSubscription`1.ProcessServerData(FirebaseServerEventType serverEvent, String serverData)
at Firebase.Database.Streaming.FirebaseSubscription`1.<ReceiveThread>d__8.MoveNext()
************************************************************
Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
************************************************************
System.ArgumentException: An item with the same key has already been added. Key: Muted
at System.ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(Object key)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary`2.System.Collections.IDictionary.Add(Object key, Object value)
at Firebase.Database.Streaming.FirebaseCache`1.<PushData>d__3.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Firebase.Database.Streaming.FirebaseSubscription`1.ProcessServerData(FirebaseServerEventType serverEvent, String serverData)
at Firebase.Database.Streaming.FirebaseSubscription`1.<ReceiveThread>d__8.MoveNext()
************************************************************
And if the value is 'true':
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
************************************************************
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: T. Path '', line 1, position 1.
at Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)
at Newtonsoft.Json.JsonTextReader.ReadAsString()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type)
at Firebase.Database.Streaming.FirebaseCache`1.<PushData>d__3.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Firebase.Database.Streaming.FirebaseSubscription`1.ProcessServerData(FirebaseServerEventType serverEvent, String serverData)
at Firebase.Database.Streaming.FirebaseSubscription`1.<ReceiveThread>d__8.MoveNext()
************************************************************
However if the value is a number then there is no problem.
I'm getting the following error:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary`2[System.String,Empty.Module.Controllers.Demp]' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '', line 1, position 1.
when I'm running
var sample = await firebase
.Child("first")
.WithAuth(auth.FirebaseToken)
.OnceAsync();
How can I correct the error?
Thanks
This is because FirebaseSubscription class uses single HttpClient instance for all subscriptions, however for HTTP 1.1 you have maximum of 2 TCP connection per host (e.g. server) that can be active (see https://social.msdn.microsoft.com/Forums/en-US/1f863f20-09f9-49a5-8eee-17a89b591007/asynchronous-httpwebrequest-maximum-connections-best-approach-threads-or-delegates?forum=netfxnetcom).
I'm trying to make this library work with VB.NET, and I think I have the authentication working OK, but I just can't translate the examples into a working syntax for VB - could you show me an example of how to return a simple query?
Russell
Is it possible to use Firebase transaction for incrementing a value in the database?
Refer to Firebase "https://dinosaur-facts.firebaseio.com/"
How can I write the query if the dinosaur of height is greater than 1 in descending order
Exists any way or method to initialise the property in my class with firebase server datetime "{'.sv':'timestamp'}" pushing the data to firebase?
There is no database secret for firebase database anymore, so without that how do we authenticate as an admin from the server.
I want to know if is possible use logic like onDisconnect to set the lastOnline timestamp. like this:
var userLastOnlineRef = firebase.database().ref("users/joe/lastOnline");
var userStatusRef = firebase.database().ref("users/joe/status");
userLastOnlineRef.onDisconnect().set(firebase.database.ServerValue.TIMESTAMP);
userStatusRef.onDisconnect().set("offline");
or how could I do it?
thanks.
Hi
I was attempting to use StartAt / EndAt with a generated key, however the URL parameters converted the value to lowercase when building the URL. This is problematic as Firebase paths / keys are case sensitive.
PS:
Visual Studio 2015 syntax makes it a schlep to compile the source code in an older version of Visual Studio.
I've got some pretty simple code which should create a new ClassRoom object and save it to Firebase under "classRooms". If I change my authentication rules in the database to allow universal access and I remove the authentication part of the request, everything works fine. So I think the issue has something to do with authentication.
Here's the code which makes the request:
String id = subjectId.Text;
String name = subjectName.Text;
String activity = this.activity.Text;
var classRoom = await firebase
.Child("classRooms")
.WithAuth(auth.FirebaseToken)
.PostAsync<ClassRoom>(new ClassRoom(id, name, activity));
And here's the ClassRoom class:
class ClassRoom
{
public String subjectId;
public String subjectName;
public String activity;
public ClassRoom(String subjectId, String subjectName, String activity)
{
this.subjectId = subjectId;
this.subjectName = subjectName;
this.activity = activity;
}
}
Thanks so much for any time anyone puts in to this. Your efforts are much appreciated 👍
I tried to debug at if(o.EventType == ...
but it not run in men.
please help !
here my code:
.Client
.Child("locations")
.AsObservable<Models.Location>()
.Subscribe(o=> {
if (o.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate)
{
o.Object.Oid = o.Key;
var exist = Locations.FirstOrDefault(x => x.Oid == o.Key);
var index = Locations.IndexOf(exist);
if (exist != null)
{
Locations.RemoveAt(index);
}
if (index > -1)
Locations.Insert(index, o.Object);
else
Locations.Insert(0, o.Object);
}
else if (o.EventType== Firebase.Database.Streaming.FirebaseEventType.Delete)
{
// delete
Locations.Remove(o.Object);
}
});
Suggest: i think we should split event Insert & Update. Simple, i need show message: Item Added or Item Updated to user.
Thanks author !
It is possible to enable Offline database with this framework?
Thanks
Let's say we have such list
{
data:
{
key1: "x",
key2: "y",
key3: "z"
}
}
How to subscribe for data and get its all content as dictionary?
If in AsObservable pass dictionary type it does not work, if pass string type I receive "key1":x, "key2":"y", "key3":"z" separately.
Thanks.
I have a collection that has Mixed objects. All objects are unique keys, but the data in that object is different. Some contain just a String:
-KWk_LncstV5y8afZwix: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQE..."
And Some contain 2 strings.
-KWklE2NYsw7QqhQl1yf:
Id: "-KWkkJb67cDMZFOGMluK"
sig: "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQE..."
When querying this data I get "An exception of type 'Firebase.Database.FirebaseException' occurred in mscorlib.dll but was not handled in user code". I've tried several things to attempt to cast this, but every time I get the same error. I'm assuming my data isn't what the parser is expecting.
to solve the 2 types in one collection, I capture the error in a try/catch, and if fail, trying secondary type.
Running this example works like a charm.
var client = new FirebaseClient(
"https://yourfirebase.firebaseio.com/",
new FirebaseOptions
{
OfflineDatabaseFactory = (t, s) => new OfflineDatabase(t, s),
//AuthTokenAsyncFactory = () => Task.FromResult("<YOUR AUTH IF NEEDED>")
});
var messagesDb = client.Child("offlinemessages").AsRealtimeDatabase<Message>();
var authorsDb = client.Child("offlineauthors").AsRealtimeDatabase<Author>();
However, if I now want to see these messages, I add the following line:
var messageList= messagesDb.AsObservable().AsObservableCollection();
This also works without any problem. When I now change the following line from above to:
var messagesDb = client.Child("WHATEVER").AsRealtimeDatabase<Message>();
And I check again for the messageList, it still shows me the messages from the "offlinemessage" child. How comes? I'm new the firebase so I'm sorry if I do not get the easy things.
Is the offline database linked to the message type and the ressourceName just for future online syncs?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.