Hello world!

Welcome to Red Pill Xamarin.

We are migrating to a new hosting provider in order to provide a richer environment to you, our loyal readers.  Better layout, less wasted space, mobile platform versions, code-parsing plug-ins… and lots more… are on the way.

We should be done moving into our new digs in the next couple days so please be sure to check back in a day or two and let us know what you think.

If you like the series please subscribe – IT’S FREE – and lets us know that people actually follow us.  If we don’t see any subscribers then it seems like there isn’t an audience for more tutorials.

301 – Quikies – Icon strategy

I’ve seen more than a few people ask “How should I deal with my icons and images in a cross-platform way?”. Well… There are a lot of strategies depending on need, and end goal. Is the image going to be a 2500×2500 Canon RAW customer portrait that you’re editing as their wedding image – Or are we talking about 48×48 .png icons for the tool bar?

By far most times we’re just talking about the icon images scattered around the app. A gear icon to indicate “settings”, or an arrow to mean “up one level”. Etc.

Each platform has its own required location.
• Droid | Resources | Drawable {sub folders for resolution specific versions}
• iOS | Resources {everything dumped into one folder}
What I do is keep the actual .png in a folder in the PCL, then add a link to the file in each of the platform projects. Not duplicates of the image, but a link. What I like about this is that I only have to replace an icon image in one place. If I replace the charging.png icon because the boss said “I don’t like the electric plug. Make it a lightning bolt”, I don’t have to be sure to change the image in 4 different platform-project folders. It helps if you name icons/images by purpose instead of description. submit.png not green_led_48x48.png – that way when the submit icon needs to change to something else it is still the submit purpose even if it is now a red triangle instead of a green circle.

In the PCL

Make a folder for your art/icon and put the real image in it.
Select it. In the properties pallet set it as: Content & Do not copy

In the Platform project (Android)

Add an Existing Item.

Navigate to the real item you put in the PCL folder.
Choose the Drop down so you can
Add as link

Select it. In the properties pallet set it as: AndroidResource & Do no copy

Notice the difference in the icons. The little blue bit tells you this is a link to the real image.

Device resolution specific versions

Purists will be mad at me for this but… I don’t do icons for high, medium and low screen densities in 90% of my stuff. Meaning I don’t have to deal with the @2x, or -xxhdpi versions. Call me lazy but a settings gear icon really just doesn’t make that big of a difference. If you have an image/icon where it does make a difference to you or your client, then you’ll need to put the right resolution in the right folder with the right name and manage them individually.

207 – Commands

Command versus Event

No this is not the next grudge match on Mixed Martial Arts… Or the Grammy Awards. If you’ve done any coding at all you know what an Event is. They are pre-wired into all the UI elements you use: Like Button.Click or TextBox.TextChanged. Certainly you’ve also created your own events for your applications: C# is an event-driven, Object-Oriented language after all. If you haven’t created your own events there is a great tutorial over on DreamInCode.net as part of their Learning C# Series. If you don’t yet grasp Objects and Classes they have a tutorial for that too. If you’re just starting out in C# you should probably take the time to work through that series so you get a foundation under you before going much further.

When to use each.

The thing about UI element events is… They are meant to be handled at a UI level but many people try to make them something that gets handled in the ViewModel. Don’t be one of those people. UI element event is for UI level handling. If you do something with Button.Click it belongs in the code-behind of that UI (Page or View).

Let’s say you want to take what you learned in the previous lesson about reusable controls to make a customized Entry that… ah… takes only IP addresses with the typical formatting: 192.168.0.100 for example. In that case it might be pretty quick and easy to handle the .TextChanged event of the Entry so you can qualify each character as its entered. After all, at this level you’re dealing with UI, you care about the UI of things, there is no ViewModel, and everything you’re doing is encapsulated within your IPv4input control.

However, if you’re on a page and you want to put a button on the page for… say… I don’t know… Submit form… or Save Changes… Or you are making your own header bar and need a Back button. That isn’t a UI related function, is it? ‘Save changes’ is an instruction to the ViewModel to perform some action. If you tap your Back button you are ordering the app to do navigation. You are giving it a command to do something.

You’ve done this myButton.Click += TheMethodToExecute();
This is a subscription. This subscribes a method to the event. But this means you have to know at design-time what method you want to execute when that button is clicked. There’s the problem with using this for MVVM where the UI doesn’t know about the ViewModel or its methods. Events are limited to one operational context which is generally their own code-behind.

Commands are more… fluid. A command can be assigned and handled with the BindingContext that your View is using at the moment. Change the context, change the handler for the command. Or re-assign the command at run-time.

Make sense? It’s the difference between yelling out a command “Switch to the red brush” not knowing who is supposed to handle it or how, and reaching in to a specific class a can executing the SwitchBrush(Red); method. Because of this ‘just shout it out to whomever is listening’ concept commands are great for multiple ways to activate the same thing. Have you ever noticed how most programs have multiple ways of doing the same thing? If you want to close and save an open document you can choose close from a menu, click the ‘X’ widget on the document window, close the app itself, make a left-to-right swipe gesture, right-click the tab in a multi-tabbed UI… and the list of possibilities goes on. You don’t want to have every one of those options hardwired to a specific method on a specific class. Commands are not so tightly coupled. You really just say “this button raises the CloseCommand” without being tightly tied to any class or method. Leaving your app free to do things like: “This menu calls CloseCommand“, “This button calls CloseCommand“, “This gesture calls CloseCommand etc. Then worry about the actual CloseCommand separately. It’s that buzzword: Separation of Responsibilities

Commands also have one other completely awesome feature: They understand the concept of CanExecute – and that can affect the IsEnabled of a UI control. I’m going to repeat that because it’s a huge feature that everyone seems to miss, not know about, or otherwise just ignore. When the command CanExecute is true all the buttons and menus that are tied to the command are automatically enabled. When the command CanExecute is false all the UI elements are automatically disabled. Let me give you an example and I’m sure you’ve seen this in other apps. Let’s say you are filling out the new user profile form on a page. You have to provide an alias as well as your real name and an email address. At the bottom is the [Submit] button. Notice the submit button is always disabled until you have filled in all the fields on the form. That’s because the button is wired to the SubmitFormCommand, and it has a SubmitFormCommandCanExecute method checking to see if you’ve finished all the requirements. Once you have that CanExecute will return true and the button will magically become enabled all by itself: You do not have to go around micromanaging the IsEnabled state of your button… and the corresponding menu item that does the same thing… and the flick gesture… and the Siri command… You don’t have to micro-manage the .IsEnabled of all those buttons and menus and gestures and keystroke shortcuts if you use commands correctly. Do I have your attention now?

In our PetsViewModel.cs lets create a command for adding a new pet to the Pets collection. This is one of those times where the code does most of the talking:

  1. Add a property for the ICommand
  2. Add a handler for when the Command is exectuted
  3. Add a line assigning a value to the property, that specifies the handler method

In its simplest forms, that’s all there is to a Command. And through the magic of Binding, our UI will update itself automatically: There is no code here that micromanages the UI. If it sounds like I’m harping on this it’s because I am. It can’t be over-stressed that your ViewModels should know nothing about the UI: Its not their role in life.

We have a command. Great. How do we use it? Go back to MainPage.xaml. Find the Grid. Right now Row 0, Column 0 contains the ListView with our Pets. We want to add a button above that to be our New Pet button. There’s a number of ways to do it that are all equally right. This is where your personal style comes in. My choice is to wrap the ListView in a StackLayout, then put the button at the top of the stack. Leaving the StackLayout as the contents of the first column. When you’re done with these changes your MainPage should look like this:

We aren’t changing any of the ListView.ItemTemplate, so I’ve collapsed that for clarity. All you’re doing is wrapping the ListView in a StackLayout, and putting a Button at the top.

Here’s the big take away with this XAML – Notice the button. It does NOT specify what method to execute when it is clicked. Its just raising the command to do something, not micromanaging how to do it. Or where to do it. If you change ViewModels that this UI is binded to at run-time then the command will be run from whatever assignment was made on that ViewModel: Something you can’t do with events.

Let’s take this a step further and create a DeletePetCommand that will take a CommandParameter of the actual Pet to be deleted. We’ll add a delete button to our ListView.ItemTemplate so the user can just tap Delete on the Pet they want to remove. That’s a fairly common use case. Here is what we’re aiming for. Notice the new Delete button on each ListView item.

Adding the new Command to the PetsViewModel.cs shouldn’t look new to you now. Make the property, the method handler then assign them in the constructor.

Flip back to MainPage.xaml. Scroll down to the ViewCell, where we have a StackLayout for properties. Add a Button as the last time in the StackLayout. We’re going to set it to place at the end and expand its space to fill in any empty space. None of that is mysterious.

What does look just a bit interesting is the binding for the button. Sometimes people get confused trying to work out the binding context for each ‘layer’ so we’ll walk through it.

Here’s what’s happening. The button Command is coming from the ViewModel. When you tap the button its going to raise the DeletePetCommand on the ViewModel. That command takes a CommandParameter. Look at the On_DeletePetCommand(object obj) method signature. That parameter is going to receive the CommandParameter we’re passing. We get that from the {Binding .} which is Xamarin syntax for “this element from the collection used as the Source on the ListView.” Your ListView takes a collection of 3 pets. This template is reused for each element. If you click the button on the 2nd item, the CommandParameter with be the actual 2nd item from the collection.

