Xamarin Development – Notes, tips and info – Part 1: How to develop your first iOS and Android Apps

Hi,

This is series of posts and my notes and info which are based on a Udemy course. I’ve taken what I consider “good to know” and wrote them down. This may come handy to someone else.

These are my notes on Xamarin Development.

Presently this post is mostly based on this Udemy Course:

https://www.udemy.com/xamarin-beginners

Contents

What is Xamarin. 2

Xamarin Platform.. 2

Xamarin Test Cloud. 2

Xamarin Insight. 2

Debugging Android applications. 3

Xamarin Platform.. 4

C# as the language for your mobile app development. 4

Share your C# code on any platform.. 4

Device provisioning/installation of your app. 4

First iOS Application. 4

Basic iOS controls: 5

Properties window.. 5

Naming UI Controls. 5

Events. 6

UI Elements. 6

Different Keyboard types. 6

Changing background colors. 7

Tips and Tricks. 7

First Android Application. 7

Basic Androi controls. 7

Naming UI Controls. 7

Accessing UI elements in the code. 8

UI Elements. 9

Different Keyboard types. 9

Navigation between pages in iOS and Android. 9

Navigation between pages in Android. 9

Adding a new layout and activity. 10

Using Intents to navigate. 10

Passing values between activities (pages/layouts). 10

Navigation between pages in iOS. 11

Adding a new navigation controller. 11

Passing values between views/segues (pages/layouts). 15

What is Xamarin

Xamarin Platform

Building applications on mobile devices

Xamarin apps share code across all platforms

Target i0S, Android, Windows and Mac with a single, shared C# codebase. Use the same language, APIs and data structures on every platform.

C# is the best language for mobile app development

Anything you can do on Objective-C, Swift or Java, you can do in C#

Native UI, native API access, native performance

Xamarin apps are built with standard, native user interface controls. Apps not only look the way the end user expects, they behave that way too. This can’t be achieved with other solutions. They look and behave as they would on that native environment (Android. iOS, Windows Phone)

Xamarin Test Cloud

Test your applications on different devices

Test your app on over 1,000 devices

Run your app on a huge collection of real devices from around the world. Select devices based on form factor, manufacturer, operating system, or even popularity in your target market.

Automate using Ruby or C#

With a framework called Calabash you can automate and test any iOS or Android app, native or hybrid, from the UI level down for perfect integration and continuous improvements.

Analyze app performance

See full-frame screenshots and video playback for every step of every test, then receive performance data and compare reports against previous runs to find regressions and bottlenecks.

Xamarin Insight

Monitoring your applications

Precise, detailed error reporting

Xamarin Insights helps developers prioritize issues by showing exactly which users each crash is impacting, and what sequence of actions preceded the crash.

Understand how users are interacting with your app

Developers can see who’s online, which devices they’re using, what issues they’ve experienced, where they’re from, and which activities they’ve used in sessions.

Integrate your data

Connect your app to a variety of external services and be notified when a new issue is opened, an issue is occurring repeated times in a small amount of time, or an issue’s status changes.

· Github

· Visual Studio Online

· …

Debugging Android applications

· You can use normal Android Virtual Devices with the SDK

· for a FASTER experience use the Xamarin Android Player: https://www.xamarin.com/android-player

o You also avoid using Hyper-V on Windows

Image: 1 Xamarin Android Player

o To Use the Android Player just go to your Visual Studio toolbar and select a device in this case the device installed in Image: 1 Xamarin Android Player

Image: 2 Example how to use the Android Player

Xamarin Platform

C# as the language for your mobile app development

· Anything you can do in Objective-C, Swift, Java, you can do in C#

· Things which are better than competition(at the present)

o Stronger Types

§ Generics and Compound types are used safely

· No need for casting of comments

· Good tools that understand what you are doing

o Language-level async, made easy in C#

o First-class functions, lambdas are easy to use

Share your C# code on any platform

· Possible to share on average about 75 % of your code across platforms

o Most of it at app logic, common functionality

o Could also be at UI level

§ Xamarin.Forms could be used in theory to achieve 100 % shareable code

Device provisioning/installation of your app

· iOS – Two options:

o Enroll to the Apple Developer Program:

§ https://developer.xamarin.com/guides/ios/getting_started/installation/device_provisioning/

o Or with Xcode 7 use free provisioning:

§ https://developer.xamarin.com/guides/ios/getting_started/installation/device_provisioning/free-provisioning/

First iOS Application

· Start with a single view app

· Main.Storyboard we define the UI

· ViewController.cs the main logic goes here

