I have to give props to Trevor Hart on this idea – he sent a message to a dev group I am in that said: “Hello fellow humans, have you ever used Xamarin and thought “Wow, how in the world is HTML easier to format text with than Android?”, well good news, you can tell android to act like an html interpreter so that you can do all your nice fancy styling in an html file, then just load it into a text view for Android. All you have to do is use the asset manager to get a stream to the html file, read from the stream and store it in a string, call fromHtml and pass the string, and pass that to setText for a text view. It’s pretty sweet actually.”
So I got to thinking – that IS actually pretty sweet!
As the landscape of web and mobile development gets more intertwined and complex, it is becoming very important to deliver a solid and consistent experience among all of the contexts that your content is viewed. What better way to do that than to deliver a mobile-first, responsive, and adaptive experience we know and love in HTML while still leveraging the .NET power given through Xamarin.
Different from Hybrid Apps?
In the mobile development world the term “hybrid app” typically refers to an application that presents some (or all) of its screens as HTML pages inside a hosted web viewer control.
Let’s walk through how to do this so you can see how it works!
So to start, I put together a simple and clean HTML layout that I wanted to use to demo this idea. Here is the layout I am working with:
As usual, create an Android Xamarin project to get started. This video will walk you through how read in the HTML file in your Xamarin Android project.
So I’m sure you can see, as I did, how great of a tool this is. Often we have text that we want to be able to present to the user in a formatted way and using the editor when making Xamarin forms is pretty painful for this kind of thing.
In this lesson will we be discussing how to invoke web services from your Xamarin iOS and Android applications. There are a few different ways that these applications can connect with web service technologies. The Xamarin platform supports consuming different web service technologies, and includes in-built and third-party support for consuming RESTful, ASMX, and Windows Communication Foundation (WCF) services.
What is REST?
Representational State Transfer (REST) is an architectural style for building web services. REST requests are made over HTTP using the same HTTP verbs that web browsers use to retrieve web pages and to send data to servers. The verbs are:
GET – this operation is used to retrieve data from the web service.
POST – this operation is used to create a new item of data on the web service.
PUT – this operation is used to update an item of data on the web service.
PATCH – this operation is used to update an item of data on the web service by describing a set of instructions about how the item should be modified. This verb is not used in the sample application.
DELETE – this operation is used to delete an item of data on the web service.
Web service APIs that adhere to REST are called RESTful APIs, and are defined using:
A base URI.
HTTP methods, such as GET, POST, PUT, PATCH, or DELETE.
The simplicity of REST has helped make it the primary method for accessing web services in mobile applications.
What is SOAP?
SOAP (Single Object Access Protocol) is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission.
ASP.NET Web Service (ASMX)
ASMX provides the ability to build web services that send messages using the Simple Object Access Protocol (SOAP). SOAP is a platform-independent and language-independent protocol for building and accessing web services. Consumers of an ASMX service do not need to know anything about the platform, object model, or programming language used to implement the service. They only need to understand how to send and receive SOAP messages.
A SOAP message is an XML document containing the following elements:
A root element named Envelope that identifies the XML document as a SOAP message.
An optional Header element that contains application-specific information such as authentication data. If the Headerelement is present it must be the first child element of the Envelope element.
A required Body element that contains the SOAP message intended for the recipient.
An optional Fault element that’s used to indicate error messages. If the Fault element is present, it must be a child element of the Body element.
SOAP can operate over many transport protocols, including HTTP, SMTP, TCP, and UDP. However, an ASMX service can only operate over HTTP. The Xamarin platform supports standard SOAP 1.1 implementations over HTTP, and this includes support for many of the standard ASMX service configurations.
Generating a Proxy
A proxy must be generated in order to consume an ASMX service, which allows the application to connect to the service. The proxy is constructed by consuming service metadata that defines the methods and associated service configuration. This metadata is exposed as a Web Services Description Language (WSDL) document that is generated by the web service. The proxy is built by using Xamarin Studio or Visual Studio to add a web reference for the web service to the platform-specific projects.
The web service URL can either be a hosted remote source or local file system resource accessible via the file:/// path prefix, for example:
This generates the proxy in the Web or Service References folder of the project. Since a proxy is generated code, it should not be modified.
Windows Communication Foundation (WCF)
WCF is Microsoft’s unified framework for building service-oriented applications. It enables developers to build secure, reliable, transacted, and interoperable distributed applications.
WCF describes a service with a variety of different contracts which include the following:
Data contracts – define the data structures that form the basis for the content within a message.
Message contracts – compose messages from existing data contracts.
Fault contracts – allow custom SOAP faults to be specified.
Service contracts – specify the operations that services support and the messages required for interacting with each operation. They also specify any custom fault behavior that can be associated with operations on each service.
There are differences between ASP.NET Web Services (ASMX) and WCF, but it is important to understand that WCF supports the same capabilities that ASMX provides – SOAP messages over HTTP.
In general, the Xamarin platform supports the same client-side subset of WCF that ships with the Silverlight runtime. This includes the most common encoding and protocol implementations of WCF — text-encoded SOAP messages over the HTTP transport protocol using the BasicHttpBinding class. In addition, WCF support requires the use of tools only available in a Windows environment to generate the proxy.
Considerations for web services
When creating apps that require a web service it is important to note that the app will require constant connectivity via the mobile connection or wifi to work. This can cause some problems when users try to use your app in areas of bad connectivity or poor reception. We will look at how to check for both mobile and wifi connectivity in the demo.
In the video below I show you how to connect to a web service using an iOS project but if you are working with Android Xamarin projects, the code and steps are going to be exactly the same. Bonus!
This video will show you how to check for a Wi-Fi and Mobile Internet connections in your Android and iOS applications written with Xamarin. Once we have checked for network connectivity, I will show you how to connect to a web service using the Windows Communication Foundation (WCF).
Displaying a list is one of the most common design patterns used in mobile applications. Tables are one of the single most important controls in iOS applications. It’s hard to find an application that doesn’t use tables in some form. Tables in iOS are highly customizable and wrap a lot of functionality that we get for free.
The source for the data displayed in the TableView can come from objects such as arrays or Lists. You can also bind to a data source such as a database table.
In order to determine what should happen when a row is clicked, you can use the RowSelected event.
A UITableView can have a ‘grouped’ or ‘plain’ style, and consists of the following parts:
Editing mode (includes ‘swipe to delete’ and drag handles to change row order)
There is a lot of functionality to make your TableViews really pop in your application.
Swipe to delete individual cells.
Entering Edit mode to reveal delete buttons on each row
Entering Edit mode to reveal re-ordering handles.
Inserting new cells (with animation).
The primary classes used to display table views are shown here
In this tutorial, we will be using UITableViewSource – Xamarin.iOS-exclusive abstract class that provides all the methods required to display a table, including row count, returning a cell view for each row, handling row selection and many other optional features. Youmust subclass this to get a UITableView working.
Opening the Browser
When we want to perform actions using another app on the device, we can do a SharedApplication call. This is part of the UIApplication class, which holds all of the central administrative properties for any application running on iOS (more here: https://developer.xamarin.com/api/type/UIKit.UIApplication/)
An Android app typically requests data and then modifies that data to produce a result throughout multiple activities. With programs you have written so far, the values entered did not persist beyond the Activity in which they were created. The data was lost because it was being stored in RAM which is cleared each time the app is closed. To create persistent data that can be accessed over and over, Android apps can save data on the device’s drive or other storage media such as a memory card. This lesson will show you how to store data that your app can then retrieve and use.
Locations of Persistent Data
Android provides several options for saving application data based on the specific needs of the app. Some apps require private storage while others need to share data between apps.
There are five different places to store data:
Shared Preferences – Stores data in key/value pairs
Internal Storage – Stores private data in the memory of the device
External Storage – Stores data, which can be available to other apps on shared external storage
SQLite Databases – Stores structured data in a private database
Network Connection – Stores data on a Web server
Retrieving Android data is just about as easy as saving it when you are working with SharedPreferences. The difference is that you do not need to setup an Editor in order to read data that has already been stored.
In addition to the Android system storage locations, Xamarin apps also have Application.Current.Properties which is implemented in Xamarin.Forms which allows you to store simple Key-Value pairs of data as well. The Properties dictionary is saved to the device automatically. Data added to the dictionary will be available when the application returns from the background or even after it is restarted.
Xamarin.Forms 1.4 introduced an additional method on the Application class – SavePropertiesAsync() – which can be called to proactively persist the Properties dictionary. This is to allow you to save properties after important updates rather than risk them not getting serialized out due to a crash or being killed by the OS.
This video will walk you through creating an app that stores information using the Shared Preferences. We will store data using an Editor and retrieve it. Retrieving Android data is just about as easy as saving it when you are working with SharedPreferences. The difference is that you do not need to setup an Editor in order to read data that has already been stored.
In this lesson, you’ll learn how to gather input from the user and make decisions with that information. You’ll also learn how to display information to the user.
We’re also going to explore the Model-View-Controller pattern, which is present in the design of apps made on the Xamarin platform.
If you’re not already familiar with the MVC pattern of application development, let’s start with an overview.
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces on computers. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.
MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.
The MVC framework includes the following components:
Models. Model objects are the parts of the application that implement the logic for the application’s data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.
Views. Views are the components that display the application’s user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Productobject.
Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.
The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.
The loose coupling between the three main components of an MVC application also promotes parallel development. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.
Using Navigation in iOS
A Storyboard is a visual representation of the appearance and flow of your application. Xamarin has introduced a Designer to allow Xamarin.iOS applications to take advantage of storyboards, so you can design your application screen visually and access the views, controllers and segues with C# for more control.
In this section, you’ll learn how to gather input from the user and make decisions with that information. You’ll also learn how to display information to the user. We’ll also look at how to navigate between multiple views in your Android application.
Adding an Activity
In order to add code to the app that will respond when the user clicks the button, we have to add an Activity. Your app can be made up of many activities that happen together or at various times.
An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI
While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup).
There are two methods almost all subclasses of Activity will implement:
onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).
What do you Intend to do?
From the Android documentation:
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
That’s some engineering speak, right?
So what is an Intent? An Intent is a description of an operation to be performed. An intent allows you to start an activity in another app by describing a simple action you’d like to perform (such as “view a map” or “take a picture”) in an Intent object.
This type of intent is called an implicit intent because it does not specify the app component to start, but instead specifies an action and provides some data with which to perform the action.
An Intent in Xamarin is pretty easy. You create the Intent object, provide any additional information you want to pass to the Intent and call StartActivity to get it kicked off.
var intent = new Intent(this, typeof(YourActivityHere));
When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, are the only choice. However, over the past few years, an entire new ecosystem of platforms for building mobile applications has emerged.
Xamarin is unique in this space by offering a single language – C#, class library, and runtime that works across all three mobile platforms of iOS, Android, and Windows Phone (Windows Phone’s native language is already C#), while still compiling native (non-interpreted) applications that are performing well enough even for demanding games.
Testing Your Apps
If you do not have a device that you can use for testing, you will need to use an emulator and run your applications in the test environment.
Xamarin Android Player
The Xamarin Android Player relies on virtualization and OpenGL. This means that it cannot run inside virtual machine instances nor can it work over Remote Desktop or VNC. Further system requirements can be found in the guide linked below.
Xamarin mobile applications can be deployed to physical devices via USB for testing and debugging (Xamarin.Mac apps can be tested directly on the development computer; Apple Watch apps are deployed first to the paired iPhone). You will need to be sure that your device is setup for development if you wish to test on it. Here is the guide that can help you get started: https://developer.xamarin.com/guides/ios/getting_started/installation/device_provisioning/
Since you are learning the basics of C# here, why not take it a step further and learn how to write mobile apps using the Windows Phone mobile platform? All of your C# knowledge you’ve learned here can start earning you money quickly on the app store!
Existing C# Learning students get $10 off of this course. Email me for your coupon code!