Xamarin.Forms: Consuming Rest Webservice - XML Parsing (C# - Xaml)

Advertisemen

Introduction:
It is a very common scenario to consuming web-service from the mobile app and from the server you will get XML/JSON response. This article demonstrates how to consume a RESTful web service and how to parse the XML response from a Xamarin.Forms application.
Note: If you are looking for JSON parsing sample, please visit my another article from here.




Requirements:
  • This article source code is prepared by using Visual Studio 2017 Enterprise. And it is better to install latest visual studio updates from here.
  • This article is prepared on a Windows 10 machine.
  • This sample project is Xamarin.Forms PCL project.
  • This sample app is targeted for Android, iOS & Windows 10 UWP. And tested for Android & UWP only. Hope this sample source code would work for iOS as well.
Description:
This article can explain you below topics:
1. How to create Xamarin.Forms PCL project with Visual studio 2017?
2. How to check network status from Xamarin.Forms app?
3. How to consuming webservice from Xamarin.Forms?
4. How to parse XML string?
5. How to bind XML response to ListView?
Let's learn how to use Visual Studio 2017 to create Xamarin.Forms project.

1. How to create Xamarin.Forms PCL project with Visual studio 2017?
Before to consume webservice, first we need to create the new project. 
  • Launch Visual Studio 2017/2015.
  • On the File menu, select New > Project.
  • The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display. In the left pane, expand Installed > Templates > Visual C# > Cross-Platform. The dialog's center pane displays a list of project templates for Xamarin cross platform apps.
  • In the center pane, select the Cross Platform App (Xamarin.Forms or Native) template. In the Name text box, type "RestDemo". Click OK to create the project.
  • And in next dialog, select Blank App=>Xamarin.Forms=>PCL.The selected App template creates a minimal mobile app that compiles and runs but contains no user interface controls or data. You add controls to the app over the course of this tutorial.
  • Next dialog will ask for you to confirm that your UWP app support min & target versions. For this sample, I target the app with minimum version 10.0.10240 like below:
2. How to check network status from Xamarin.Forms app?
Before call webservice, first we need to check internet connectivity of a device, which can be either mobile data or Wi-Fi. In Xamarin.Forms, we are creating cross platform apps, so the different platforms have different implementations. 
So to check the internet connection in Xamarin.Forms app, we need to follow the steps given below.
Step 1:
Go to solution explorer and right click on your solution=>Manage NuGet Packages for solution.

Now search for Xam.Plugin.Connectivity NuGet package. On the right side, make sure select all platform projects and install it.


Step 2:
In Android platform, you have to allow the user permission to check internet connectivity. For this, use the steps given below.
Right click on RestDemo.Android Project and select Properties => Android Manifest option. Select ACCESS_NETWORK_STATE and INTERNET permission under Required permissions.



Step 3:
Create a class name "NetworkCheck.cs", and here I placed it in the Model folder. After creating class, add below method to find network status.
  1. namespace RestDemo.Model  
  2. {  
  3.     public class NetworkCheck  
  4.     {  
  5.         public static bool IsInternet()  
  6.         {  
  7.             if (CrossConnectivity.Current.IsConnected)  
  8.             {  
  9.                 return true;  
  10.             }  
  11.             else  
  12.             {  
  13.                 // write your code if there is no Internet available    
  14.                 return false;  
  15.             }  
  16.         }  
  17.     }  
  18. }  
3. How to consuming webservice from Xamarin.Forms?
We can consume webservice in Xamarin using HttpClient. But it is not directly available, and so we need to add "Microsoft.Net.Http" from Nuget.


Step 1: Go to solution explorer and right click on your solution=>Manage NuGet Packages for a solution => search for Microsoft.Net.Http NuGet Package=>on the right side, make sure select all platform projects and install it.



Note: To add "Microsoft.Net.Http", you must install "Microsoft.Bcl.Build" from Nuget. Otherwise, you will get an error like "Could not install package 'Microsoft.Bcl.Build 1.0.14'. You are trying to install this package into a project that targets 'Xamarin.iOS,Version=v1.0', but the package does not contain any assembly references or content files that are compatible with that framework."

Step 2:
Now it is time to use HttpClient for consuming webservice and before that we need to check the network connection. Please note that In below code you need to replace your URL, or you can also find the demo webservice url from the source code given below about this article.
  1. public async void GetXml()  
  2.        {  
  3.            //Check network status  
  4.            if (NetworkCheck.IsInternet())  
  5.            {  
  6.   
  7.                Uri geturi = new Uri("REPLACE YOUR URL"); //replace your xml url  
  8.                HttpClient client = new HttpClient();  
  9.                HttpResponseMessage responseGet = await client.GetAsync(geturi);  
  10.                string response = await responseGet.Content.ReadAsStringAsync();//Getting response  
  11.   
  12.            }  
  13.        }  
4. How to parse XML response string in Xamarin.Forms?
Generally, we will get a response from webservice in the form of XML/JSON. And we need to parse them to show them on mobile app UI. Let's assume, in the above code we will get below sample XML response.

  1. <menu>  
  2. <item>  
  3. <id>1</id>  
  4. <name>Margherita</name>  
  5. <cost>155</cost>  
  6. <description>Single cheese topping</description>  
  7. </item>  
  8. </menu>  

So to parse above xml, first we need to create class name(XmlPizzaDetails.cs) with relavent properties(id, name, cost & description) like below.

  1. public class XmlPizzaDetails  
  2.    {  
  3.        public string id { getset; }  
  4.        public string name { getset; }  
  5.        public string cost { getset; }  
  6.        public string description { getset; }  
  7.    }  



And finally, write below code to parse above XML response.

  1. public async void GetXML()  
  2.         {  
  3.            //Check network status  
  4.             if (NetworkCheck.IsInternet())  
  5.             {  
  6.   
  7.                 Uri geturi = new Uri("REPLACE YOUR URL"); //replace your xml url  
  8.                 HttpClient client = new HttpClient();  
  9.                 HttpResponseMessage responseGet = await client.GetAsync(geturi);  
  10.                 string response = await responseGet.Content.ReadAsStringAsync();  
  11.   
  12.                 //Xml Parsing  
  13.                 List<XmlPizzaDetails> ObjPizzaList = new List<XmlPizzaDetails>();  
  14.                 XDocument doc = XDocument.Parse(response);  
  15.                 foreach (var item in doc.Descendants("item"))  
  16.                 {  
  17.                     XmlPizzaDetails ObjPizzaItem = new XmlPizzaDetails();  
  18.                     ObjPizzaItem.id = item.Element("id").Value.ToString();  
  19.                     ObjPizzaItem.name = item.Element("name").Value.ToString();  
  20.                     ObjPizzaItem.cost = item.Element("cost").Value.ToString();  
  21.                     ObjPizzaItem.description = item.Element("description").Value.ToString();  
  22.                     ObjPizzaList.Add(ObjPizzaItem);  
  23.                 }  
  24.                //Binding listview with server response  
  25.                listviewPizza.ItemsSource = ObjPizzaList;  
  26.   
  27.             }  
  28.             else  
  29.             {  
  30.                 await DisplayAlert("XmlParsing","No network is available.","Ok");  
  31.             }  
  32.            //Hide loader after server response  
  33.             ProgressLoader.IsRunning = false;  
  34.         }  

5. How to bind XML response to ListView?

Generally, it is very common scenario is showing a list of items in ListView from the server response.
Let's assume we have below xml response from the server via webservice.

  1. <menu>  
  2. <item>  
  3. <id>1</id>  
  4. <name>Margherita</name>  
  5. <cost>155</cost>  
  6. <description>Single cheese topping</description>  
  7. </item>  
  8. <item>  
  9. <id>2</id>  
  10. <name>Double Cheese Margherita</name>  
  11. <cost>225</cost>  
  12. <description>Loaded with Extra Cheese</description>  
  13. </item>  
  14. <item>  
  15. <id>3</id>  
  16. <name>Fresh Veggie</name>  
  17. <cost>110</cost>  
  18. <description>Oninon and Crisp capsicum</description>  
  19. </item>  
  20. </menu>  

See there is 3 different items in above xml response and if we want to plan for showing them in ListView first we need to add below Xaml code in your ContentPage(XmlParsingPage.xaml).

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              x:Class="RestDemo.XmlParsingPage">  
  5.     <Grid>  
  6.         <Grid>  
  7.             <Grid.RowDefinitions>  
  8.                 <RowDefinition Height="Auto"/>  
  9.                 <RowDefinition Height="*"/>  
  10.             </Grid.RowDefinitions>  
  11.             <Label Grid.Row="0" Margin="10" Text="Xml Parsing" FontSize="25" />  
  12.             <ListView x:Name="listviewPizza" Grid.Row="1" HorizontalOptions="FillAndExpand" HasUnevenRows="True">  
  13.                 <ListView.ItemTemplate>  
  14.                     <DataTemplate>  
  15.                         <ViewCell>  
  16.                             <Grid HorizontalOptions="FillAndExpand" Padding="10">  
  17.                                 <Grid.RowDefinitions>  
  18.                                     <RowDefinition Height="Auto"/>  
  19.                                     <RowDefinition Height="Auto"/>  
  20.                                     <RowDefinition Height="Auto"/>  
  21.                                     <RowDefinition Height="Auto"/>  
  22.                                 </Grid.RowDefinitions>  
  23.                                 <Label Text="{Binding name}" HorizontalOptions="StartAndExpand" Grid.Row="0" TextColor="Blue"  FontAttributes="Bold"/>  
  24.                                 <Label Text="{Binding cost}" HorizontalOptions="StartAndExpand" Grid.Row="1" TextColor="Orange"  FontAttributes="Bold"/>  
  25.                                 <Label Text="{Binding description}" HorizontalOptions="StartAndExpand" Grid.Row="2" TextColor="Gray"  FontAttributes="Bold"/>  
  26.   
  27.                                 <BoxView HeightRequest="2" Margin="0,10,10,0" BackgroundColor="Gray" Grid.Row="3" HorizontalOptions="FillAndExpand" />  
  28.                             </Grid>  
  29.                         </ViewCell>  
  30.   
  31.                     </DataTemplate>  
  32.                 </ListView.ItemTemplate>  
  33.             </ListView>  
  34.         </Grid>  
  35.         <ActivityIndicator x:Name="ProgressLoader" IsRunning="True"/>  
  36.     </Grid>  
  37. </ContentPage>  

See in above code there is a ListView which was binded with relevant properties (name, cost, description) which was mentioned in our class name called XmlPizzaDetails.cs.
Finally, we need to bind our ListView with list like below:(Please find which was already mentioned in the 4th section of GetXML method at 25th line)

  1.   //Binding listview with server response  
  2.                listviewPizza.ItemsSource = ObjPizzaList;  



Demo Screens from Android:



Demo Screens from Windows10 UWP:

You can directly work on below sample source code that is having the functionality of xml parsing. 
 XMLParsingSample
Note: If you are looking for JSON parsing sample, please visit my another article from here.

FeedBack Note: Please share your thoughts, what you think about this post, Is this post really helpful for you? Otherwise, it would be very happy, if you have any thoughts for to implement this requirement in any other way? I always welcome if you drop comments on this post and it would be impressive.

Follow me always at @Subramanyam_B
Have a nice day by  :)

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Tutorial Unity 3D