General Xamarin Notes

Fire OS 3.5 Notes

  • Build with v17 of Android
  • Open the Android SDK Manager
  • Tools -> Add-on Sites --> User Defined Sites -> Add the following url:
http://kindle-sdk.s3.amazonaws.com/addon.xml
  • In the SDK Manager -> Extras -> add the:
Kindle Fire USB Driver
Android Support Repository
Android Support Library
Intel X86 Emulator Accelerator

Emulator Resources

Cheat Sheets

Videos

Books

Libraries

Collection of abstracted mobile functionalities. Xamarin.iOS, Xamarin.Android & WP8

iOS Simulator

Xamarin Studio

  • Must manually add your own using statements, since in most cases it won't automatically import them. For example:
using System.Linq;
  • How to change the build configuration for a project (eg: change it to Mono / .NET 4.5):
Project (in the top menu) -> click on the project name -> Build (heading) -> General -> Target Framework

Xamarin Studio Errors

Can not find file specified when compiling in Xamarin Studio

chmod +x fslex.exe
chmod +x fsyacc.exe
  • fix 2
    find the path in your error message:
/Users/someuser/Library/Developer/Xamarin/android-sdk-macosx//tools/zipalign'

then we know the android path:

/Users/someuser/Library/Developer/Xamarin/android-sdk-macosx/

Check if the build-tools/20.0.0 path exists. If it does not, install the Android SDK Build Tools 20.0

Visual Studio Errors

aapt-exe-exited-with-code-1-when-building-mono-for-android-project

Configure Android Device

How to enable debugging on physical android device

MVVM

  • Best practice for when to split up the ViewModel layers functionality: Always create a new class
    when the UI has a new screen. This keeps code clean and follows SRP

Xamarin Forms

Unit Tests

  • For unit tests in Xamarin Studio, create a new NUnit Library Project

Dependency Injection

  • program should depend upon abstractions, not on concrete types. (from SOLID)

Service Locator Pattern

Open Source Alternatives:
iOS
  • iOS - Place the service locator registration code in either the static void Main() method or in the FinishedLaunching method of the AppDelegate class since these are called before the applications starts
Android
  • Must be put in a custom Android Application class that has an OnCreate method
  • The OnCreate method must be called prior to
    any activities being created in the app.

iOS Xamarin Notes

Project File Types

  • Use preprocessor statements when using cloned or linking projects files. Eg:
#if ANDROID
	// Do something if running on Android
#elif IPHONE
	// Do something if running on iPhone
#else
	// Do something if running on a different OS
#endif
#if IPHONE
  • Only use the preprocessor statements when in a bind or have a small amount of code. Instead use inheritence or interfaces since this preprocessor code can become a tangled mess.

  • Standard class library and file-linking strategy go hand-in-hand

Files and Folders used in Xamarin iOS Apps

  • Resources - Directory that contains any images or plain files that you
    want to be copied directly to your application bundle.
  • AppDelegate.cs - Apple's main class that handles application-level
    events in your app.
  • ViewController.cs - controller that represents the first screen in
    your app. Has same name as your project.
  • Info.plist - Apple's version of a manifest file that can declare
    various settings for your application.
  • Main.cs - file containing the standard entry point for a C# program static void Main(). Do not modify this file.
  • MainStoryboard.storyboard - storyboard definition file for
    your application. Contains the layouts for the views in your app, list of
    controllers, and transitions for navigating in your app.

Overridable methods in AppDelegate.cs

TODO: Clean this up!
FinishedLaunching: This is the first entry point for the application, which
should return true.
DidEnterBackground: This means the user clicked on the home button on
their device or another instance, such as a phone call, came to the foreground.
You should perform any action needed to save the user's progress or state of
the UI as the iOS may kill your application once pushed to the background.
While your application is in the background, the user could be navigating
through the home screen or opening other apps. Your application is
effectively paused in memory until resumed by the user.
• WillEnterForeground: This means the user has reopened your application
from the background. You might need to perform other actions here such as
refreshing the data on the screen and so on.
• OnResignActivation: This happens if the operating system displays
a system pop up on top of your application. Examples of this are calendar
reminders or the menu the user can swipe down from the top of the screen.
• OnActivated: This happens immediately after the OnResignActivation
method is executed as the user returns to your app.
• ReceiveMemoryWarning: This is a warning from the operating system to free
up the memory in your application. It is not commonly required with Xamarin
because of C#'s garbage collector, but if there are any heavy objects such as
images throughout your app, this is a good place to dispose them. If enough
memory cannot be freed, the operating system could terminate your application.
• HandleOpenUrl: This is called if you implement a URL scheme, which is the
iOS equivalent of file extension associations on a desktop platform. If you
register your app to open different types of files or URLs, this method will
be called

