Przejdź do głównej zawartości

How to call webAPI service in Xamarin?

In the last few weeks I worked on the web service written in ASP.NET Core. I had a plan to connect the Xamarin application to this web service.
Today I'll show you how you can connect your Xamarin app to web service located anywhere in the cloud.

First we need to have a web service deployed, which is our server-side part of the system. I describe how to create a web service in ASP.NET COre in my previous post: .

Today I'll demonstrate how it works from client perspective, in our case it's Xamarin.Forms application but web application or desktop application can use exactly the same code. This is the great benefit of using C# language - we can use the same code on multiple platforms.

OK, I bet you're interested in the code. Let's jump to the code.

This is the final version of the client class that I can use to save and retrieve data from web service:


The class design is straightforward. It has 2 public methods which encapsulate 2 functionalities: adding single record to the cloud based web service, and retrieving list of records for a specified user identifier. Note how I use HttpClient class. I put it in using statement which automatically dispose all resources related to the HttpClient class when my work is done.
Note that developers that use AddRecord method anywhere in the project code doesn't have to know the web service URL, It's encapsulated in the method. Also the developer doesn't need to know that http method POST was used to sent data to the server. His job is limitted to call: client.AddRecord(record). That's it. By good design we can limit the ammount of time that client developer needs to spend to understand how our API works in the background. We save his time. The same benefits you can see in case of GetRecords(string userName) method. We hide all technical details in this method including deserialization which happens in this line:
var deserialized = JsonConvert.DeserializeObject>(jsonObject.ToString());
Note that all communication between our Xamarin app and ASP.NET Core service goes through JSON format, which is just string.
Deserialization enables us to convert json string to list of C# objects. You just need to instal Newtonsoft.Json Nuget package ant then add 2 using statements in your class:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

This are external packages used in my project which I can display in Visual Studio 2017:

If you're missing NewtonSoft package - you have to install it.

Let's switch to client developer perspective and see how we can use the cliend class in action.

This is how we can add new weight record to the cloud service:

Doing save is easy as 1,2,3:
var client = new PerfectLifeWebServiceClient();
await client.AddRecord(new WeightRecord(userName:App.User.Email, weight:weight));
We create a new instance of our client and just call AddRecord Method with proper data: usuername and weight.

And this is how we can get all records saved so far:


Having the client class which is now the API that we use, look how easily we can get a list of records from web service. 3 lines of code do the job:
var client = new PerfectLifeWebServiceClient();
var result = client.GetRecords(App.User.Email).Result;
_records = result.Select(r => new DataPoint { Date = r.DateTime.Date.ToString("dd-MM-yyyy"), Weight = r.Weight });

We can format DateTime(this .NET type contains the date segment and time segment).
We are interested only in date part, and we want to get rid of the time part:
r.DateTime.Date.ToString("dd-MM-yyyy")
We use ToString method which accepts string as format od data. As the result we get only date, skipping hour and minute part.

What about the final result from user perspective? Of cours I managed to deliver new value and the new application is available in Google Play store:
https://play.google.com/store/apps/details?id=com.kacban.perfectlife
And these are the screenshots that I took from android emulator.

The new screen where you can select you current weight:


The statistics screen where you can see your progress:


And also the bonus feature - menu which lets you switch between weight view and statistics view:


Thanks for reading.
Please leave a comment bellow to let me know how you like my application.









Komentarze

Popularne posty z tego bloga

Aplikacja 'Perfect Life' - planowanie funkcjonalności

W poprzednim wpisie przedstawiłem budowę historii użytkownika(ang. User Story). Dzisiaj korzystając z tego narzędzia zaplanujemy kilka funkcjonalności. Czas na zaplanowanie funkcjonalności aplikacji mobilnej Perfect Life. Aplikacja jest tworzona w oparciu o technologię Xamarin.Forms. Póki co jednak abstrahując od rozwiązań technologicznych skupimy się na funkcjonalnościach. Dobre planowanie swojej pracy to podstawa sukcesu każdego projektu programistycznego. US1: Jako użytkownik aplikacji mobilnej chcę ekran logowania aby mieć możliwość zapisywania swoich postępów US2: Jako użytkownik aplikacji mobilnej chcę mieć kalkulator wskaźnika BMI aby móc mierzyć poziom swojej kondycji US3: Jako użytkownik aplikacji mobilnej chcę widzieć wykresy aby móc wizualnie interpretować swoje postępy US4: Jako użytkownik aplikacji mobilnej chcę mieć możliwość rozwiązania quizu, żeby zbadać wskaźnik Body Age US5: Jako użytkownik aplikacji mobilnej chcę pobierać pliki PDF aby mieć dostęp do planó...

Dziś Premiera Visual Studio 2017

Dzisiaj ważny dzień dla programistów .NET. Premiera środowiska programistycznego Visual Studio 2017. Relację na żywo można oglądać tutaj: https://launch.visualstudio.com/ Jutro będzie dzień warsztatów, w których możemy wziąć udział online. Nowe VS możemy pobrać ze strony: https://www.visualstudio.com/ Co ciekawe pobierając VS teraz otrzymasz 60 dni darmowego dostępu do Xamarin University. To ważne jeśli chcesz się nauczyć tworzyć aplikacje mobilne. Co nowego? Lepsza integracja z VSTS Live unit testing - zwróćmy uwagę na ikony po lewej stronie: Dodatkowe ikony: Wyszukiwanie metod po fragmencie nazwy. Code suggestions, czyli podpowiedzi na temat najlepszych praktyk w trakcie pisania kodu. Możemy zdefiniować własne sugestie dot. kodu i dodac własne konfiguracje edytora kodu: Dodatkowo pojawiły się dodatkowe ikony, dzięki którym łatwo się zorientować gdzie kończy się klasa, a gdzie namespace. Wygląda to nieźle. Inne usprawnienia o których mówił Scott Hanselman...

ASP.NET Core MVC - wdrożenie na Linuxie krok po kroku

Dzisiaj skupimy się na wdrożeniu aplikacji ASP.NET Core MVC. Po przeczytaniu tego artykułu będziesz potrafił uruchomić swoją pierwszą aplikację ASP.NET Core na maszynie wirtualnej z systemem Ubuntu 14. Załóżmy, że mamy nasza aplikację gotową i chcemy ją uruchomić. Jak najłatwiej to zrobić? Podczas debugowania możemy roboczo wykorzystać Visual Studio do uruchomienia aplikacji na IIS Express. Jednak w warunkach produkcyjnych kiedy chcemy wdrożyć aplikację na systemie Linux, musimy poszukać innego rozwiązania. Dlaczego? Bo Linux nie będzie obsługiwał ani visual Studio ani IIS Express, ponadto jeśli korzystamy z Continuous Deployment, to chcemy wdrożenie robić z poziomu konsoli. Jak pisałem w poprzednich postach, wraz z nadejściem ASP.NET Core MVC, mamy możliwość wdrażania aplikacji napisanych w C# na platformie Linux. To niezwykle istotne, bo przynosi ogromne korzyści, choćby dlatego, że ceny hostingu są kilka razy niższe dla maszyn z Linuxem niż z Windowsem. 1) Framework-depen...