How to get the new key pushed on firebase? - firebase-realtime-database

Dears,
I don't know how to get he new key pushed in firebase.
This is my simple example code:
FirebaseDatabase.instance.reference().child('mychild').push().set(
<String, String>{
'hello': 'world',
});
How can I get the key of this element pushed?
Thanks

You can try this :
DatabaseReference rootRef = FirebaseDatabase.instance.reference();
String newkey = rootRef.child('mychild').push().key;
rootRef.child('mychild').child(newKey).set(<String, String>{'hello': 'world',});

Related

Stop Firebase from adding index number of ObservableCollection

Does anyone know how I can stop Real Time Firebase from adding the index of an observable collection as a title? All code is listed below along with how the data is shown in Firebase.
How data is presented in Firebase:
Index 0 is added to the DB as title '0'
//Await task that post the code to firebase
public static async Task AddExercise(ObservableCollection<Exercise> exercisepassed)
{
await Client.Child("exercises").PostAsync(exercisepassed);
}
Code that get sent to await task :
addexercise1.Add(new Exercise
{
id = uniqeexid,
title = title,
UserId = uid,
DurationMinutes = durationMinutes,
StartDate = startdate,
NotificationIds = notificationIds,
Time = time,
VideoId = videoId,
Often = often,
exerciseid = exid });
await DbFirebase.AddExercise(addexercise1);
If you want to get rid of the -N7... type keys, call PutAsync instead of PostAsync.
If you want to get rid of the 0, then don't post a ObservableCollection<Exercise>, but instead post a single Exercise object.

How to use SODA.net and App Token in asp.net-core MVC

As per Socradata.com suggest, I have created both and an Application Token and an Application Key.
When I query using a Soda.net Click using the App Token and username and password like this:
var client = new SodaClient(sodaHost, sodaAppToken, user, pwd);
var soql = new SoqlQuery().Select("draw_date", "winning_numbers", "mega_ball", "multiplier").Where("draw_date > '2018-01-01'").Order(SoqlOrderDirection.DESC, "draw_date");
var dataset = client.GetResource<MyClass>(soda4x4);
var results = dataset.Query<MyClass>(soql);
Or when query using the App Token and App Key like this:
var client = new SodaClient(sodaHost, sodaAppToken, keyId, keySecret);
var soql = new SoqlQuery().Select("draw_date", "winning_numbers", "mega_ball", "multiplier").Where("draw_date > '2018-01-01'").Order(SoqlOrderDirection.DESC, "draw_date");
var dataset = client.GetResource<MyClass>(soda4x4);
var results = dataset.Query<MyClass>(soql);
I get the following error:
System.ArgumentOutOfRangeException
HResult=0x80131502
Message=The provided resourceId is not a valid Socrata (4x4) resource identifier.
Parameter name: resourceId
Source=SODA
StackTrace:
at SODA.SodaClient.Query[TRow](SoqlQuery soqlQuery, String resourceId)
at SODA.Resource1.Query[T](SoqlQuery soqlQuery)
at NumPicker.Controllers.HomeController.MegaMillions() in C:\Users\ka8kgj\Desktop\NumPicker\NumPicker\Controllers\HomeController.cs:line 45
at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
However, when I query anonymously with this client. No error. All is well.
var client = new SodaClient(sodaHost);
var soql = new SoqlQuery().Select("draw_date", "winning_numbers", "mega_ball", "multiplier").Where("draw_date > '2018-01-01'").Order(SoqlOrderDirection.DESC, "draw_date");
var dataset = client.GetResource<MyClass>(soda4x4);
var results = dataset.Query<MyClass>(soql);
Obviously I can not see an issue with the code. Can someone point out what I am missing?
Ok, Here is the answer. It is most embarrassing but I will take the humiliation so that others may not have too..
When you create the app-token on the SOCRATA web site. You get a Key / Secrete pair.
When passing the app-token, It is the KEY that should be passed. NOT THE SECRETE !

how to add or remove item to the the existing array in firestore ?