Overridable method in ViewController.cs

ViewDidLoad: This occurs when the view associated with your controller is
loaded. It will occur only once on devices running iOS 6 or higher.
• ViewWillAppear: This occurs prior to your view appearing on the screen. If
there are any views that need to be refreshed while navigating throughout
your app, this is generally the best place to do it.
• ViewDidAppear: This occurs after the completion of any transition
animations and your view is displayed on the screen. In some uncommon
situations, you might need to perform actions here instead of in
ViewWillAppear.
• ViewWillDisappear: This method is called prior to your view being hidden.
You might need to perform some clean-up operations here.
ViewDidDisappear: This occurs after any transition animations are
completed for displaying a different controller on the screen. Just like the
methods for appearing, this occurs after ViewWillDisappear.

Detailed Methods

iOS Open URL in Native Browser

using MonoTouch.Foundation;
using MonoTouch.UIKit;
public static void OpenUrl(string url) {
	UIApplication.SharedApplication.OpenUrl(
	NSUrl.FromString(url));
}

Android Notes

Files and Folders used in Xamarin Android Apps

TODO: Clean this up!
The Assets folder: This directory will contain files with a build action of
AndroidAsset. This folder will contain raw files to be bundled with an
Android application.
• Properties/AndroidManifest.xml: This file contains standard declarations
about your Android applications, such as the application name, ID, and
permissions.
• The Resources folder: Resources are images, layouts, strings, and so on
that can be loaded via Android's resource system. Each file will have an ID
generated in Resources.designer.cs that you can use to load the resource.
• The Resources/drawable folder: Any images used by your application are
generally placed here.
The Resources/layout folder: This contains any *.axml (Android XML)
files that Android uses to declare UIs. Layouts can be used for an entire
activity, fragment, dialog, or child control to be displayed on the screen.
• The Resources/values folder: This contains XML files to declare key-value
pairs for strings (and other types) throughout an application. This is how
localization for multiple languages is normally set up on Android.
• MainActivity.cs: This is the MainLauncher action and the first activity of
your Android application. There is no static void Main function in Android
apps; execution begins on the activity that has MainLauncher set to true.

Android Activities

  • activity - task or unit of work that users can perform on their screen. eg: Making a phone call
  • Back stack - stores the users history

Overrideable methods in Activities Lifecycle

TODO: Clean this up!
OnCreate: This is the first method called when your activity is created. Set up
your views and perform other loading logic here. Most importantly, you will
call SetContentView here to set up your activity's view.
• OnResume: This is called when your activity's view is visible on the screen.
It is called if your activity is displayed for the first time and when the user
returns to it from another activity.
• OnPause: This is called to notify that the user has left your activity. It can
happen prior to navigating to a new activity within your app, locking the
screen, or hitting the home button. Assume that the user may not return,
so you need to save any changes the user made here.
• OnStart: This occurs immediately before OnResume when the activity's view
is about to be displayed on the screen. It occurs when an activity starts and
when a user returns to it from another activity.
• OnStop: This occurs immediately after OnPause when the activity's view is
no longer displayed on the screen.
• OnRestart: This method occurs when the user returns to your activity from
a previous activity.
• OnActivityResult: This method is used to communicate with other
activities in other applications on Android. It is used in conjunction with
StartActivityForResult; for example, you would use this to interact with
the Facebook application to login a user.

  • OnDestroy: This is called when your activity is about to be freed from memory.
    Perform any additional clean-up that could help the operating system here,
    such as disposing any other heavyweight objects the activity was using.

Overrideable methods in Activities

TODO: Clean this up!

  • StartActivity(Type type): This method starts a new activity within your
    application and passes no extra information to the activity.
  • StartActivity(Intent intent): This is an overload method to start a new
    activity with Intent. This gives you the ability to pass additional information
    to the new activity, and you can also launch activities in other applications.
    • StartActivityForResult: This method starts a new activity with the
    anticipation of receiving OnActivityResult when the activity's operation
    is completed.
    • Finish: This will close the current activity and invoke OnDestroy when it
    is completely closed and no longer displayed on the screen. Depending on
    what is currently on the back stack, the user will return to a previous activity
    or the home screen.
    • SetContentView: This method sets the primary view to be displayed for an
    activity. It should be called within the OnCreate method prior to the activity
    being displayed on the screen.
    • FindViewById: This is a method to locate the view displayed in your activity.
    It has a generic version to return a view of the appropriate type.

Intent

  • intent - object that describes transition from one activity to another actitivty