· iOS UI design on implementation requires more work to make it work and look good across different iOS devices

· By default the main.storyboard is linked to the ViewController.cs.

Basic iOS controls:

· Label

· TextField (for inputing data)

· Button

Properties window

· Widget tab

o You can alter button properties such as:

§ Color and how it looks

§ Title

§ Font

§ ID

§ etc

· Layout tab

o How the control is laid out on the UI

· Events tab

o How the user interacts with the control through touch

Naming UI Controls

· This can be achieved through the properties window.

o Select the desired UI control from the main.storyboard

o Go to the Name text field under the Identity category

o Notice: This is a physical name, meaning that you use this in the code to access the control

Events

· When users click/touch on buttons an event is launched.

· You can attach to a click event through the UI or through code by normal C# event handling in the ViewDidLoad() function in the ViewController.cs file

public override void ViewDidLoad()

{

base.ViewDidLoad();

// Perform any additional setup after loading the view, typically from a nib.

this.convertButton.TouchUpInside += ConvertButton_TouchUpInside;

}

UI Elements

Different Keyboard types

· You can select different types of keyboard by selecting a text field and under Keyboard Type select the desired keyboard output

Changing background colors

To change the background color of a control simply change the BackgroundColor property. Example>

this.colorView.BackgroundColor = UIColor.FromRGB(redValue, greenValue, blueValue);

Tips and Tricks

Using this.View.EndEditing(true); will end/hide the editing keyboard.

First Android Application

· For Visual Studio development you need Hyper-V to emulate an android device

Basic Androi controls

· Under Text fields category you will find normal input controls

· Under form widgets you will find basic button and plain text controls

Naming UI Controls

· This is found in the properties window under the Main category and in there ID

Accessing UI elements in the code

· In an Android application you have to find the controls manually and assign them to a variable of the same type.

· You use the FindViewById<>() function call. You pass the class type to the template(generic) parameter, then pass the control ID by accessing your project namespace then Resources class, then Id class and finally the control ID which you define in your layout.

Example:

using Android.Runtime;

using Android.Views;

using Android.Widget;

using Android.OS;

namespace BMICalculationAndroid

{

[Activity(Label
=
“BMICalculationAndroid”,
MainLauncher =
true,
Icon =
“@drawable/icon”)]

public class MainActivity : Activity

{

Button calculateBMI;

TextView resultTextView;

EditText heightEditText, weightEditText;

protected override void OnCreate(Bundle bundle)

{

base.OnCreate(bundle);

// Set our view from the “main” layout resource

SetContentView(Resource.Layout.Main);

this.calculateBMI = FindViewById<Button>(BMICalculationAndroid.Resource.Id.calculateBMI);

this.resultTextView = FindViewById<TextView>(BMICalculationAndroid.Resource.Id.resultTextView);

this.heightEditText = FindViewById<EditText>(BMICalculationAndroid.Resource.Id.heightEditText);

this.weightEditText = FindViewById<EditText>(BMICalculationAndroid.Resource.Id.weightEditText);

}

}

}

UI Elements

Different Keyboard types

· To change to keyboard type when typing on a mobile device you do it similarly as on the iOS side

o In the properties window go to Main – Input Format => inputType and change the keyboard type

Navigation between pages in iOS and Android

Navigation between pages in Android

Adding a new layout and activity

· This allows you to create another UI view/page that is to be displayed in your application

To do this in Visual Studio go to the Resources/Layout folder and add a new item. From the Add New Item window select the Android Layout option.

Then create new activity code class which will operate on the newly created layout.

You can create this for example in your project root by adding again a new item there.

Then to create the link and set the content between the layout and the activity call the SetContentView() function.

protected override void OnCreate(Bundle savedInstanceState)

{

base.OnCreate(savedInstanceState);

// Create your application here

SetContentView(Resource.Layout.BMIDetails);

}

Using Intents to navigate

· You navigate to another layout(page) by using the Intent class

· You can use the constructor that takes the present content and the desired activity class associated with the layout

· Then you start the activity and move to the other layout(page) by calling the StartActivity() function

var intent = new Intent(this, typeof(BMIDetailsActivity));

StartActivity(intent);

Passing values between activities (pages/layouts)

· In the activity from where you want a value to be passed to another activity you use the Intent class member function named PutExtra() to store the value. It is a key value pair which can be retrieved in another activity later:

var intent = new Intent(this, typeof(BMIDetailsActivity));

intent.PutExtra(“bmi_value”,this.bmi);

StartActivity(intent);

· And to restore the value you access it through the activity Intent class member by accessing from it the Extras member. From there use the GetFloat() function.