Then what happens when we tap the button?

  • The Pet comes in as the obj parameter.
  • We cast it from a generic object type, to a Pet type.
  • Then we check to make sure it isn’t null (just to be robust and safe), and we check that the Pet being passed to the method is really part of our Pets collection. Again, to be robust and safe. Its easy to imagine 6 months from now when there are 3 other members on your team and someone calls this method from someplace other than the ListView. That’s the point of commands after all, to not be hard coded to just one method of execution. To be safe, we make sure its not null, really is a Pet object type, and really is in our collection.
  • If it passes all those safety checks, then we remove it from the Pets collection. Again, any UI binded to the collection will update automagically.

Hit [F5] and give it a play. Add a new Pet, change its name, delete it, delete an existing pet out of the middle of the List. Cool eh?

 

206 – Reusable controls

Most reusable controls fall into one of two categories: Custom or composite. A custom control is one where you are doing all the low-level work like rendering. Maybe you need a round gauge with a dial like a speedometer. A composite control is control made up of (composed of, get it?) several other controls. Maybe you use a particular arrangement of a border, label and entry in 10 different places on a page as the form someone fills out. Instead of duplicating the markup 10 times you make a composite control then just place 10 of those on the page. Or maybe you’re tired of the limitations of the built-in header on a navigation page. You could make your own header control then place it on the top of all your pages. In WPF these are UserControl. In Xamarin they are ContentView. Getting used to the naming yet? ContentPage is a page of content, generally views. A grouping of views is the ContentView, which you can then put in other ContentViews or a ContentPage.

Composite controls (ContentViews) are really common, or at least should be, and straightforward to make because you’re not having to do any low-level work. Since they are made from existing controls you know they will render on all the supported platforms. Let’s start with an easy one that everyone needs sooner or later: An input control. You see this everywhere, there is a question or hint, and an entry to type in your value. Maybe it’s for your user name, and another for password. Or for registering on a site for your alias, first name, last name, email address, {…}

If you’re at all like me, you’d rather make something one time and use it many times, than to make it many time – then have maintain every instance individually. So much easier to have it defined in one place, even if it does mean an extra 10 minutes on the front end of the project. There’s that theme again: A little work on the front end saves you tons of work in your day-to-day.

Once done with our new InputControl, you’ll be able to add it to any page and bind to its properties just as easily as any other OEM control

We want this to be a versatile control that you can reuse for all sorts of things. Of course, you can go back and add more and more to it over time to suit your needs; but for now what are the basic properties we probably know we’ll need:

  • Caption – That’s the text that tells us what this is for such as “User Name”, “Password” or “Birthday”
  • Value – That the text the user enters. For the sake of consistency with every other control out there we are not giving it a name like ‘user reply’. Every control has a ‘Value’ and that’s what we all look for and expect when we code.
  • Colors for the caption and the value – both foreground and background


Conceptually that’s all there is to it: A constructor and the properties.

BindableProperty

If you come from WPF this is the Xamarin version of a DependencyProperty. A BindableProperty is basically a normal CLR property with a little bit of plumbing that lets you use it for binding in your XAML views.

A CLR property has a public property with a get and set method, backed by a field, usually set to private.

A BindableProperty also has a public method with get and set, and a backer – only the backer is of type BindableProperty and is created with a method that takes a few parameters such as type, parent type and default value, used to do that plumbing we mentioned.

Your turn

Believe it or not you’ve read everything you need to make all the code-behind for this control. You know the name of the control, the properties we want and have an example. So let’s do it.

Right-click on the Controls folder you made. Choose Add|New Item…

Then select a new Forms Xaml View and name it InputCntrl

Don’t worry about the XAML just yet. We need to make the BindableProperties we intend to bind our UI elements to. We already named them:

And you know the syntax:

I’ll give you the first one to copy/paste. You can type out the rest. (They go in InputCntrl.xaml.cs if you didn’t realize that)

       #region Caption (Bindable string)
        public static readonly BindableProperty CaptionProperty = BindableProperty.Create(
                                                                  "Caption", //Public name to use
                                                                  typeof(string), //this type
                                                                  typeof(InputCntrl), //parent type (tihs control)
                                                                  string.Empty); //default value
        public string Caption
        {
            get { return (string)GetValue(CaptionProperty); }
            set { SetValue(CaptionProperty, value); }
        }
        #endregion Caption (Bindable string)

XAML

Now that you have the properties you can use them in your XAML. Open InputCntrl.xaml

BindingContext is everything when it comes to getting things to bind and work right in any MVVM app – WPF or Xamarin. Controls inherit context from the parent control, unless a different context is explicitly assigned. That’s what we need to do here. We need to tell each UI element (label, entry, button etc.) to explicitly look at this control for its context in order to find those BindingProperties we just made. This is one of the rare occasions when we actually give a XAML element a name: When it is going to be referenced by another XAML element within the XAML itself. To the ContentView, add a tag naming the control ‘this’. That’s right. We’re going to keep to the Microsoft naming and have this item refer to itself as ‘this’. It makes all of us comfortable and the code and markup easy to read and follow.

We can now use ‘this’ as a reference source telling the rest of our XAML where to look for properties to bind to.

I’m sure if you study it a bit you’ll see what’s happening, but for the sake of thoroughness let’s break it down.

  • Style – We defined those earlier so we can keep consistent theme throughout our app.
  • HorizontalOptions & HorizontalTextAlignment – Just to be safe we are overriding these from the style. Remember HorizontalOptions is on the label itself; HorizontalTextAlignment is the position of the text within the label (assuming the label is bigger than it needs to be).
  • Text – Ah… the good stuff. We are binding, referencing ‘this’ as our source. Well, ‘this’ is this control that we just named. On that source of ‘this’ we want to take a path to ‘Caption’ – that’s the BindingProperty we made just a bit ago.
  • TextColor – This looks familiar. We just do the same thing, getting the CaptionForeground property we made from ‘this’ control.
  • BackgroundColor – just like the last two.

Let’s do the same with an Entry. Nothing unfamiliar now:

If we stick those two controls in a Grid of two rows we’re pretty much done with our reusable InputCntrl. I do want to point out that nowhere have we tried to micromanage the size of anything. We aren’t forcing the size of the label… We aren’t hardcoding any numbers anywhere. Our control can size itself as needed. Its seems common sense but lots of people trip over this. For some reason (maybe habit) they just have to try to set the size of everything. That just doesn’t work when you don’t know the size of the phone/tablet/laptop/desktop/watch your app is going to be running on.

Let’s put it to use

If we go back to our MainPage.xaml that we are using for testing we can replace the individual label and entry use for the selected pet’s name with a single control that accepts bindings.
• Comment out the label from the first row, first column.
• Then do the same for the entry in the first row, second column.
• Now add an InputControl in that same space, first row, first column, for a column span of 2
• Bind the value of the InputCntl back to the pet’s name property just the same as we had previously done on the individual Entry.

• Save everything
• Hit [F5] and see it on your device.

Here is a screen capture from an Android tablet. Tap on one of the ListView items. Its details appear on the right for editing… Including in our new reusable control.

205 – Base classes

Let’s be lazy efficient – working smarter instead of harder – through inheritance.

If you’ve done any amount of C# or other OOP language, then you know that inheritance is the mechanism of having one or more classes inherit from a base class. By putting as much common functionality in your base class as possible you don’t have to duplicate it in all the inherited classes. If this is a foreign concept to you then stop and pick up a “Learn C# in 30 days” book and work it cover-to-cover
before going any further because you’ll need those foundation concepts.

We’re going to apply the concept of inheritance to our ViewModels by starting with a ViewModelBase… Well… We’re really going to start even smaller, with a ModelBase class. There will be several things that models and ViewModels have in common such as notifying listeners of property changes. So, we might as well put as much common code in the ‘base-est’ class we can. Then our ViewModelBase will inherit from ModelBase

Reminder: Models are our small data bits. Model = Class = blueprint for an instantiated object = All the same thing. If you’re making a phone book it might be an address class or a person class.

Things that do NOT go in the model or base include:

  • The actual saving and loading from database or file. An object should be ignorant of such things. Its up to the storage/database layer to know the mechanisms of this; not the object.
  • Same goes for network updates. Objects don’t know about sending themselves to a server.
  • Anything to do with the UI. An object doesn’t know a darned thing about the display… or if there even is a display.

Shortly after making the solution, we made folders for Controls, Converters and Icons. We might as well make a couple more right now: Models, ViewModels and Pages.

ModelBase.cs

If you didn’t know this about Visual Studio, its fairly smart and will try to do what it thinks you intended. If you select the folder for Models then choose ‘New Class’ from the context menu (keystroke Shift-Alt-C) it will make a new class for you AND put it in that folder AND give it a namespace path to match. RpxOne.Models.ModelBase.cs Do that now.

Doesn’t look like much right now, does it?

What are some of the things we do with objects, that would go well here?

  • Access them from other classes
  • Serialize them (for an xml file, for network upload, for a local database record etc.)
  • Get notification of changes so our app can react – usually by updating the UI, marking the object dirty so we know to save it before closing, etc.

Lets add support for those things

  1. Access from other classes – So we have to make this class Public
  2. Serializable
    1. We mark the class with the [Serializable] attribute
    2. To be serializable a class must have a constructor that takes no parameters. Add one now.
  3. Notifications to other classes. What do our other classes really want to know about?
    1. When a property changes value – so we can update a label for example
    2. When an object is disposed of,
    3. When the contents of a collection changes – So our ListViews can update. Judging by forum questions this is missed by a lot of people. The question usually sounds like:
      “When my page first comes up the ListView has all the items, but when I add or remove items the ListView doesn’t show the changes. What do I have to do to the ListView to get it to update?” The problem isn’t the ListView: It’s the lack of event notifications on the data bound as the source. The ListView is bound to a Collection property. The property raises a PropetyChangedEvent when the entire property is replaced with a new Collection. If you add one item the Collection is not replaced. That’s where the CollectionChangedEvent comes in.

