In the last posts, we have set up everything needed to connect to Firebase in C#. Let's finally connect.
Open up HeroConn.cs and start coding. I'll paste the code here first and then talk through what is happening: using System; using System.Threading.Tasks; using Firebase.Database;
namespace FirebaseHeroes.Data { public class HeroConn { private const String databaseUrl = "https://tour-of-heroes-xxx.firebaseio.com/"; private const String databaseSecret = "your-unique-database-secret"; private const String node = "heroes/";
private FirebaseClient firebase;
public HeroConn() { this.firebase = new FirebaseClient( databaseUrl, new FirebaseOptions { AuthTokenAsyncFactory = () => Task.FromResult(databaseSecret) }); }
public async Task Insert(Hero hero) { await firebase.Child(node).PostAsync<Hero>(hero); } } } First I created a String 'node'. This represents the hero part of the database, accessed through the databaseUrl + 'heroes/'. As this class is specifically dealing with Hero objects, this is set as a constant. I then created a variable 'firebase' of type FirebaseClient which is the actual connection to Firebase. This variable is initialised in the constructor by passing both the databaseUrl and the databaseSecret key to the FirebaseClient constructor. This piece of code could actually be broken out into its own class and reused for other Firebase objects and database operations. The Insert() method deals with, you guessed it, inserting a Hero object into the Firebase database. This method is async as the FirebaseClient method is PostAsync. Note how the method also takes in the 'node' variable to access the heroes section of the database and the actual Hero object (hero) which will be added to the database. It really is that easy!
Connecting the Interface
With the connection and Insert() method created, I'm going to go back to the btnAdd_Tapped() method in MainPage.xaml.cs
This method needs to be altered to call the Insert() method from HeroConn. Again, this is not hard to do. Remembering that the Insert method has a Hero object as a parameter, a Hero object will first be created from the form data and then passed to the Insert method. I am not going to perform any validation of the text fields in the UI as this is out of scope for these posts. Note: As the rating field is an int, an exception will be thrown if anything else is entered in to the Rating text box and the button is clicked. Here is the finished MainPage.xaml.cs code: namespace FirebaseHeroes { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); }
private async void btnAdd_Tapped(object sender, TappedRoutedEventArgs e) { HeroConn heroConn = new HeroConn(); Hero hero = new Hero { Name = this.tbInputName.Text, Rating = Convert.ToInt32(this.tbInputRating.Text) }; await heroConn.Insert(hero);
this.tbOutput.Text = String.Format("Hero {0} added!", hero.Name); } } }
Note that the btnAdd_Tapped handler method has also been marked async since the HeroConn Insert() method is async.
The Convert.ToInt32 method may throw and exception as I stated above. After the insert has completed, a message will be displayed in the tbOutput TextBlock.
Run and Test
The application should now have the ability to insert data into the Firebase database so let's test and see.
First of all, open up the Firebase console for the tour-of-heroes project - it will be something like https://tour-of-heroes-xxxxx.firebaseio.com/heroes and you will need to be logged in to your Google account of course. Now run the application and keep the Firebase console window open alongside. Try to add a Hero by entering some text in the Name field and a number in the Rating field and clicking the Add button. You should see the record being created in the Firebase console with the same data you just entered, success! Note the Key value that Firebase automatically added to the record. This is the unique identifier for that record in the database and can be used in future to get that specific record from the database - much like a primary key in a standard RDMS. The image below shows this.
If you view these windows at the same time, you will see how quickly the data is added to Firebase. You will also notice that Firebase has colour coded highlighting for a record when an operation is being performed on it: Green for Insert, Orange for Update and Red for Delete - more on these in a later post!
2 Comments
Sabahat
2/15/2018 05:56:43 am
What is this 'databaseSecret ' which you use during Insertion .
Reply
Jose
4/21/2018 05:31:35 pm
await firebase.Child(node).PostAsync<Hero>(hero);
Reply
Leave a Reply. |
Author
2nd Year B.Sc. Software Development Archives
December 2017
Categories |