var bmi = Intent.Extras.GetFloat(“bmi_value”);

Navigation between pages in iOS

Adding a new navigation controller

· Drag and drop a new navigation controller

· If you already have a root view controller, then remove the one which was created by the previous operation (Press the mouse second button on the view controller and press delete)

· Next move is to indicate to the application what is the starting view (Apple story board naming is: sourceless seque). You are using a sourceless seque indicator: https://developer.xamarin.com/guides/ios/user_interface/introduction_to_storyboards/

o Drag and drop it on the navigation controller

Image: 3 it should look something like this

· Next create a relationship between the navigation controller and the main view by pressing CTRL + left mouse button on the navigation controller and dragging the mouse over the main view. Then you select the Root option from the new popup. This will mark the main view as the root view.

· Next drag a new view on the storyboard and give it a name. Once you do this the developer tool will warn you that there is no code behind class associated with the view(In Xamarin Studio the UI will offers you to create one). In Visual Studio the easiest way to do it is to press the dark grey area on the view without a controller and writing a new class name in the Class property in the properties window. This will create a new view controller associated to the view selected.

· To navigate from your Main(root) view just select a control that can be pressed like a button, press CTRL + left mouse button on it, then drag to the desired view and let go of the mouse button. In the new popup select Show. This is it. A connection and transition has been made between the views.

Passing values between views/segues (pages/layouts)

· To pass a value between views/segues you can override the function PrepareForSegue() which is launched when the segue is about to be used, that is when the user presses a button or some other UI element which invokes the action of moving from one view/page/layout to another one. What was done earlier.

· In the function you then access the parameter segue and ask for the DestinationViewController class member which you have to cast to the target view controller class. After that it is simply of matter of accessing the defined properties in the view controller class. Same as accessing any public member of a class.

public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)

{

base.PrepareForSegue(segue, sender);

var detailViewController = segue.DestinationViewController asBMIDetailsViewController2;

if(detailViewController != null)

{

detailViewController.bmi = this.bmi;

}

}

How to profile and analyze your application performance with Visual Studio 2015

I ran into a couple of good MSDN resources while looking into how to analyze your applications performance and see possible bottlenecks. Here is what I found:

https://blogs.msdn.microsoft.com/visualstudio/2016/02/15/analyze-cpu-memory-while-debugging/

https://blogs.msdn.microsoft.com/visualstudioalm/2015/07/20/performance-and-diagnostic-tools-in-visual-studio-2015/

https://blogs.msdn.microsoft.com/visualstudioalm/2015/10/29/profile-your-cpu-in-the-debugger-in-visual-studio-2015/

https://blogs.msdn.microsoft.com/visualstudioalm/2015/04/29/diagnosing-event-handler-leaks-with-the-memory-usage-tool-in-visual-studio-2015/

https://blogs.msdn.microsoft.com/vcblog/2015/10/21/memory-profiling-in-visual-c-2015/

 

IIS Express and Android Studio connection issues

If you are getting a following like error when you are trying to connect to a Microsoft Web Service or whatever server point that is under IIS Express you might encounter the following error:

failed to connect to /127.0.0.1 (port “Your port number here”): connect failed: ECONNREFUSED (Connection refused)

The error above is due to a loopback problem. What you need to do is do some configurations.

  1. Find your applicationhost.config file under your documents(usually): C:\Users\”Your account name here”\Documents\IISExpress\config
  2. Then find your web service binding information see the example below(the sample in the green color, the red color binding is what is by default configured).
  3. Add the IP address and the port to which you want to connect at from android studio. The IP address has to be your development machines IP address.
  4. Also you need to add new rules to your windows firewall that allows your ports through which you wish the connection to be done.
  5. You may need to run Visual Studio in Administrator mode

<sites>

<site name=”MyFitnessTrackerWebAPI(1)” id=”17″>
<application path=”/” applicationPool=”Clr4IntegratedAppPool”>
<virtualDirectory path=”/” physicalPath=”C:\Users\Adrian Simionescu\Dropbox\MyFitnessTracker\MyFitnessTrackerWebAPI\MyFitnessTrackerWebAPI” />
</application>
<bindings>
<binding protocol=”http” bindingInformation=”*:52797:localhost” />
<binding protocol=”http” bindingInformation=”*:80:192.168.163.151″ />
<binding protocol=”http” bindingInformation=”*:52797:192.168.163.151″ />
</bindings>
</site>

</sites>

After this when you start up your webservice you should be able to access your service by address or host name. Also your IIS Express hosting information should look something in the this direction(based on the configuration above):

IIS express configurations