So lets add inheritance for the interfaces that provide these. At this point your code should look about like this…

and have red squiggles under the interface notations because we haven’t added the required methods to support the interfaces. That’s next.

We’re going to need to raise a couple events for when these changes take place:

The next bit will be a little longer, but not bad. We’re going to add all the methods required by those interfaces. Remember I said at the start of this series that we’re going to do more work up front to make our every day, over and over work easier. This is one of those moments. You will make hundreds of properties in most applications. If an extra few minutes in the base class makes dealing with all of those properties just a minute faster you’ve more than made up for the time spent here. If you need to top off your Mt. Dew, now would be a good time. Go ahead… I’ll wait for ya.

INotifyPropertyChanged

Most intro examples around the ‘net show something like OnPropertyChanged(“FirstName”); because it’s easy to read and doesn’t require the setup we’re about to do. As a result even experienced developers continue to do this for years. Here’s the problem: It violates best practices by using ‘magic strings’. So long as the text in the quotes exactly matches the name of the property you’re golden. But if you (or a team mate) refactor the code so the property becomes “NameFirst” but forgets to look around for all those magical strings all the event notification for this property breaks; and you may not see that right away. It could be on a view that only gets shown when the user has two middle names and a hyphenated last name – or some other one in a thousand case that you don’t check every time you do a quick test. Leading to the update getting released. Three days later support gets flooded with calls from mad customers – Usually resulting in you getting calls on the weekend while you’re trying to relax.

We’re going to create a method in the ModelBase that takes an expression instead of a string and uses that to raise the PropertyChangedEvent. Why an expression? Because that’s what the property itself is. We’re going to send the actual property to this method and let it pull out the name for us. If we can send an expression instead of a string it makes our code easier to read, friendlier to changes, find and replace doesn’t break it, and keeps us from goofing up with typos.

For example this
OnPropertyChanged(() => NameFirst);
is more robust for long term use and maintainability than this
OnPropertyChanged(“NameFirst”);
because if you rename the property you don’t have to search for all
the uses of the magic string “NameFirst”… you don’t have typical human mistakes of typing “FirstName”, “Firstname”, “Namefirst”, “NameFrist” etc.


INotifyCollectionChanged

As mentioned earlier, this is so your classes are notified about changes to elements within a collection, and not just when the entire collection as a whole property is set.

Property – IsDirty

Let’s do one other thing to support this: When ever any property is changed let’s mark the object as dirty. For example, when you change the name of a Person, and the Person is automatically marked dirty, without you having to expressly do it every time on every property of every object.


ViewModelBase : ModelBase

Make a new class in the ViewModels folder and call it ViewModelBase. Just like before, it doesn’t look like much to start with. Make it public, inherit from ModelBase, and serializable.

Hit F6 and make sure everything still builds. We’ve done nothing that should have broken our app, but it costs nothing to double check. You can even hit F5 sending it to your device just to make sure you’re still in a good place. You should still see our very simple starting app that looks similar to this, depending on how much you played with styles etc. earlier.

Testing it

So far this is all theoretical until we actually see it in operation and confirm it all works. In a bit we’ll get into the right way to handle commands and navigating to new pages. But we need these to work first. For now we’re going to use the MainPage for a quick test. We’re going to mock up a PetInfo page, ViewModel to back it with, and of course we’ll need a Pet model. When we’re done it will look like this:

Yes, it is ugly. But it also shows us exactly where every element is from page (red), to ListView (fuscia), to each of the 3 elements in the collection (yellow), to each property on the element (black). I tend to do this sort of thing when I am first making a view because honestly it never goes right the first time and if everything has its own color you can see what you have and what you’re missing, to help point you in the right direction. Later you just take the colors out or make them something more attractive.

  • In the Models folder, make a new Pet class inheriting from ModelBase.
  • Give it properties for
    • Name : string
    • Dob : DateTime
    • Coloring : string
  • In the ViewModels folder, make a new PetsViewModel inheriting from ViewModelBase
  • Give it properties for
    • Pets : ObservableCollection
    • SelectedPet : Pet

So we can have some dummy data add a #if DEBUG block in the constructor to add some values:

#if DEBUG
            Pets.Add(new Pet()
            {
                Name = "Fido",
                Coloring = "Tan",
                Dob = new DateTime(1776, 7, 4)
            });
            Pets.Add(new Pet()
            {
                Name = "Snowball",
                Coloring = "White",
                Dob = new DateTime(1968, 7, 20)
            });
            Pets.Add(new Pet()
            {
                Name = "Santa's Little Helper",
                Coloring = "Brown",
                Dob = new DateTime(1989, 4, 12)
            });
            OnPropertyChanged(()=>Pets);
            NotifyPropertyChanged("Pets");
#endif

To your MainPage code behind we are going to add just one property:
MyViewModel : PetsViewModel

        #region MyViewModel (PetsViewModel)
        private PetsViewModel _MyViewModel = new PetsViewModel();
        public PetsViewModel MyViewModel
        {
            [DebuggerStepThrough]
            get
            {
                if (_MyViewModel == null) MyViewModel = new PetsViewModel();
                return _MyViewModel;
            }

            [DebuggerStepThrough]
            set
            {
                if (_MyViewModel == value) return;
                OnPropertyChanging();
                _MyViewModel = value;
                OnPropertyChanged();
            }
        }
        #endregion MyViewModel (PetsViewModel )

NOTE: This is not how to do things in a finished view, but it will suffice to whack out a quick test. It is NOT an example from MVVM best practices. We’ll cover that in a coming lesson.

Next you need to update the MainPage.XAML to build the UI.  Sadly WordPress is terrible at letting me add XAML in the same way as the CSharp blocks.  There is a big screen capture at the end of this page to show you the XAML.

Now run it on your device!

Play:

Tap on one of the pets in the ListView. Their details populate the right side of the display. If you tap on the name or coloring, you can change it AND IT UPDATES IN THE LISTVIEW IN REAL TIME. That’s the magic of binding – no code behind making explicit updates to various UI fields. The models and view models don’t know a thing about the UI.

Select an item then tap on the DOB field – A DatePicker pops up so you can pick a date. Cool eh?

Source Code

I’m not going to provide full code everyplace. I think there is a lot of learning that takes place when you can’t just copy/paste your way to a completed project. Reading, typeing, debugging, watching Intellisense pop up suggestions, is an invaluable learning process that really drives it all into your brain.

But in this case, since this lesson will be the basis of the follow lessons its important to get it right. So just in case I missed anything during my explanation here’s the full code. (Sorry in advance for how WordPress managles some of this and extends the spacing between lines).

ModelBase.cs

using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Xml.Serialization;

namespace RpxOne.Models
{
    [Serializable]
    public class ModelBase : INotifyPropertyChanged,
                             INotifyCollectionChanged,
                             IDisposable
    {
        public ModelBase()
        {
            //Required for serialization
            PropertyChanged += OnPropertyChanged;

        }


        #region Events
        public event NotifyCollectionChangedEventHandler CollectionChanged;
        public event PropertyChangedEventHandler PropertyChanged;
        #endregion Events


        #region Properties
        #region IsDirty
        private bool _IsDirty;
        [XmlIgnore]
        public bool IsDirty
        {
            [DebuggerStepThrough]
            get
            {
                return _IsDirty;
            }

            [DebuggerStepThrough]
            set
            {
                if (_IsDirty == value) return;
                OnPropertyChanging(() => IsDirty);
                _IsDirty = value;
                OnPropertyChanged(() => IsDirty);
            }
        }
        #endregion IsDirty
        #endregion Properties

        #region INotifyPropertyChanged Members
        public static class PropertyHelper
        {
            public static PropertyInfo GetProperty(
                Expression<Func<T, TValue>> selector)
            {
                Expression body = selector;
                if (body is LambdaExpression)
                {
                    body = ((LambdaExpression)body).Body;
                }
                switch (body.NodeType)
                {
                    case ExpressionType.MemberAccess:
                        return (PropertyInfo)((MemberExpression)body).Member;
                    default:
                        throw new InvalidOperationException();
                }
            }
        }
        protected virtual void OnPropertyChanged(Expression e)
        {
            try
            {
                PropertyChangedEventHandler handler = this.PropertyChanged;
                if (handler == null) return;

                // The fully qualified property is really  RpxOne.Models.SomeModel.SomeProperty
                // so we need to strip that down to just the property name.
                var ts = e.ToString();
                var lineage = ts.Split('.');
                if (!lineage.Any()) return;

                var name = lineage[lineage.Length - 1];
                if (name == null) return;

                handler?.Invoke(this, new PropertyChangedEventArgs(name));
            }
            catch (Exception ex)
            {
                //TODO: Log exception
            }
        }
        public void NotifyPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }


        protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            try
            {
                IsDirty = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("Error: {0}", ex.Message));
            }
        }

        #endregion INotifyPropertyChanged Members

        #region INotifyPropertyChanging Members
         public event NotifyCollectionChangedEventHandler PropertyChanging;
        protected virtual void OnPropertyChanging(Expression property)
        {
            //PropertyChangedEventHandler handler = this.PropertyChanged;
            //if (handler != null)
            //    handler(this, property.CreateChangeEventArgs());
        }

        #endregion INotifyPropertyChanging Members

        #region IDisposable Members
        [XmlIgnore]
        private bool _disposed = false;

        ~ModelBase()
        {
            OnDispose(false);
        }

        public void Dispose()
        {
            OnDispose(true);
            GC.SuppressFinalize(this);//Prevent redundant call on an already released object.
            //https://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
        }

        protected virtual void OnDispose(bool disposing)
        {
            string output = String.Format("The Dispose({0}) method.\n", disposing);

            // Execute if resources have not already been disposed.
            if (!_disposed)
            {
                // If the call is from Dispose, free managed resources.
                if (disposing)
                {
                    Console.Error.WriteLine("Disposing of managed resources.");
                    //TODO: Dispose of managed objects
                }
                // Free unmanaged resources.
                output = "Disposing of unmanaged resources.";
                //TODO: Dispose of UNmanaged objects
            }
            _disposed = true;
        }

        #endregion IDisposable Members

        #region OnCollectionChanged Members
        protected virtual void OnCollectionChanged(Expression e)
        {
            var handler = this.CollectionChanged;
            handler?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        OnPropertyChanged(() => e);//If the contents of the property changed, then the property itself changed as far as binding is concerned. But will cause a listview to reload. Uncomment if you are having issues
        }
        #endregion OnCollectionChanged Member

    }
}</code></pre>
<h3>ViewModelBase.cs</h3>
<pre><code class="language=csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RpxOne.ViewModels
{
    [Serializable]
    public class ViewModelBase : Models.ModelBase
    {
        public ViewModelBase()
        {
            
        }
    }
}</code></pre>
<h3>Pet.cs</h3>
<pre><code class="language=csharp">using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace RpxOne.Models
{
    [Serializable]
    public class Pet : ModelBase
    {
        #region Name (string )
        private string _Name;
        [XmlIgnore]
        public string Name
        {
            [DebuggerStepThrough]
            get
            {
                //if (_Name == null) Name = new string();
                return _Name;
            }

            [DebuggerStepThrough]
            set
            {
                if (_Name == value) return;
                OnPropertyChanging(() => Name);
                _Name = value;
                OnPropertyChanged(() => Name);
            }
        }
        #endregion Name (string )


        #region Dob (DateTime )
        private DateTime _Dob;
        [XmlIgnore]
        public DateTime Dob
        {
            [DebuggerStepThrough]
            get
            {
                //if (_Dob == null) Dob = new DateTime();
                return _Dob;
            }

            [DebuggerStepThrough]
            set
            {
                if (_Dob == value) return;
                OnPropertyChanging(() => Dob);
                _Dob = value;
                OnPropertyChanged(() => Dob);
            }
        }
        #endregion Dob (DateTime )


        #region Coloring (string )
        private string _Coloring;
        [XmlIgnore]
        public string Coloring
        {
            [DebuggerStepThrough]
            get
            {
                //if (_Coloring == null) Coloring = new string();
                return _Coloring;
            }

            [DebuggerStepThrough]
            set
            {
                if (_Coloring == value) return;
                OnPropertyChanging(() => Coloring);
                _Coloring = value;
                OnPropertyChanged(() => Coloring);
            }
        }
        #endregion Coloring (string )
    }
}</code></pre>
<h3>PetViewModel.cs</h3>
<pre><code class="language=csharp">using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using RpxOne;
using RpxOne.Models;

namespace RpxOne.ViewModels
{
    public class PetsViewModel : ViewModelBase
    {
        public PetsViewModel()
        {
#if DEBUG
            Pets.Add(new Pet()
            {
                Name = "Fido",
                Coloring = "Tan",
                Dob = new DateTime(1776, 7, 4)
            });
            Pets.Add(new Pet()
            {
                Name = "Snowball",
                Coloring = "White",
                Dob = new DateTime(1968, 7, 20)
            });
            Pets.Add(new Pet()
            {
                Name = "Santa's Little Helper",
                Coloring = "Brown",
                Dob = new DateTime(1989, 4, 12)
            });
            OnPropertyChanged(()=>Pets);
            NotifyPropertyChanged("Pets");
#endif
        }

        #region Pets (ObservableCollection )
        private ObservableCollection _Pets;
        [XmlIgnore]
        public ObservableCollection Pets
        {
            [DebuggerStepThrough]
            get
            {
                if (_Pets == null) Pets = new ObservableCollection();
                return _Pets;
            }

            [DebuggerStepThrough]
            set
            {
                if (_Pets == value) return;
                OnPropertyChanging(() => Pets);
                _Pets = value;
                OnPropertyChanged(() => Pets);
            }
        }
        #endregion Pets (ObservableCollection )


        #region SelectedPet (Pet )
        private Pet _SelectedPet;
        [XmlIgnore]
        public Pet SelectedPet
        {
            [DebuggerStepThrough]
            get
            {
                //if (_SelectedPet == null) SelectedPet = new Pet();
                return _SelectedPet;
            }

            [DebuggerStepThrough]
            set
            {
                if (_SelectedPet == value) return;
                OnPropertyChanging(() => SelectedPet);
                _SelectedPet = value;
                OnPropertyChanged(() => SelectedPet);
            }
        }
        #endregion SelectedPet (Pet )
    }
}</code></pre>
<h3>MainPage.xaml.cs</h3>
<pre><code class="language=csharp">using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using RpxOne.Controls;
using RpxOne.Models;
using RpxOne.ViewModels;
using Xamarin.Forms;

namespace RpxOne
{
    public partial class MainPage : ContentPage
    {
        #region Constructor(s)
        public MainPage()
        {
            InitializeComponent();
        }
        #endregion Constructor(s)


        #region MyViewModel (PetsViewModel)
        private PetsViewModel _MyViewModel = new PetsViewModel();
        public PetsViewModel MyViewModel
        {
            [DebuggerStepThrough]
            get
            {
                if (_MyViewModel == null) MyViewModel = new PetsViewModel();
                return _MyViewModel;
            }

            [DebuggerStepThrough]
            set
            {
                if (_MyViewModel == value) return;
                OnPropertyChanging();
                _MyViewModel = value;
                OnPropertyChanged();
            }
        }
        #endregion MyViewModel (PetsViewModel )
    }
}

MainPage.xaml

Here’s where WordPress really falls down – sorry.  Its hard to present XAML in WordPress because it keeps trying to parse it as part of how the page should be rendered.  Here’s a screenshot of the XAML for making the app page shown above.

mainpage-xaml

401 – Revisiting… MVVM

Revisiting some basics

When I started this series, it was my intent to NOT go over the true basics of C# or coding in general. There are so many good tutorials and books and course etc. out there that I didn’t want to rehash all that great material. I also didn’t want to come off sounding arrogant; like I could cover all that better than others had.

But I also said at the start of this series that I was letting the questions on a couple of forums act as my guide for what was needed and wanted. There’s no point covering material that nobody asks questions about, and a disservice to readers to not cover areas that spawn lots of questions.

MVVM – The fundamental design pattern of XAML/C# applications whether WPF or Xamarin

Understand that this is not a comprehensive tutorial on MVVM. There are lots of those and sever good books on the subject. I am not going to insult those authors by suggesting I can cover their material better. Nor am I going to spend my time rehashing material you can readily get directly from those sources.

However, I keep seeing the same question on forums, or the same bad practices on forums again and again. In the end, I choose to think it’s just a case of not knowing they don’t know what they don’t know.

Tiniest of examples from the 30,000ft view.

Let’s say you’re making an HR page that displays information for an `Employee`. You don’t bind to the page’s code behind. Instead you have a `ViewModel` that has properties and method on it all related to working with Employees. Such a `SelectedEmployee` property, `SaveChanges()` method and so on. An individual `Employee` would be a model.

  • MVVM – Model View ViewModel
  • Model – That’s the Employee. It knows nothing more than the employee data. 90% of the time it knows nothing about how it is formatted, viewed, saved… It’s a pure object representing at thing.
  • ViewModel – That’s a group of properties for working with 1-n instances of your Model. Here you have methods for loading your models, selecting one in particular at a time, maybe properties for other models so you can see both the currently selected `Employee` and their `Schedule` and their `JobDescription`.
  • View – That the page or control for interacting with the ViewModel. It has a drop-down for selecting the employee, and a button for [Save] after you make changes.

You set the `SelectedEmployee` on the ViewModel of the page. So your label will show the `.Name` of that employee (Fred Flintstone). When you change `SelectedEmployee`, the label will show the `.Name` of the new model Employee: (Barney Rubble)

`Label.Text` is bound to `SelectedEmployee.name`
If you change the name, the label updates
If you change the selected employee, the label updates

XAML/C#/MVVM concepts and design

There seem to be a lot of people jumping into Xamarin and cross-platform development that have no background in XAML; that did not migrate to Xamarin from WPF. It seems like people are going from 1998 WinForms, skipping over WPF, and straight into Xamarin because they want to get out of positions where there have been held back and into roles that involve the US$ 3 Billion mobile market. Imagine that.

  • First word of advice: Realize that you were held back and that you are skipping over 10+ years in UI advances and design principals. Your WinForms or other platform-specific design patterns DO NOT APPLY any more.
  • Second word of advice: Do not get offended when people say your skills are out of date. You know they are out of date; that’s why you are aiming at Xamarin.
  • Third bit of advice: Do not try to bring your old ways of doing things into the modern world. Do not think you have to learn JUST new ways of building the user interface. There is an entire design pattern and many foundation concepts to be learned when it comes to XAML/C#/MVVM application architecture. If you take the time to learn first and don’t jump right in to trying to architect/design/build your own application your transition will actually be faster.