Views

Text View Field

  • To get the instance of the TextView field, place the code below in the OnCreate method:
TextView text = FindViewById<TextView>(Resource.Id.myTextBox);

Detailed Method

iOS Open URL in Native Browser

using Android.App;
using Android.Content;
using Android.Net;
public static void OpenUrl(Activity activity, string url) {
	var intent = new Intent(Intent.ActionView,
	Uri.Parse(url));
	activity.StartActivity(intent);
}

TPL (Task Parallel Library)

  • For asyncronous programming, use the C# 5 async and await keywords.
  • Always use Task<T> for communicating with webservices since it can take a while
  • currently no support for async/await in NUnit (Only nUnit 2.6.2 has async/await support
  • If using an nUnit version that's lower than 2.6.2, you can work around it by calling the Wait method directly on any methods that return Task or Task. eg:
loginViewModel.Login().Wait();
Assert.That...

Start New Xamarin App

Create Solution

  • Create a new Blank Solutition, called

Create Portable Library

  • Porable Library project
  • Named: .Core

ScreenShot1

Create iOS Application

  • Create a new iOS -> iPhone -> Single View Application
  • Name it: .iOS

ScreenShot1

Modify the Info.plist

  • Info.plist is critical to settings that are needed in the app store and should be the first thing you setup in your project
  • In Xamarin Studio, double click on Info.plist, you will see the Application Name as <ProjectName>.iOS, rename it to <ProjectName>. The application name is the title below your apps icon in iOS.
  • Remove the .iOS from the end of the bundle identifier and change the name to be all lower case. Replace the company with your company.

iOS Options

  • Right click on your .iOS project -> properties
  • linker behavior - Linking will strip any code that will never be called within your
    assemblies. Keeps your app small and allows them to
    deploys a stripped-down version of the core Mono framework with your app. Recommended to use the Link SDK assemblies only option.
  • Use SGen generational garbage collector - new Mono garbage collector. Use for games that need high performance.

iOS Text Fields

  • To create a masked text field, check the Secure checkbox in the text fields properties. This identifies whether the input is masked (such as for a Password input). More details in the Xamarin documentation

iOS Activity Indicator

  • Good for giving feedback to the user that something is happening while a process is taking place, such as logging in
  • To use this, in the story board, drag the activity indicator onto the controller. Be sure to check the project.animating and hidden checkboxes.

Adding Shared Code to iOS Project

  1. In your <ProjectName>.iOS project, create a new folder name Core.
  2. Right-click on the new Core folder -> Add -> Add Existing Files, select all the files and folders that contain code from the .Core folder. Select Add a link to the file on the next screen. This way you can access all of them in the iOS.

Code Sharing Options

  • Details about the code sharing options
  • Shared Projects - Use the Shared Asset Project type to organize your source code, and use #if compiler directives as required to manage platform-specific requirements.
  • Use Shared Projects when writing code that will only be shared in your app and you will not be distributing to other developers.
  • Portable Class Libraries - Create a Portable Class Library (PCL) targetting the platforms you wish to support, and use Interfaces to provide platform-specific functionality.

Segue and Storyboards

  • segue is a transition from one controller to another. It's used in iOS development to represent a transition between Scenes.
  • To create a segue, hold down the Ctrl key and click-drag from one Scene to another.
  • storyboard file is a collection of controllers and their views attached together by segues.

Transition to another controller

  • To transition to anoutther controller via a segue use (replace with the name of the Segue:
PerformSegue("<SegueName>", this);

4 Types of Seques:

TODO: Clean this up!

  • Push: This is used within a navigation controller. It pushes a new controller
    to the top of the navigation controller's stack. Push uses the standard
    animation on iOS for navigation controllers and is generally the most
    commonly used segue.
  • Relationship: This is used to set a child controller of another controller.
    For example, the root controller of a navigation controller, container views,
    or split view controllers in an iPad application.
  • Modal: On using this, a controller presented modally will appear on top of
    the parent controller. It will cover the entire screen until dismissed. There are
    several types of different transition animations available.
  • Custom: This is a custom segue that includes an option for a custom class,
    which subclasses UIStoryboardSegue. This gives you fine-grained control
    over the animation and how the next controller is presented.

iOS Table View (UITableView)

  • UITableView - Similar concept to a list view on other platforms
  • UITableView is controlled by UITableViewSource
  • UITableViewCellAccessory.DislosureIndicator
  • Recyling cells is import for mobile apps (for memory and fluid scrolling). Use DequeueReusableCell to achieve this.

UiTableViewSource Common Overrides

  • 2 required methods for setting up a table view are RowsInSection & GetCell

TODO: Clean this up!

  • RowsInSection: This method allows you to define the number of rows in a
    section. All table views have a number of sections and rows. By default, there
    is only one section; however, it is a requirement to return the number of rows
    in a section.
  • NumberOfSections: This is the number of sections in the table view.
  • GetCell: This method must return a cell for each row. It is up to the
    developer to set up what a cell should look like; you can also implement code
    to recycle the cells as you scroll. Recycling cells will yield better performance
    while scrolling.
  • TitleForHeader: This method, if overridden, is the simplest way to return
    a string for the title. Each section in a table view can has a standard header
    view by default.
  • RowSelected: This method will be called when the user selects a row.

Notifications

  • iOS notifications.
  • Xamarin provides a C# friendly way to subscribe to notifications
  • Static nested class named Notifications inside UIKit classes that provide notifications
  • To unsubscribe from these events, we dispose of the NSObject that is returned

eg: Subscribing to notifications:

willShowObserver = UIKeyboard.Notifications.ObserveWillShow(
				(sender, e) => OnKeyboardNotification(e)
			);
willHideObserver = UIKeyboard.Notifications.ObserveWillHide(
				(sender, e) => OnKeyboardNotification(e)
			);

eg: Unscrubscribing from notifications

if(willShowObserver != null){
	willShowObserver.Dispose();
	willShowObserver = null;
}
if(willHideObserver != null){
	willHideObserver.Dispose();
	willHideObserver = null;
}

Xamarin iOS Designer

  • Details about the iOS Designer are here

Create Android Application

  • Create a new project: Android -> Android Application
  • Name it: .Droid

Commonly Used Android Permissions

** TODO: Clean up **
commonly used manifest permissions:
• Camera: This provides access to the device camera
• Internet: This provides access to make web requests over the internet
• ReadContacts: This provides access to read the device's contacts library
• ReadExternalStorage: This provides access to read the SD card
• WriteContacts: This provides access to modify the device's contacts library
• WriteExternalStorage: This provides access to write to the SD card

Android App Settings to Use

** TODO: Clean up **

  • If using Xamarin Studio, you need to generate the android manifest via: Project Options -> Android Application -> Add Android Manifest
  • • Application name: YourAppName
    • Package name: com.yourcompanyname.yourappname; make sure to name future
    apps beginning with com.yourcompanyname
    • Version number: 1
    • Version: string resembling a version number
    • Minimum Android version: Select Android 4.0.3 (API Level 15)
    • Required permissions:

ScreenShot1

Strings.xml

  • In the Resources directory -> values folder -> Strings.xml
  • this is where all the text throughout your Android app should be stored

Create Application Class For IOS Registration

 [Application(Theme = "@android:style/Theme.Holo.Light")]
    public class Application : Android.App.Application {
        protected Application(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) {
        }

        public override void OnCreate() {
            base.OnCreate();
			// insert your IOC container registration code here
            
        }
    }

Common Android Layouts

TODO: Clean this up

  • • ViewGroup: This is the base class for a view that contains a collection of child
    views. You normally won't use this class directly.
    • LinearLayout: This is a layout that positions its child views in rows or
    columns (but not both). You can also set weights on each child to have them
    span different percentages of the available space.
    • RelativeLayout: This is a layout that gives much more flexibility on the
    position of its children. You can position child views relative to each other so
    that they are above, below, to the left, or to the right of one another.
    • FrameLayout: This layout positions its child views directly on top of one
    another in the z order on the screen. This layout is best used for cases where
    you have a large child view that needs other views on top of it and perhaps
    docked to one side.
    • ListView: This displays views vertically in a list with the help of an adapter
    class that determines the number of child views. It also has support for its
    children to be selected.
    • GridView: This displays views in rows and columns within a grid. It also

Dialog Box Samples

Mono Android Dialog box samples (from 2013)

How to add an Android Layout

  1. Right click on the Layouts folder
  2. Add -> new item
  3. Selected Android Layout

Id's (Resources in Android)

  • Contain an @+id prefix. Eg:
@+id/username
@+id/password

(for a password field, set the input type property to "textPassword")

Set Android Activity to Launch on Start

To set the android activity that will launch on startup, use MainLauncher = true, as show in:

[Activity(Label = "@string/ApplicationName", MainLauncher = true)]

ListView and BaseAdapter

  • Android equivalent of UITableView and UITableViewSource are ListView and BaseAdapter.

Xamarin Number Picker

<Button
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/addButton"
android:textSize="50dp"
android:layout_gravity="right" />
       
<Button
android:text="-"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/subtractButton"
android:textSize="50dp"
android:layout_gravity="left" />
  • Number Picker control code

In the xml layout file:

<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/numPicker" />

In the Activity.cs file:

private NumberPicker _numPicker;
_numPicker = FindViewById<NumberPicker>(Resource.Id.numPicker);
_numPicker.MaxValue = 99;
_numPicker.MinValue = 0;
  • Create a menu folder within the Resources folder
  • Create a new Android Layout file named
    AbcMenu.axml.
  • Remove the default layout XML created and replace it with:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/abcMenu"
android:icon="@android:drawable/ic_menu_add"
android:showAsAction="ifRoom"/>
</menu>

**TODO: Clean up**

* **android:id** - Use in C# to reference the menu item with Resource.Id.abcMenu
* **android:icon** - This is an image resource to display the features for the menu item. Example uses a generic plus icon
* **android:showAsAction** - makes menu item visible if there is room

### Layout Types
* **RelativeLayout**
* **LinearLayout**

### Image View Types
* *Plus (+) icon: ```*@android:drawable/ic_menu_add```

### Styling Android
* [How to create a custom style in Android and what to take into consideration](http://developer.android.com/design/style/index.html)
* [Android/iOS Icon and Splash Screen Generator](http://www.appiconsizes.com/)
* [Android Design Tutoria from Late 2013](http://www.vogella.com/tutorials/AndroidStylesThemes/article.html)
* [Android Asset Studio](http://romannurik.github.io/AndroidAssetStudio/) - Web App that generates icons for your Android app
* [Android Design Preview](https://github.com/romannurik/AndroidDesignPreview) - lets you mirror a portion of your desktop to your device. Can help streamline your high-fidelity mockup workflow.
* [Android Holo Colors Generator](http://android-holo-colors.com/) - Generate your own colors for the Android Holo theme.
* [Another Theme Tutorial](http://mrbool.com/how-to-change-the-layout-theme-of-an-android-application/25837)
* [Yet another Theme Tutorial](http://examples.javacodegeeks.com/android/core/ui/android-styles-and-themes-example/)
* [Android Design Patterns](https://developer.android.com/design/patterns/index.html) - From android.com and very good!
* [Android Themes and Styles](http://developer.android.com/guide/topics/ui/themes.html) - From android.com and very good!

#### Android Action Bar Generator
* [Android Action Bar Generator](http://jgilfelt.github.io/android-actionbarstylegenerator/#name=example&compat=holo&theme=light&actionbarstyle=solid&texture=0&hairline=0&neutralPressed=1&backColor=E4E4E4%2C100&secondaryColor=D6D6D6%2C100&tabColor=33B5E5%2C100&tertiaryColor=F2F2F2%2C100&accentColor=33B5E5%2C100&cabBackColor=FFFFFF%2C100&cabHighlightColor=33B5E5%2C100) - put in the style that you want and it spits out all that you need for an action bar in android and a link to the [github code](https://github.com/jgilfelt/android-actionbarstylegenerator).
* [Xamarin Info on tabbed layouts and action bar](http://developer.xamarin.com/guides/android/user_interface/tab_layout/actionbar/)

#### Android Up and Down buttons or Zoom In/Zoom Out buttons

* [Drawable references](http://developer.android.com/reference/android/R.drawable.html)

* To set the background programatically (credit: [stack overflow](http://stackoverflow.com/questions/18557069/android-numberpicker-theme-plus-minus-buttons)):

Button b= (Button) findViewById(R.id.button1);
b.setBackgroundResource(android.R.drawable.arrow_up_float);
Set background in xml


<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:drawable/arrow_up_float"
 />

* for zoom in/zoom out just use ```btn_minus``` and ```btn_plus```


### Passing Complex Objects Between Activities
* [Ideas for passing custom objects between android activities](http://stackoverflow.com/questions/18997967/passing-custom-object-between-android-activities-in-c-sharp)
* [IParcelable](http://dan.clarke.name/2012/09/implementing-iparcelable-in-mono-for-android/)
* serialised to JSON, passed a string extra and deserialised it on the other end
* eg: **serialize with ServiceStack.Text**

intent.PutExtra("SelectedItemId", JsonSerializer.SerializeToString(selectedInsurance));


* eg: **deserialize with ServiceStack.Text**

var insurance = JsonSerializer.DeserializeFromString(Intent.GetStringExtra("SelectedItemId"))
No need to implement Java.Lang.Object, Java.IO.ISerializable


* [Activity LifeCycle](http://developer.android.com/reference/android/app/Activity.html#startActivity%28android.content.Intent) and then use ```StartActivity(intent);``` and pass it in through an intent