Firestore has recently add the new new method FieldValue.arrayUnion(value) and FieldValue.arrayRemove(value) but i couldn't find the implementation in flutter cloud_firestore package. Is there any way to achieve this result ?
Firestore addUpdate: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
Here is the simple example to show how to update the array values. My document have an up voters array to add the user id's who have up-votes the document.
configure firestore, the config details can be copied form your google-services.json file
final FirebaseApp app = await FirebaseApp.configure(
name: 'test',
options: const FirebaseOptions(
projectID: 'projid',
googleAppID: 'appid',
apiKey: 'api',
databaseURL: 'your url',
),
);
final Firestore firestore = Firestore(app: app);
await firestore.settings(timestampsInSnapshotsEnabled: true);
update code using transaction
fireStore.runTransaction((Transaction tx) async {
DocumentSnapshot snapshot =
await tx.get(widget._document.reference);
var doc = snapshot.data;
if (doc['upvoters'].contains('12345')) {
await tx.update(snapshot.reference, <String, dynamic>{
'upvoters': FieldValue.arrayRemove(['12345'])
});
} else {
await tx.update(snapshot.reference, <String, dynamic>{
'upvoters': FieldValue.arrayUnion(['12345'])
});
}
});
Hope it helps
Update:
And now it seems that it is supported! With the version 0.8.0.
https://pub.dartlang.org/packages/cloud_firestore
And then use FieldValue.arrayUnion and FieldVale.arrayRemove.
There doesn't seems to be a way currently. Please follow the following two github issues:
https://github.com/flutter/flutter/issues/21148
https://github.com/flutter/flutter/issues/20688

Twitterizer Problems

I am trying to figure out if twitterizer is still relevant. The library looks really old. And the current project i am working on uses it. I am using the following code...
private static OAuthTokens OAuthTokens()
{
var accessToken = "<insert>";
var accessTokenSecret = "<insert>";
var consumerKey = "<insert>";
var consumerSecret = "<insert>";
return new OAuthTokens
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
AccessToken = accessToken,
AccessTokenSecret = accessTokenSecret
};
}
if i do the following call
var responseFollowersIds = TwitterFriendship.FollowersIds(credentials, new UsersIdsOptions()
{
UseSSL = true,
APIBaseAddress = "http://api.twitter.com/1.1/",
ScreenName = screenName
});
I can see that i have followers and that the request being made looks like this
https://api.twitter.com/1.1/followers/ids.json?screen_name=screenname&cursor=-1
notice that i set the APIBaseAddress to the latest version, but if i try and get the followers i use the following
var responseFollowers = TwitterFriendship.Followers(credentials, new FollowersOptions
{
ScreenName = screenName,
UseSSL = true,
APIBaseAddress = "http://api.twitter.com/1.1/",
});
But then i get an error
{"errors":[{"message":"Sorry, that page does not exist","code":34}]}
upon further investigation i realized that TwitterFriendship.Followers request url is wrong and that is buried deep in the twitterizer code.
The request made is
https://api.twitter.com/1.1/statuses/followers.json?cursor=-1&screen_name=screenname
and should be
https://api.twitter.com/1.1/followers/list.json
according to the new twitter documentation.
Is there an easy way to fix it?
A little bit late, but just in case anyone faces this problem again. You can easily fix it by modifiying the code of Twitterizer at \Methods\User\FollowersCommand.cs, look for the constructor and change the URL of the method:
public FollowersCommand(OAuthTokens tokens, FollowersOptions options)
: base(HTTPVerb.GET, "followers/list.json", tokens, options)

Angularfire2 get a key of added object

Am I able to get a key of just added object?
For example:
items.push(
{ ... }
).then(_ => console.log(key of the object));
items.push(
{ ... }
).then(_ => console.log('Added item key is ', _.key));
Please try like this.
If you mean Firebase 3 (AngularFire's $firebaseArray has a $add to replace push) then it returns a reference that is also a "thenable", checkout the Firebase docs
So you can get the key of the reference even synchronously:
var thenableRef = dataRef.push({someKey: 'some value'});
var newItemKey = thenableRef.$key;
thenableRef.then(_ => console.log('There\'s my new key: %s', newItemKey));

Resources