If you weren’t aware Microsoft created the XAML markup language. XAML/C#/MVVM has been in use for over 10 years. It is not a new thing just for Xamarin. Therefore, there is a LOT more material out there that is meaningful to you than you may have been aware of. Just about everything you read about WPF design principals and concepts applies to Xamarin, at least in a conceptual way. Understanding the relationship between markup and code, between UI and logic & data is vital to building good Xamarin applications. After all, Xamarin is built on top of all that WPF experience as well as ports of the .NET framework.

Basic concept: Separation of UI and logic.

XAML is used to create the User Interface. C# is used to write the logic. The two are NOT supposed to know about each other and certainly DO NOT DEPEND on each other. Under the XAML/C#/MVVM design concept you have something called BindingContext (Xamarin) or DataContext (WPF). BindingContext is a property that tells your XAML where to look for data properties to bind to. When your UI askes for “.Name” or “.Count” this is the object your UI should look at for those values.

Here’s the idea: Your UI can bind to a class that has data and probably some logic. That class is UI agnostic, meaning it doesn’t know or care about how data is presented or even if it is even presented at all.

Your data class should be quite happy running as the backing of a web REST service, backing a console application, a WPF window or a Xamarin Page… even all the above at the same time. Your data classes should not be doing lots of work or holding lots of properties that exist solely for presentation. Do not keep 3 different versions of the same data collection in different sort orders… do not keep 5 different strings just for variants of the date because they are for short form, long form and UTC. Do NOT code directly to UI elements such as textBox4.Text = “Fred”. All of that presentation-specific stuff can be handled differently and better at the point of presentation.

Your UI markup (the XAML) exists for the sole purpose of presenting data. It is a way for your user to interact with your data but it is not the storage of your data. Do not use the labels and textboxes as the places to store values as so many people did (wrongly) in WinForms and other technologies. The UI presents values by binding properties on UI elements with properties in the BindingContext object. For example: A label’s .Text property can be bound to the .Name property of the data object. If the data object is an employee, then the label shows the employee’s name. If the data object is your dog, then the label shows the dog’s name. The important concept to take away from here is that the data class doesn’t know about the UI, and the UI isn’t depended on a specific data class.

Misconception: UI and logic binding is 1:1

It’s very common to see people coding their logic as if there is a one-to-one relationship to UI. For example an EmployeePage and an EmployeePageViewModel. In real-world applications it’s common for the same ViewModel to be the backing for multiple UI/Forms/Pages. For example an EmployeeObject can be the backing for the EmployeeView of the EmployeePage, SupervisorPage and HrPage. It’s the same employee object with the same data, but the HrPage will be able to show the employee’s salary, while the EmployeePage can show the login password and give the employee the ability to change it, and the SupervisorPage shows the employee’s performance review data.

At the same time the SupervisorPage will show different employees’ data by binding to different employee objects. Every time the supervisor selects a new user from a dropdown for example, that employee object becomes the BindingContext of the page causing a complete change in all the data presented to the new employee. No code is executed when that new employee is selected. The UI updates automatically just by the change in BindingContext object. Do I have your attention now?

Thus the relationship of UI to data object is really n:n not 1:1, and is fluid; changing throughout the run-time of the application and not just a one time ‘set-it-and-forget-it’ operation.

Rules of thumb –

  • XAML controls do not get names 99% of the time. If you’re naming controls on a XAML page (or other sub-view) for any reason other than referencing them from another control in XAML you’re probably doing something wrong.
  • Control events such as Button.Click are not to be used for changing other UI elements. Clicking a button should not change whether or not another control is visible for example. Flipping a switch should not change which image is shown. UI elements are binded to data on a ViewModel. Actions/events in the UI trigger actions in the ViewModel such as ‘ProcessImage’ or ‘SaveRecord’. That action might change one or more properties: Maybe a file name is changed, or a status is updated. Since the UI is binded to the data, when the data updates the UI is updated automatically. So there are 3 indirectly associated relations: A control raises a command – the command executes a method on the VM – the method does some work that may as a side affect update some data – the data is binded to some other UI elements so they get updated.
  • If you are subscribing to UI.event then you’re probably doing something wrong. If you’re doing it only for the purpose of something UI related then it might be okay. Button.Click Entry.TextChanged etc. should only be tied only methods in the code-behind the view and should only affect the view and not anything in the program logic. See where we are going with this? Events on UI elements get handled in the code for the UI. The code in the application logic only affects application data. For example: Lets say you’re making a small control that will be reused throughout your application. It could be

Concept: Commands – The next generation of Event

With XAML-based apps comes the concept of ‘Commands’. Think of them as the next evolution of the Event. Commands are less coupled than events. For example, on an event you have to subscribe directly to that instance.
MyClassInstance.SomeEvent += eventHandlerMethod();
Which most times means you have to know the subscription source/target at design time.

But a command can be referenced just by name, including in your XAML binding. Meaning its more fluid and will bind to your context at RUNTIME.

{06dec2017 lost XAML – I’ll try to replace this ASAP}

Commands can also take Parameters that again, don’t have to be defined at design time. You can send virtually any run-time object along with the command, and let the handler be concerned with how to interpret it. In the example above when the command is raised it will carry with it the SelectedDocument as a parameter. So, while you are clicking a button you are not subscribing to the Button.Click then forced to jump through hoops to handle some specific object. Instead the handler for “AcceptThis” receives the actual document to be accepted. The same command handler can then also be assigned to a menu item… Or ListView selection… Or a network call where a document is downloaded and should then be automatically accepted. All of those other options don’t have to know where the command was defined. All of those other options don’t have to provide the same parameter object.

When you put all that together it means an ‘AcceptThisCommand’ can be bound to a photograph in one case and have a photo processor handle it… and bound to a music file in another case and since the handler is from a different context it will know how to handle that data type.

And without the tight binding that events have you can add a new listener FROM the listener without having to know who/where the command is being raise from. You don’t have to to know that the FileDoneDownloadingCommand is buried deep in ApplicationVM.Media.Handlers.REST.Services.Transfers – You just know that you’re listening for the command to be raised. Later when someone refactors that service moving the command to a much easier to remember location all of the subscribers to don’t break. Making it a far more maintainable architecture.

How does that affect your old-school coding habits?
For one: Stop using Button.Click
It’s a hold-over from WinForms days to make the transition easier that brought old habits into new paradigms. Instead you want to assign a command to your button. Your thinking should be more “What is the purpose of the button?” and less “What method do I execute from the button?” The purpose of the button is to tell your app that something has happened, and less about micromanaging what to do when it happens.

Concept: Converters

XAML apps make heavy use of Converters for presentation purposes. Let’s say you’re building a rocket science program. Your model assumes your rocket speed is measured in meters-per-second. But for your display you’d like to show something more human friendly like Miles per Hour. Instead of making a second property on your data object, or cramming in the match on the data object we’ll make a converter that does this. That way we can re-use the converter in countless places rather than have countless property or numerous duplications of our math.

Now we can use binding to grab the speed off our rocket object and display it as MPH with one line:

{06dec2017 lost XAML – I’ll try to replace this ASAP}

Notice how we even assigned a StringFormat in there to limit the value displayed to only two decimal places. Again, we aren’t creating more properties just for formatting the value. Formatting is just for presentation purposes and has nothing to do with the actual logic of the object so we keep it in the XAML and out of the C#.

204 – App architecture

Let’s take a moment to discuss architecting our app. After all, we don’t want to go racing into the night without a map, at 100 mph screaming “I don’t know where we’re going, but we’re making good time.”

MVVM – The preferred design pattern for C#/XAML applications

As mentioned earlier we will be using a design pattern tailored for C#/XAML and proven with over a decade of use in WPF applications for Windows. This pattern is MVVM: Model, View, ViewModel. I’m not going to make an entire book here for MVVM, but it behooves us to touch on some basic principles so we are all on the same sheet of music as we move forward.

  • Model – That’s an object. An instance of your ‘Monster’ class in a game, or your ‘Animal’ class in a pet tracking app.
  • View – That’s a collection of UI Elements used to visually interact with your data. A view could be an entire page, or it could be a reusable control.
  • ViewModel – That’s the backing data for a view. Commonly it will have several properties that are instances of different models.
    • Let’s cover that just a bit more. The ViewModel for scheduling a work shift would probably have a Permissions property on it that governs what the current user can do. It might also have a Week object that represents the coming week being scheduled. It might have a SelectedWorker property of type Employee representing a given user that the manager might be looking at to see if they can be scheduled for the coming week. And so on. The ViewModel is a collection of properties for a given need.
    • Do not confuse that with ‘this view model is for this page’. That one-to-one relationship is a common mistake. The ViewModel is the properties and methods that go together for a need or purpose. But it can be the backing for many different views. That same ViewModel used by the manager for scheduling a work shift might also be used by the HR person on a similar but different page for scheduling vacation time. Someone in the maintenance department might use the same ScheduleViewModel to see when a machine is out of use for a week so it can be torn down and rebuilt.

In other words: Your page is a view, and it is binded to a ViewModel. When properties on your ViewModel change values, the UI elements on the page are updated and vice versa. The ViewModel is the BindingContext of the view (page).

If that’s all gibberish then check this entry that goes a bit deeper. If that is still gibberish then stop and study:

