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;

}

}

Advertisements

Mobile Device Testing and Debugging with VirtualBox, Android Studio, Visual Studio and IIS

This post is from the perspective of a person who has a Microsoft technologies based web solution that needs to connect with a mobile device. This might work for other types of technologies and virtual machines with some or alot of tuning. Basic principles should be more or less the same.

I will give firstly an introduction on the solution used in my scenario:

I have a Android mobile device with an app in it that needs to connect to a webapi service to retrieve data and post data to it. The thing which this post is concerned about, is debugging the app with Android studio using the app from the Android device against a webapi which is also under debug mode in Visual Studio. This way I can see what is happening both on the client and on the server side.

Basically how this works is that you will have to connect with your mobile device to a local network where your physical machine exists. Because you are using a mobile device the logical way is over WiFi and no having your device plugged in to your physical machine by USB does not work. You can not directly connect to a localhost that way. Well atleast I could not make it to work. Notice that you can connect to a localhost from Android Studio while debugging your Android app but this is only possible is your a emulating the app locally. Even then though you might have problems and have to configure your solution in such a way that your app will pick it up.

This post assumes that you have a ready build for your server side solution at a location in your development machine. Here are the steps:

1. Create IIS site

– Add a new application to IIS which points to your solution build location.
mobile1

mobile2

– Next make sure that the application pool account has enough privileges to the location. I do this by creating a new account to AD or I create a local machine account on my development machine.

This is to configure the Application Pool account:
mobile8

These steps are for the file system level:
mobile3

mobile4

– If you are using a database in your application make sure that the application pool account has the proper privileges. This depends of course on how you have built your solution.
– Assign a port to your web application

mobile6

mobile5

2. Config ports and firewall settings
– Next you need to allow inbound and outbound connections to you web application through the port which was earlier configured for the web application. This needs to be done for both the virtual machine and your actual physical machine.

For virtualBox:
mobile9

For WMWare:
mobile10
mobile11

3. Attach to process

The next steps is to attach your developer tools to your server solution and your mobile application to whatever developer tools your are using, something like Android Studio or XCode.

Config VirtualBox

How to Forward Ports to a Virtual Machine and Use It as a Server

 

Things learned from Objective-C – Cocos2D porting and testing in Swift – Part 2

More things learned from playing around with Swift, Objective-C and Cocos2D

Interoperability between Objective-C and Swift – Initialize patterns

If you have in you Objective-C code an Initialize Pattern to access it in Swift you just use the class name and access the initialize pattern as you would access a static function. Just remember to downcast with the ‘as’ operator returning the class from which you are using the initialization pattern.  The green code below:

var moveToLeftEdge : CCActionMoveTo = CCActionMoveTo(duration: CCTime(birdTime), position: screenLeft);
var turnaround : CCActionFlipX = CCActionFlipX(flipX: true);
var moveBackOffScreen : CCActionMoveTo = CCActionMoveTo(duration: CCTime(birdTime), position: birdStart);
var birdActions = Array<CCAction>();
birdActions.append(moveToLeftEdge);
birdActions.append(turnaround);
birdActions.append(moveBackOffScreen);
birdActions.append(turnaround);

var moveLeftThenBack : CCActionSequence = CCActionSequence.actionWithArray(birdActions) as CCActionSequence;

 

Interoperability between Objective-C and Swift – Objective-C Selectors

To access Objective-C selectors in Swift you define a constant value with the value being the function name to call within your class. See green code below:

https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-XID_38

let mySelectorTurnAround: Selector = “turnAround”;
var turnArround : CCActionCallFunc = CCActionCallFunc.actionWithTarget(bird, selector: mySelectorTurnAround) as CCActionCallFunc;

 

Objective-C Struct definition usage and initialization

If you are get the following error message when using struct definitions in Objective-C then the solution is to initialize the struct before usage. Below is an example of than in the green color.

Error Message: Struct ‘struct name’ must be completely initialized before a member is stored to

Original Objective-C Struct definition:

// Bezier configuration structure.
typedef struct _ccBezierConfig {
// End position of the bezier.
CGPoint endPosition;
// Bezier control point 1.
CGPoint controlPoint_1;
// Bezier control point 2.
CGPoint controlPoint_2;
} ccBezierConfig;

In Swift Code Usage

var curve : ccBezierConfig = ccBezierConfig(endPosition: CGPointMake(0, 0), controlPoint_1: CGPointMake(0, 0), controlPoint_2: CGPointMake(0, 0));