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

Getting started with MvvmCross in less than 10 minutes

Mvvmcross has gained popularity very rapidly its became as most widely used package for the cross platform apps and with v4.0 they have made it more robust and easily accessible.Though Stuart lodge has given N+1 days of mvvmcross and are to be considered the best to begin with. so,I thought my implementation to get started with mvvmcross and to know about basics of mvvmcross. Let’s Go:

To begin with mvvmcross I’m going to create  a blank android project . Once you are done with add a PCL inside solution and name it whatever you want  and the reference of the PCL project into the native project as in the screenshot .

referencedPro_001

Now install the mvvmcross package from the nuget. Once you install the mvvmcross plugin from the nuget it will automatically add a Setup file in your native application, and if not you can manually create that file:

 


public class Setup : MvxAndroidSetup
{
public Setup(Context applicationContext)
: base(applicationContext)
{
}

protected override IMvxApplication CreateApp()
{
return new App();

}

}

Make sure here “App” is a  class file in the Core Project which is  a application object and handles the lifecycle of the ViewModels during naviagtion.This set up class works as the bootstrapper for the cross plugin.

Now lets move to the core project which we have created and Add  “App.cs” file in the core project:


public class App : MvxApplication
{
public App()
{
Mvx.RegisterSingleton<IMvxAppStart>(new MvxAppStart<FirstViewModel>());
}

}

Here First ViewModel is the firstview from where you want to start the app and make sure that not be confused with the Splash Activity.

Now what  I’m going to do is that I”ll be taking the current date and time and bind it to the textView  in . Lets create a folder named as “ViewModel” inside which we’ll place our “FirstViewModel” which will get the current date and time and bind the variable to layout.

FirstViewModel

 


/// <summary>
/// Gets the system's current time and date.
/// </summary>
public class FirstViewModel :MvxViewModel
{
private string _time;
public string Time
{
get
{
return _time;
}
set
{
_time = value;
RaisePropertyChanged(()=>Time);
}
}

public FirstViewModel()
{
GetTimeData();
}

private void GetTimeData()
{
DateTimeOffset t = DateTime.Now;
_time = t.ToString("yyy - MM - dd HH: mm:ss");
}

}

Now in the layout just create a simple layout and containing textView like this:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/showTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
//BINDED THE PROPERTY
local:MvxBind="Text Time"/>
</LinearLayout>

Now , we’ll create the Activity for the layout and for that create a folder named as Views –>FirstView.cs


[Activity(Label = "Sample", MainLauncher = true)]
public class FirstView : MvxActivity
{

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.FirstView);

}

}

Now here is the catch Mvvmcross supports naming conventions to associate the Views with the ViewModel. For example in our case we have named our View as “FirstView”, mvvmcross with locate the viewmodel as long as it is named as “FirstViewModel”. This is simply for one reason the base class that mvvmcross uses have MvxViewModel properties named ViewModel.

However if you want to link the View with ViewModel that have different name then you have to define the the ViewModel property of a View explicitly like this:

Inside the layout’s class file, just add following lines and mvvcross will get the viewmodel for that view:


public new FirstViewModel ViewModel
{
get { return (FirstViewModel)base.ViewModel; }
set { base.ViewModel = value; }
}

 

Thats all !! Run and you’re up with your first mvvcross application in less than 10 minutes.

 

Must have packages for easing the Xamarin Development

  1. Today cross platform apps is major go-go in tech industry as it comply with  the Resources and to publish your apps with attractive features within the consumers.Being a Xamarin dev , I came across multiple packages which can be very easy and will fast paced  the development cycle as well.I thought  to share those packages with you well.
    1. SPLAT

    I like this library very much. Paul  Betts has done all the work for you. This is one the most recommended plugin. ToNative() and FromNative() methods to convert image, colors  and what not. It also provide the automated method which saves the image while saving it with compression ratio. As of now splat supports various features such as cross platform image loading, colors for PCL,geometry primitives, logging framework as well. You can also undergo Paul’s blog to know how to use it.Below are nuget and github link for the details:

    Github : https://github.com/paulcbetts/splat

    Nuget: https://www.nuget.org/packages/Splat/

     

    1. MonoHttpClient

    Again many thanks to Paul Betts who has created this plugin. Basically modernhttpclient converts breaks into the platform specific library i.e NSURLSession on iOS and OkHttp on Android. Trust me it is much faster and I used it in almost every Xamarin app I have created. Also, it’s pretty easy to use it you just have to download and it call the NativeMessageHandler () inside the httpclient that’s it. You are up and running. Isn’t it perfect!!

    GitHub: https://github.com/paulcbetts/ModernHttpClient

    Nuget: https://www.nuget.org/packages/modernhttpclient/

     

    1. MVVMCross

    However with the Xamarin. Forms I use MVVM only but in the Xamarin. IOS and Xamarin. Android it’s good to use MVVMCross and with the latest version (4.0) it’s pretty easy to use and is pretty much stable overcoming some the previous issues. All thanks to Stuart and cheese baron. It provide you the extensiveness of MVVM pattern and ease to use it you can directly do the bindings on the axml file on android and on view controllers in iOS. MVVMCross has its own documentation which is full of samples and certainly a stop to know about it work.

     

    GitHub: https://github.com/MvvmCross/MvvmCross

    Nuget: https://www.nuget.org/packages/MvvmCross/

    Documentation: https://mvvmcross.com/docs

     

    1. SQLite.Net

    This is one of the most widely used plugin in the mobile world and is used to store small piece of data.Its basically a thin wrapper over SQLite and is fast and efficient.It also has very simple methods for CRUD operations.

     

    GitHub: https://github.com/praeclarum/sqlite-net

    Nuget: https://www.nuget.org/packages/sqlite-net/

     

    1. ReactiveUI

    ReactiveUI  is heavily inspired by the functional reactive programming and is based on MVVM framework. The ease with ReactiveUI is that it provides the flexibility unlike MVVMCross which enables set the follow the predefined pattern. That’s what I feel while using both the plugins. I must say that before integrating into your mobile app I would rather ask to see the video series for the same and consult the reactive doc (however site is Work in progress in some of the sections.)

     

    GitHib: https://github.com/reactiveui/ReactiveUI

    Nuget: https://www.nuget.org/packages/reactiveui/

     

    1. ReactiveExtensions

    Reactive UI is built around reactive extensions. Rx extensively uses lambdas  which are pretty easy to grasp  even if you are not a .NET guy. However , it has a lot more apart and again I urge to go thru the Paul Betts documentation and evolve videos to get the better understanding of the Rx. Before that I rather suggest to go thru the below link if you are considering Reactive UI for your mobile project. This link gives you a basic understanding of how Rx works:

     

    https://blog.xamarin.com/why-every-mobile-developer-should-use-reactive-programming/

     

    1. Akavache

    Now a days  mobile dev like me are more inclined towards the akavache which is built on the top of SQLite and gives the leverage to store the data into key value pairs , not only this it also stores the local data which expires. Its major ease in to make UI responsive and is oftenly used for applications which takes consideration of caching.It unifies the caching of different object types i.e HTTP responses, JSON Objects, images too.

     

    GitHub: https://github.com/akavache/Akavache

    Nuget: https://www.nuget.org/packages/akavache/

     

    1. Fody

    If you are planning to use all these packages then Fody will certainly going to help you. Fody eliminates the plumbing  code through an extensible add-in model. Also you can you the add-in with Fody to inject the INotifyPropertyChanged .For more details about Fody I’ll suggest to visit the github which has details and the implementations as well.
    GitHub: https://github.com/Fody/Fody

    Nuget: https://www.nuget.org/packages/Fody/1.29.4