Despite my disclaimer that a ViewModel and View do not have to have a 1:1 relationship, that doesn’t mean that can’t have it either. In fact, it’s fairly common and there are even several NuGet packages built around navigation based on the idea that if you push a given ViewModel you want a de-facto page to appear. And let’s be honest, the mobile app space is mostly straight-forward programs with a limited purpose in life that tend to not have 50 variations on a page or have 200 different and unrelated functions. So, it’s not unreasonable to say a lot of mobile apps primarily have a one-ViewModel-to-one-Page relationship.

It’s also common to have a hybrid of relationships on one app. For example, your HomePage will probably always be your one and only HomePage: The center of your app where the user always returns to when done with something. Meaning it gets and keeps the same instance of the HomePageViewModel for the lifespan of the app. But you might want your DownloadFilePage to be fresh every time with no memory of the previous file downloaded. When you push a new DownloadFilePage you give it a new DownloadViewModel every time. And the UserViewModel probably backs 10 different views that each handle one aspect of the user: One for changing their password, one for assigning a new avatar image, one for assigning a new social media service to them. The other reason for this regards the built-in Navigation object that we are about to discuss. It has few methods but on is .PopToRoot() meaning clear everything and go back to your first page. If that first page is the Home page your user thinks of as ‘Home’ it makes your life a lot easier than if you push the LoginPage first and have to constantly unwind the Navigation queue to the 2nd or 3rd element.

Let’s keep that one part as a decision about our app: We are going to have a HomePage backed by a HomePageViewModel and they both live for the lifecycle of our app.

Navigation

We have a decision about our home page (architecturally speaking). Now what? Probably navigation. Let’s discuss how navigation works in a mobile app. First when we say ‘navigation’ we aren’t talking about turn-by-turn driving directions. We are talking about internal navigation from one page to another. Most mobile apps are designed around the idea that a cell phone isn’t a bunch of real estate and thus you move from one page with a small dedicated purpose, to another page with a small dedicated purpose. Take a social media app for example. One page is for viewing the current feed of posts. Another page is for setting your preferences. Another page just searches for new friends.

Xamarin.Forms provides a stack-based Navigation queue so developers don’t have to roll their own. This means you push pages on to the navigation stack to move forward to that page, and pop them off to go back. That’s it: Push/forward, Pop/back.

A couple things about The Xamarin site page for Navigation.

  • CarouselPage – This is still experimental, under development, being replaced by (or going to make use of) a CarouselView that you can put on any page, and basically something that nobody is happy with YET. Especially since the CarouselView doesn’t support binding so you can’t bind a collection of pages to it, like anyone would expect. I mean… Really?
  • MasterDetailPage, NavigationPage and TabbedPage – All good choices for a quick start and for your first few projects to get used to building Xamarin-based applications. At some point you’ll probably out grow them when you want to customize beyond what these read-to-go pages support. Maybe you want more control over the look and feel of the Tabs, or to redefine the ‘Hamburger’ menu icon look.
  • ContentPage – The most generic so you have to do more work up front. But also the most versatile since nothing has been done in advance to limit you.

NavigationPage – yes, we mentioned this already. If you look at the NavigationPage it is a page with content below a Navigation bar at the top, the bar has a back button and title etc. You provide a ContentPage as the content that is going below that title bar. Let’s break down the code that does that so we can better comprehend it; versus copy/paste somethis mysterious that ‘just works’ but we don’t know why.

Xamarin.Forms.Application.Current.MainPage =
new NavigationPage(new HomePage());

See that NavigationPage constructor taking another page as an argument? We’re passing in a new HomePage class (derived from ContentPage). Here’s the part I like about the NavigationPage… You can hide the Navigation bar at the top. That means your ContentPage becomes the full screen page with nothing added that you didn’t put there. My control freak enthusiast self likes that. My suggestion for starting out our test app is to use a NavigationPage with our own custom HomePage class. For now, we can keep the Navigation title bar because there is no reason not to and it gives us stuff for free that we can use: Like a standard ‘Back’ button. As we progress and want to customize beyond what it can do, then we will hide the built-in bar and make our own: Without having to change big parts of our underlying infrastructure.

When you create your app one of the early things you do is set the app’s MainPage. MainPage is special term to Xamarin navigation and not a class we make. We’re telling the app “Your Main Page is this: xyzPage”. As we just discussed we’re going to set it to a new NavigationPage and provide one of our ContentPages as the Page to be shown. Let’s look at that code again. At this point both sides of the assignment should make sense.

Xamarin.Forms.Application.Current.MainPage =
new NavigationPage(new HomePage());

I have seen many forum posts where people are having trouble with navigation usually to the effect of “how to go back”. In every one of them the person was not pushing new pages onto the queue. Instead they were using that same line of code: Constantly making the new page the MainPage – Wiping out the navigation queue so there was no history to traverse back. So as a rule, once you have set your HomePage – Leave it. Also, do not think of the HomePage as the first page your user will encounter. Commonly the first page is a Login page… Or maybe it’s a Welcome page… or maybe it’s a splash screen. None of those really fit the name “Home” page though, do they? The HomePage should be just that: The page is that is the central home of the user when they aren’t doing something specific.

The Xamarin site tutorials always show something like this, where you are pushing a new instance of a given page.

async void OnNextPageButtonClicked (object sender, EventArgs e)
await Navigation.PushAsync (new SomeOtherXamlPage());

There are pros and cons to that, that I never see discussed.

  • PRO:
    • You have a clean instance of the page with no old information on it.
    • It’s good for simple tutorials where you don’t want to confuse the reader or have to answer a bunch of questions about “What is an instance?” and why something isn’t working as expected and it later turns out to be two different instances of a page or its ViewModel
    • You’re not holding on to anything so you release memory back to your device and the app.
  • CON:
    • You have a clean instance of the page with no old information on it. Meaning you’ve lost any existing state you might have wanted.
    • Your app has to render the new page instance for the first time everytime, which is visible processing time. Read “visible UI lag”. The more your new page has to calculate to set itself up for the first time, the longer the lag. This is especially true for grabbing images off the device. For example, if your page has to calculate if something should be red or green based on a binding… should something be visible depending on a binding to an enum converter… Do you have 34 icons to read and render…
    • You have to bind the Page to its ViewModel object every time. Or generate a new ViewModel instance. Again, this is clean for one-off examples of navigation but don’t always play into the kind of re-use we have in live application.
    • Basically you’re exchanging memory for performance.

If your page can be rendered once and not thrown away… then re-pushed later… without fear of its state being wrong, then it might be worth keeping your page(s) as properties of your application view model so you can re-use them. One example might be your PreferencesPage. If you have a page where you set up your preferences to English, blue theme, large font, soft volume {…} you know those are going to be the same values the next time the user opens that page. They might open it 10 times in one session because they make an adjustment then try it out, make another adjustment and try it out. If you keep that page you can push it out again and again without having to reload the VM or re-render the page itself, making the UI feel ‘snappy’.

When you have a concern about the page state, such as more data downloaded from a server or the user has logged off and a new user logged in, then you can nullify the existing page instance and make a new instance. This pattern does require a bit more attention to detail on the part of the developer which is probably why it’s not discussed in the intro tutorials by Xamarin. But the boost in responsiveness can be worth it for the moderately experienced developer. If all of that was gibberish don’t panic. It will either become clear when you see it in code, or it is something you’ll dissect & study and grow to understand.

Design flaws to avoid:

  • Doing too much
    • Separation of responsibility is paramount to create coding that can be easily maintained for years. You want your “ReadFile()” method to ONLY read a file. It does not also populate the page, it does not make decisions about what to do next based on the content, it does not perform a NavigationBack when it is done. It reads a file and returns the contents to the caller: That’s it.
    • The same goes for your XAML pages. A page describes where things go. A stack of labels here, 4 com port status controls there, and a button. The page does not define the theme of the app, it does not choose colors, it does not choose font sizes etc. If you put those things on the page, and you have 20 pages, and you decide to re-theme from red to blue… What do you the developer now have to do? You have to scrub through 20 pages and re-colorize everything.
  • Moving too fast
    • Everyone wants to see everything yesterday. Especially bosses. The guy that knows nothing about software development wants to tell you how to develop. That’s never good. Usually it’s something like “Just throw together something that looks good so I can get a screen-shot for approval from the 7th floor. We’ll go back later and make it all better next quarter.” Does anyone ever get the chance to go back and clean up crap from last quarter? NO! So, stand your ground. Don’t call something ‘done’ unless you consider it a work of art that you would sign your name to.
    • If you’re just doing a project for learning you’re the boss. Don’t talk yourself into doing crap just so you can move forward. If some bit of code, you wrote isn’t right… isn’t robust… Fix it. When you move on to the next part you want that last part in your rear-view mirror and not have to return to it later.
  • Don’t bring old ways into new projects
    • If you’ve been a developer since WinForms (or earlier) you have a lot of habits and ways of doing things that have served you well for decades. Most of them are still good. But remember some of those tried-and-true ways of doing things really are DECADES old, and may not apply to second decade of the 21st century hardware, operating systems, and probably not to strategies for cross-platform apps with 90%+ reusable code.
    • Logic doesn’t know anything about the UI
    • We do not use Button.Click()
    • We do not make 15 extra properties just for UI formatting needs. (Because our logic does not know anything about the UI)
  • Your ViewModels knowing too much about each other.
    • Sometimes you need for one ViewModel to know something specific about another. Good or bad is arguable but even the best of pros will say sometimes its unavoidable. But you don’t want everyone to know everything about each other because then you have the same spaghetti and interdependent mess you have with WinForms of the 1990’s.
  • Avoiding work up front often leads to 10x more work later
    • Let’s say you have 10 pages and they all know how to call back to the Application Navigation queue. Seems like a good idea at first: When you click the ‘Settings’ button it pushes the ‘Settings’ page to the top of the queue. It works fine when you start your solution and it’s a small project. Then it grows. And grows. Then you have 40 pages that all do this. Then your boss says “Oh, we need to be able to move forward and backward.” Well… You can’t do that with a stack because you’ve popped off the pages and their gone. Now you have to make your own navigation scheme. Wait for it… Then you realize you have 40 pages that all make their own calls to the built-in scheme all over the place. Oh crap…
    • This is where abstracting away some things is good. If you had built a NavigationLayer class and given it the “PushPage” and “PopPage” methods that did nothing more than call the build-in queue you wouldn’t be looking at working the weekend because you wouldn’t have to change 80 calls. You would just update the methods in your NavigationLayer.
    • The same goes for any major mechanism. If you have 100 direct SQL database calls and the boss says “We’re changing database engines” then you’re crapping your pants. But if you have a DataAccessLayer with methods for “GetRecord” and “SaveRecord” you just have to change engine support in one place.

