step-up-labs / firebase-database-dotnet

C# library for Firebase Realtime Database.
MIT License
669 stars 168 forks source link

Sending data to specific key with PostAsync #57

Closed Bart-Holland closed 7 years ago

Bart-Holland commented 7 years ago

In a project I am working on I am trying to send data to a specific key in firebase database.

The key is in this structure: users/userid/locations/location/lastWarning

This lastWarning only accepts a string. Using PostAsync I am trying to send a string "test". However doing this results in a 'permission denied'

The code I am using is this:


public string SetFirebaseData(string fbRef, double? messageLevel)
        {
            string Token = FirebaseLogin();
            string firebaseDFatabaseURL = ConfigurationManager.AppSettings["FireBaseDatabaseURL"];
            FirebaseOptions options = new FirebaseOptions();
            options.AuthTokenAsyncFactory = () => Task.FromResult(Token);          

            string data = messageLevel.ToString();

            var firebase = new FirebaseClient(firebaseDFatabaseURL, options);
            FirebaseObject<string> result = firebase.Child(fbRef).PostAsync(data, false).Result; 

            return result.ToString();
        }

where fbRef = "users/PsIIwpnhCxMhSN5IN5UFJD5wxAw1/locations/KATV/lastWarning" and messageLevel = 0

Since this results in a 401 permission denied I tried to send data to the location without lastWarning in it. using this fbRef = ""users/PsIIwpnhCxMhSN5IN5UFJD5wxAw1/locations/KATV/"" and messageLevel = 0

Now the data: 0 will be placed in firebase database, but the Key will not be 'lastWarning', it will be a generated key. Something like: "-Ki9mqNi5bpubh_C0MKG"

So how do I do this? How will get this to work?

bezysoftware commented 7 years ago

You can use PutAsync

Bart-Holland commented 7 years ago

Ah yes thanks I struggled with that one as well. Think I've got it now:

public async Task SetFirebaseData(string fbRef, double? messageLevel)
        {
            string Token = FirebaseLogin();
            string firebaseDFatabaseURL = ConfigurationManager.AppSettings["FireBaseDatabaseURL"];
            FirebaseOptions options = new FirebaseOptions();
            options.AuthTokenAsyncFactory = () => Task.FromResult(Token);          

            string data = messageLevel.ToString();
            FBLocationPut fbLocation = new FBLocationPut();
            fbLocation.lastWarning = data;

            var firebase = new FirebaseClient(firebaseDFatabaseURL, options);
            await firebase.Child(fbRef + "lastWarning/").PutAsync(fbLocation.lastWarning);

        }

Now I need to figure out if it worked or not ;)