Home » Uncategorized » Kinvey integration with Xamarin

Kinvey integration with Xamarin

Now a days mbaas is becoming quite popular. Backend as a service, basically, it’s a cloud computing category that’s comprised of companies that make it easier for developers to set up, use and operate a cloud backend for their mobile, tablet and web apps. You can either look up the kinvey website to dig deeper into the details on mbaas.

To use kinvey sdk  into the xamarin application , we first need to install the kinvey sdk which you can easily download from the Xamarin component from the store.

Meanwhile lets set up the kinvey  account for ourselves which we’ll be using in our example.

  • Go to console.kinvey.com and sign up yourselves.
  • Once you sign up yourself you’ll be taken to home screen of kinvey which comprises of 3 tabs namely My Apps,New app, My Profile.
  • Tap on the New App , name it and you just created the structure for your app.
  • Once you create the app it will reflect in your My apps tab.

Now we are going to do two things in our sample.

  • Will login with the user which we create at the kinvey’s end.
  • Will pull out the collection from kinvey.

So, Kinvey is quite handy for maintaining your users, your data , kinvey has its own user management system which is quite useful and easy to use I must say this.

Since we have create a new app, now its time to set up Users :

  1. Click on the newly created App -> Click on Development
  2. You’ll be taken to the dashboard which is the center for all your fun activities.

s1

Just to add, your app Id and app secret are very important and these two will be needed when you set up the kinvey client and sometime in unauthenticated api calls.

For quickly setting up user, please refer the video depicting the process to add the user:

Unable to display content. Adobe Flash is required.

Now we know how to add users into the  Kinvey User table.

Since we are up and running we’ll do the quick demo by logging this user and check the whether the implementation is correct or not.

Going back quickly check whether kinvey SDK is successfully installed or not under your components in VS.

Now we create a simple login  page:

  • Go to Main.axml and paste the below code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#87CEFA">
 <LinearLayout
 android:id="@+id/llayout"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_gravity="center">

<android.support.design.widget.TextInputLayout
 android:id="@+id/editInputLayout"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_margin="10dp">
 <EditText
 android:id="@+id/email"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="Email" />
 </android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
 android:id="@+id/passwordInputLayout"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"

 android:layout_margin="10dp">
 <EditText
 android:id="@+id/password"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:hint="Password" />
 </android.support.design.widget.TextInputLayout>

<Button
 android:id="@+id/btn1"
 android:layout_width="60dp"
 android:layout_height="40dp"
 android:layout_marginLeft="40dp"
 android:layout_marginRight="40dp"
 android:textAllCaps="false"
 android:textColor="#ffffff"
 android:background="#3232FF"
 android:gravity="center"
 android:text="login" />
 </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

Now it’s the time to intialize the client for kinvey Sdk through which we’ll be doing the talking most of the time. So for just to see the functioning of kinvey client you can create client inside OnCreate() function but I’m going to create a separate class for creation of client so that it can be reusable.

Create a class ClientHandler and add the below mentioned code:


public class ClientHandler
 {
 private static Client kinveyClient;
 public static Client GetClient()
 {
 if(kinveyClient == null)
 {

#region Without Offline database
 kinveyClient = new Client.Builder(your_app_key, you_app_secret)
 .setLogger(delegate (string message) { Console.WriteLine(message); })
 .build();
 #endregion
 }

return kinveyClient;
 }

}

Now go back to your MainActivity.cs and add below code to do the login:


public class MainActivity : Activity
 {
 private EditText _email, _password;
 private Button _btn;
 //private static Client kinveyClient;
 private Context _context;
 protected override void OnCreate(Bundle bundle)
 {
 base.OnCreate(bundle);

// Set our view from the "main" layout resource
 SetContentView (Resource.Layout.Main);
 _email = FindViewById<EditText>(Resource.Id.email);
 _password = FindViewById<EditText>(Resource.Id.password);
 _btn = FindViewById<Button>(Resource.Id.btn1);

_btn.Click += _btn_Click;
 }

 private async void _btn_Click(object sender, System.EventArgs e)
 {
 _context = this;
 //Something
 if(_email.Text !=null && _password.Text != null)
 {

ClientHandler.GetClient().User().Login(_email.Text, _password.Text,new KinveyDelegate<User>
 {
 onSuccess = (user) =>
 {
 StartActivity(typeof(DashBoardActivity));
 },
 onError = (error) =>
 {
 RunOnUiThread(() =>
 {
 AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
 builder1.SetMessage(error.Message);
 builder1.SetCancelable(true);

AlertDialog alert1 = builder1.Create();
 alert1.Show();

});

 }

 });

 }else
 {
 AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
 builder1.SetMessage("Inavlid email or password");
 builder1.SetCancelable(true);

AlertDialog alert1 = builder1.Create();
 alert1.Show();
 }
 }

Another Note: Kinvey also provides built in methods to validate emails so you can use them to validate the email.

One important point to note down here is Kinvey also provide caching at the server end but you can also set up your client to use your database for caching purposes and you can set up the kinvey client with db for that you just have modify the kinvey client like this:


kinveyClient = new Client.Builder(your_app_key, your_app_secret)
.setLogger(delegate (string message) { Console.WriteLine(message); })
&nbsp;.setFilePath(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal))
&nbsp;.setOfflinePlatform(new SQLitePlatformAndroid())
&nbsp;.build();

Imp Note: Kinvey requests are by default asynchronous in nature and you can show loader, gif w.r.t to them or you can use the async await wherever necessary.

With the above code till now if user is valid user will be taken to DashBoard activity and if not then its shows the error.

Whoa!!! You just interacted with the Kinvey , Isnt it cool with juts few lines you are able to login into the app.

Since we are logged in successfully and user is navigated to blank screen now we add the collection in kinvey and fetch that list into out dashboard activity.

For that we need to add the collection into the kinvey so we head back to console.Kinvey.com and a collection which we will be fetching on our dashboard after successful login

1) Login to console.kinvey.com  . In the dashboard on the right side you are able to see the collection which appears to be empty.

2) Just click on the create collection  create collection and select data source as Kinvey Data Store.

3) add  two columns namely name and location.

4)Now add as many rows as you want

5) Make sure _id, _acl and _kmd are the default parameters  of which _id is more important asThe Kinvey REST API automatically checks whether the _id field of an incoming request is an ObjectID

Here is quick video for creating collections in kinvey :

Unable to display content. Adobe Flash is required.

Once you are done creating the collection you can see that its now appearing on the dashboard as shared one.

Now let’s go back to our code base and create a new activity named as DashBoard activity:

[Activity(Label ="Dashboard")]
public class DashBoardActivity : Activity
{
private TextView _t1;
private RecyclerView _recyclerView;
private List<PersonEntity> _CollList;
private PersonEntity[] popo;

protected async override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.dashboard);
_t1 = FindViewById<TextView>(Resource.Id.t1);
_recyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
_t1.Text = "Welcome Utk!!";

AsyncAppData<PersonEntity> col = ClientHandler.GetClient().AppData<PersonEntity>("hopper",typeof(PersonEntity));
popo = await col.GetAsync();
List<PersonEntity> lol = popo.ToList<PersonEntity>();

HopperAdapter hopAdapter = new HopperAdapter(this,lol);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
_recyclerView.SetLayoutManager(linearLayoutManager);
_recyclerView.SetAdapter(hopAdapter);
}
}

You can add the recycler adapter class and item.axml for decorating your recylerview as per your need.

So, all set just execute it and see your self .. MBAAS With Xamarin 😉

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s