203 – Now for the left foot

Second step

So far, we’ve managed to get the program created from the default solution templates to build. But we aren’t going to actually to go real far with the project like this. There are things we want to change away from the default and closer to how things need to be for a real app.

There are certain things that are just staples in a XAML/MVVM application so we might as well take care of a little housekeeping now so we can continue to build cleanly and not have to clean up a big mess later. Let’s make some folders in our PCL project. Every project involves making some controls that are going to be reused, so we need a folder for ‘Controls’. This being XAML, we are going to have ‘Converters’. And without some ‘Icons’ our app might be a bit boring.

If you’ve done any reading about Xamarin you already know that each platform project needs its images in a special folder. In Android it’s the ..\Resources\drawable
folder, for example. So, you’re probably wondering why we just made a folder for icons in the PCL project. It’s so we can keep all of our icons in one place, and link references to them in all of the other platform projects. We aren’t going to copy them into the other projects because that just becomes a maintenance problem. Every time the boss says to ‘change the download icon’, you have to be sure to change it in all 5 platforms. In our case, since we will have the actual file in the PCL project and just have reference links in the other projects we only have to change one file in one place one time.

Converters

Let’s touch on converters for just a moment. If you’ve done WPF XAML in the past you should already know what these are. For those that don’t let’s explain something really quick. XAML is a markup language we use to describe our GUI. One of the key concepts is bindings.

  • EX: We bind the text of a label to the string property that holds the value we want to display.
  • We bind the visibility of a control to the bool property that determines if we should see the control. For example, we may not want to even show the [Submit] button on a form until all the entry boxes are filled in.
  • EX: We bind entire views to the currently selected user. If a label is binded to SelectedUser.NameFirst all we have to do is change the SelectedUser and the label will update itself automagically. Consider the implications of that across the entire app. Maybe a given user has poor eyesight. When they log in the theme changes to high contrast and larger type.
  • EX: We bind the volume to the time (through a converter) so the app is only half as loud between 9pm and 8am.
  • With me so far? Well converters are really small reusable classes that do some converting for us for specific purposes. For example, we may want to show a button only when some property is false instead of true. We can’t bind directly to that property, right? And making a second property just to show the opposite value would be a mess. So we use a BoolInvertConverter. We can attach that any time we want the opposite value.

If you’ve never seen this before don’t panic if it’s a bit vague. We’ll do some of this soon and seeing is understanding.

Styles

Styles are another key concept of XAML that you should have seen if you’ve done WPF. If you’ve done web work and used Cascading Style Sheets then you’ve also got some idea where this is going. A style describes how we want a given type of UI element to look. Maybe we want our normal labels to all be white text, 20 point, vertically centered, horizontally at the start. Well we don’t want to have to put all of that on every label every time so we define a Style for that. And, styles can inherit from other styles making it easy for definitions to exist in just one place.

Activity (we’re doing this in our new solution)

We’re going to define a few styles first so we can apply them to some controls we’re going to build later. If you open the app.xaml file you’ll see a fairly bland document. But you might have guessed just by the name Application.Resources, that within this tag is where you will put all of the resources for the application.

Let’s add in a pair of tags for ResourceDictionary. Then inside of them we are going to add a few font size definitions. We’re going to take advantage of Xamarin’s OnPlatform concept to define different values to different platforms. We do this because of how each platform handles fonts just a little differently.

UPDATE (24aug2017) – OnPlatform is all one word

A couple people have asked about Intellisense popping up a suggestion of “On Platform” with a space.  Ignore that. If you put in a space then it is two key words: On and Platform not OnPlatform – and everything goes sideways quickly after that.

To see this in action we can open the MainPage.xaml and use this on the label provided by the solution template.

What makes this even nicer is that resources can use other resources. Let’s define some sizes and colors then reference those in our styles.

Hopefully you can see where we are headed with this. Once you define the small bits you can then make them part of the medium bits and so on. Once you have defined the LabelStyleSml you can use that as the basis for a LabelStyleMed with nothing more than a change to the font size. Since everything is based on some other resources you can change the entire look of your UI with only a couple changes: Change the primary font color in one place and everything that uses it updates, and everything that use something that use it updates, and everything that uses something that uses something that uses it updates {…} Call it ‘inheritance’. Call it ‘Cascading’. Call it whatever you like; I call it really, really nice.

I’m going to give you the markup for a few resources and styles. Sure you could copy/paste it but I might suggest taking the extra 5 minutes to read it and type it into your solution. That simple act helps drive it into your brain, and gives you some hands-on with your IDE so you can get a feel for it popping up helpful Intellisense suggestions and how it marks what it thinks are errors until you complete your typing.

Once you have these in your solution go back to the MainPage a play a bit. Change the style and re-run the app on your device to actually see it in operation. Play around with it a bit… We’ll wait for ya.

06dec2017 – The move to a new host lost some included code. One of the reasons I like the screen shots. I’ll get this style markup replaced as soon as I can. Sorry for the problem.


<!--?xml version="1.0" encoding="utf-8" ?-->

<!-- Application resource dictionary -->

<!--#region Font Sizes -->
<!--#endregion Font Sizes -->

<!--#region Colors -->
<!--#endregion Colors -->

<!--#region Styles (Labels) -->
<!--#endregion Styles (Labels) -->

202 – Starting on the right foot

*Updated March 2017 for Visual Studio 2017 retail release.

The Foundation

Just like any structure, having a solid foundation is critical. Starting our solution out correctly and implementing good practices from the start makes your day to day life so much easier. For example, it’s a ton easier to plan for your app to be multi-cultural than it is to quickly whack in a bunch of text on all your buttons and labels, then 6 months from now have to go back and retro fit. It’s a lot of man-hours to comb through every line of code to find hard-coded strings and shoehorn in all the infrastructure for being culture aware. But if you do it as you go, with each button you don’t have to ‘go back’ at all.

This isn’t always popular with new developers who are anxious to see something happen. Bosses are often the same way: They need to be shown something doing anything to satisfy their immediate gratification needs. But trust me when I say it’s worth the fight to convince people (including yourself) to work methodically and deliberately, getting these ‘big concepts’ in early so the effort can be distributed to everyone on the project, every day, instead of one or two people for 400 hours at the end of the year.

The big items we talked about for user expectations in today’s app world include:

  1. Cross-Platform
  2. Multi-cultural
  3. Multi-user
  4. Value added features

Items that should go unmentioned, but I’m quickly realizing do have to be mentioned:

  1. Good OOP design
  2. Adherence to MVVM pattern
  3. Good XAML that is smart and dynamic rather than heaping in more and more C#. Meaning use of DataTriggers and ControlTemplates where they were meant to be used.

1 – New Cross-Platform Solution

Don’t be mad that I walk through this a bit even though you you’ve been a developer for years and you know how to make a new solution. There are some details to be aware of.

There are really two types of solutions that could be used: Portable and Shared. You want portable. It is more versatile and suffers less from misc. ‘weirdnesses’. Portable will make the structure you saw earlier with the Portable Class Library (PCL). It is the more widely used solution type. Shared has its place in certain situations where you are sharing classes with other solutions, other teams etc. But if you can’t point to a solid reason where you KNOW this is the type you have to have, then it isn’t.

Visual Studio 2015:

Visual Studio 2017:

With VS2017 this became a two-dialog process in order to walk users through their needs in a more ‘wizard-like’ flow, rather than confuse them with too many options in one dialog.
Step 1: Do you want an app or a library or a UI test?

Step 2: What kind of app? We want a Xamarin.Forms app using PCL for our common (non-platform specific) code.

One final question to answer and you can just blindly click [OK] unless you have some very unusual reason to not target the suggested version:

After a couple minutes the built-in templates will generate this multiple-project solution for you:

VS2017
VS2015

Why are the Windows 8.1 projects missing from VS2017?
Because – Its dead Jim: You get his watch, I’ll grab his tricorder.

Don’t try to execute this yet. I know you want to. Despite having the latest version of the Xamarin plugin already installed in Visual Studio, the project templates may not be up-to-date – Especially if you’re still on VS2015. This is something everyone gripes about on the Xamarin forum, or causes confusion because it’s natural to expect that a new default solution should compile and run out-of-the-box. If it’s any consolation, it’s not as bad as it used to be. There was a while where Xamarin.Forms was version 2.x and 1.x of Xamarin Forms was the default of the project templates.

This might seem odd but… Close the solution. Now open the solution.
In the Solution Explorer pallet, you’ll notice each project going through a (Loading…) phase. I don’t pretend to know exactly what all that entails, but I can tell you that with a brand-new solution something important happens as part of (Loading…) that makes the solution happy enough to not go sideways when we do the next step.

Open the NuGet Manager for the solution. (Right-click on the Solution then choose ‘Manage NuGet Packages for Solution)

It will open to the Installed list. There are important details here that a lot of people overlook. The first is thinking that since this is the installed list, the version seen on the product is the installed version: Its not. Look at the icon for the package and you may notice an up-arrow: That indicates an Update is available. It’s the right hand pane that shows which version is installed to which project. Yes, you can have different package versions in different projects. Sometimes you have to because of compatibility issues.

Next and very important: Notice the dependencies of the package. Xamarin forms dependencies in particular. If you are running Visual Studio 2015 you may still be on Cycle 8 of Xamarin, and may still have Xamarin Forms 2.2.3.180 – The Xamarin.Android.Support.xxx libraries with that version are frozen at 23.3.0. You cannot update past that version.

Choose the ‘Updates’ list. There will be a block of updates Xamarin.Android.xxx.xx, and some others above and some below that block.

Depending on your version of Visual Studio, which workload and options you installed with Visual Studio, updates to the Xamarin extension since this tutorial was written, there could be different packages that need updating. You may not see ‘Universal Windows Platform’ but may see 5 other packages. That’s perfectly normal.

  1. Update the ones above the block, one at a time.
    Wait until the console actually says
    ‘======= Finished =========
  2. Update Xamarin.Forms package
  3. If you are on Xamarin.Forms 2.3.3.180 or lower
    DO NOT MANUALLY UPDATE the Xamarin.Android.Support.xxx packages.
    Ever. It will tell you there are newer versions: They lie! Many of these updates are actually for the older Xamarin.Forms v 1.x family, but they changed the version numbering from 4 places (23.0.1.3) to 3 places (24.2.1) and it screws up the automatic version comparison. When you update the Xamarin.Forms package it knows which versions of dependency packages it needs and will get what it needs.
  4. If you are in Visual Studio 2017 it pre-installed Xamarin.Forms 2.3.3.193 (or later) – or if you updated your VS2015 installation to Cycle 9 and Xamarin.Forms 2.3.3.193 or later – you can install the updates to the Xamarin.Android.xxx.xx packages. Versions 25.1.1 as of this writing.
    But you don’t have to. And maybe don’t want to at this time. We’re just getting set up, so if it ain’t broke don’t fix it. At least get through all the initial setup, running of the program on your device etc. before messing around with these. – If you can’t tell, I’m still a little apprehensive about updating these packages. As of March 2017 (today) these updates are still very new and the long-term benefits and issues to a Xamarin solution have not yet been truly explored by real-world developers (as opposed to the “oh its perfect” hype from Microsoft). So what I’m suggesting is: If you can’t point to a reason just yet for needing these updates, don’t do them just for the sake of doing them.
  5. You will probably get a message at the top of the NuGet manager telling you to restart Visual Studio. Do it. If you don’t get a message saying this, do it anyway, then load the solution.
  6. Clean the solution.
  7. Build each project one at a time starting at the top: The portable project, then Droid, then iOS {…}
    1. If you don’t have a Macintosh build machine, or haven’t set up provisioning etc. that’s fine. We’re not dealing with that right now, just ignore that project: You can even unload that project if you like.
  8. If you have a physical android device that is already set up for debugging
    1. Set the droid project as the default project.
    2. Plug in the device. Visual Studio should show it as the target device.
    3. NOTE: I strongly suggest a physical Android device for development. 8″ Android tablets are cheap. You can get them at Sam’s Club and WalMart for $50. Your cell provider will probably give you one for free when you renew your contract. The Android project is, in my opinion, the best center-line for development. Build and test on this to get all your code and UI working. Later in development you can spend some time doing a tweak to the left for iOS and a tweak to the right for Windows UWP.
    4. WARNING: Ignore what anyone says about Android emulators. They are slow and suck. If you use them just accept that you want to launch the simulator as soon as you start your PC, then go get coffee and a doughnut before you even bother opening Visual Studio and your project. Keep the emulator open as much as possible. You don’t want to shut it down at the end of the day, forcing you to lose another half-hour the next morning. I’ve also recently seen a few threads where people are seeing odd rendering in emulators, having to do with some sort of conflict with their PC graphic cards. It doesn’t do you much good to use an emulator that doesn’t actually show you property WYSIWYG output.
  9. If you don’t have a device and are just doing this on your Windows machine, then we’ll use the UWP project as our default.
    1. Set the UWP project as the default.
    2. Visual Studio will show “Local Machine” as the debug target.
    3. Open the Configuration Manager, and tick on ‘Build’ and ‘Deploy’ for the UWP project.
      Why these aren’t ticked by default is a mystery. Again, if you are on Visual Studio 2017 you may not see the end-of-life project types of Win8
  10. Go ahead and debug the solution. You should get a basic “Welcome to Xamarin!” application.
  11. Congratulate yourself and open another Mt. Dew: You just built and ran your first cross-platform application.

201 – Managing expectations

User Expectations:

We are into the second decade of the 21st century. People don’t want a program that just runs on their desktop PC and expects the user to have 50 hours of training to do one thing. In today’s fast paced, on the go, order-a-Frappuccino-from-your-cell-phone-while-walking-up-to-the-coffee-shop-door-because-we-just-don’t-have-time-to-stand-in-line world, what do people just automatically expect, etc.?

  • Cross-platform. Everything we do has to work on iOS, Android and UWP.
    • More than just work, it has to work intuitively and consistently. Nobody reads manuals. Heck nobody even provides manuals anymore. People expect to open an app and just know how it works and trust that it will keep them from hurting themselves (like not losing 2 hours of work because they didn’t explicitly hit ‘save’ before shutting down).
    • If they’ve used the app on their own iPhone then they expect to be able to grab the boss’s Android phone and be able to show them how it works, with all the same features in the same place. Yet at the same time it should feel like an iPhone app or an Android app to users familiar with the nuances of their devices.
  • Value added features such as social media, mapping, photos. More and more this is just expected. It’s not enough for your app to do its job. The user wants to post about themselves doing whatever it is your app facilitates. If it’s a recipe book program it can’t just show a recipe. It also has to have a built-in cooking timer, camera access (to photo the finished cookie) and Facebook access (to post the recipe along with the photo of the cookie). If it’s an on-line ordering app for a restaurant it also has to have a map/directions feature to guide the user to the restaurant and be the loyalty rewards tracker such as the Starbucks ‘Stars’ rewards or Burger-21 “punches” towards free food. If it’s an app to make labels, then it should also be able to order more label supplies directly from your client’s eStore.
  • Multi-cultural. It should work equally well in English or Klingon or whatever.
  • Multi-user. Mostly for the point of just doing it in our app, but we want to implement some sort of user-based operation and permissions system. If it’s a checkbook app the wife should see her files, the husband his, and the kids their allowance accounts but kids don’t have administrator permissions. If it’s a Point Of Sale app like the Ziosk tablets at TGIFriday etc. then the customer can pay their bill, but not have permission to alter the bill or change prices of dishes.
  • Bug reporting. It’s really nice for the developer if they can get direct reports from the user. It also helps the user feel like their experience and feedback is important. You may have done it with Visual Studio itself; using their bug/feedback reporting system to report a bug and include a screenshot from within the reporting system.
  • Instructions. Don’t laugh, lots of programs get released every day that either have no instructions because the developer just expected everyone would be able to intuitively figure it out, or they have a quickly written text document. I know I just said that nobody reads manuals and I stand by that statement. People do however sometimes need little examples or guides. They won’t take two hours to read a manual cover-to-cover. But they will take 30 seconds to read the single-screen guide on how to use the “make me skinny filter” of a selfie app. Nowadays people expect a nice slide show, or walk-through wizard showing them the overview of where everything is, what that funny squiggly icon means and so on. Maybe your app just needs a semi-transparent overlay pointing out where each button is and what it does, that pops up the first time the app is launched.
    • Proof read. Let your app and instructions sit for a couple days. Then proof read again. Then have someone else read them when you give them your app for testing. It makes you look really sloppy when you can’t even write the instructions for your own app without a bunch of typo’s and wrong words (to/too/two or than/then etc.).

Client Expectations:

You always have a client and stake holders when it comes to your programs. Sometimes the client is yourself, and the stake holders are you and maybe your friends and family if they are also going to receive copies of the app. If you have a full-time job developing, then your client is your employer and the stake holders are the end-users. If you are a freelance developer, then the client is the client that hired you. In the end, the client is the person signing the front of the paycheck and you are just the code monkey signing the back of the check. Meaning, they get whatever they want so you better manage what they want.

Depending on your client you may be granted a lot of latitude, or none at all. They may be reasonable about limitations, or not. But one thing is for sure: They will answer ‘yes’ to everything if you ask “Do you want blahblah?” So don’t offer what you don’t want to code. Clients often expect certain things as just automatically included and you get labeled as a bad developer if you don’t deliver even if it’s never been discussed and not in the contract. For example: Settings. Everyone just assumes there should be a Settings dialog somewhere for the user to pick folder locations and color schemes and who-knows-what-else. Nowadays people seem to just automatically expect social media integration. It’s just sort of “Well, yeah duh… Of course, I thought users would be able to post a Facebook review of our service from the app. Isn’t that just included in every app these days?” So, it’s incumbent on you to ask questions smartly, educate your client, and well define the project. You have to actively managing client expectations.