Category Archives: Programming

Xamarin.Android – Adding Audio

Adding audio to your applications can take on many forms. This could be a sound-effect for a game, audio that is played on demand, or in the form of a podcast or audiobook.

The Android multimedia framework includes support for playing variety of common media types, so that you can easily integrate audio, video and images into your applications. You can play audio or video from media files stored in your application’s resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection.

Setting Your App Up for Audio

Before starting development on your application using MediaPlayer, make sure your manifest has the appropriate declarations to allow use of related features.

Internet Permission – If you are using MediaPlayer to stream network-based content, your application must request network access.

Wake Lock Permission – If your player application needs to keep the screen from dimming or the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode()methods, you must request this permission.

One of the most important components of the media framework is the MediaPlayer class. An object of this class can fetch, decode, and play both audio and video with minimal setup. It supports several different media sources such as:

  • Local resources
  • Internal URIs, such as one you might obtain from a Content Resolver
  • External URLs (streaming)

Playing Audio with MediaPlayer – Using the built-in MediaPlayer class to play audio, including local audio files and streamed audio files with the AudioTrackclass.

Recording Audio – Using the built-in MediaRecorder class to record audio.

Working with Audio Notifications – Using audio notifications to create well-behaved applications that respond correctly to events (such as incoming phone calls) by suspending or canceling their audio outputs.

Working with Low-Level Audio – Playing audio using the AudioTrack class by writing directly to memory buffers. Recording audio using the AudioRecord class and reading directly from memory buffers.

In addition to stopping the MediaPlayer you want to call the release() method on the object when you are done with the audio to free up resources.

Starting and Stopping Audio

This video will show you how to use the MediaPlayer class to start and stop MP3 audio in your Xamarin Android app.

Xamarin.Android – Creating Lists and Opening the Browser

The ListView Control


Displaying a list is one of the most common design patterns used in mobile applications. This makes the ListView control one of the most important design elements. In this lesson we will look at how to create a list of items in our app using the ListView control.

There is a great tutorial that digs in deeper with ListView controls and setting up custom adapters and layouts here:

A ListView consists of the following parts:

Rows – The visible representation of the data in the list.

Adapter – A non-visual class that binds the data source to the list view.

Fast Scrolling – A handle that lets the user scroll the length of the list.

Section Index – A user interface element that floats over the scrolling rows to indicate where in the list the current rows are located.

There is a great tutorial that digs in deeper with ListView controls and setting up custom adapters and layouts here:

The primary classes:

ListView – user interface element that displays a scrollable collection of rows. On phones it usually uses up the entire screen (in which case, the ListActivity class can be used) or it could be part of a larger layout on phones or tablet devices.

View – a View in Android can be any user interface element, but in the context of a ListView it requires a View to be supplied for each row.

BaseAdapter – Base class for Adapter implementations to bind a ListView to a data source.

ArrayAdapter – Built-in Adapter class that binds an array of strings to a ListView for display. The generic ArrayAdapter<T>does the same for other types.

CursorAdapter – Use CursorAdapter or SimpleCursorAdapter to display data based on an SQLite query.

 Android includes built-in ListActivity and ArrayAdapter classes that you can use without defining any custom layout XML or code. The ListActivity class automatically creates a ListView and exposes a ListAdapter property to supply the row views to display via an adapter. The built-in adapters take a view resource ID as a parameter that gets used for each row. You can use built-in resources such as those in Android.Resource.Layout so you don’t need to write your own.

There is a lot of opportunity for customizing the appearance of the ListView control. Want to learn more? Check out this section –’s_appearance/

Opening the Browser

Android phones have a built-in browser with an intent filter that accepts the intent requests from other apps. To use this you have to have a URI (Uniform Resource Identifier) which is a string that identifies the resource of the Web site.

You may already be familiar with the term URL (Unform Resource Locator) – a URI is a URL with additional information that is needed for gaining access to resources required for posting the page.

We can use what we’ve previously learned about Intents to open the browser window.

Here is the video walk-through for this lesson that shows how to setup a ListView control and launch the browser window.

Xamarin Apps – Input/Output

Gathering User Input

In this lesson, you’ll learn how to gather input from the user and make decisions with that information. You’ll also learn how to display information to the user.

We’re also going to explore the Model-View-Controller pattern, which is present in the design of apps made on the Xamarin platform.

Model-View-Controller (MVC)

If you’re not already familiar with the MVC pattern of application development, let’s start with an overview.

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces on computers. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

You can find a great description of this design pattern here –

MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.

The MVC framework includes the following components:

  • Models. Model objects are the parts of the application that implement the logic for the application’s data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.
  • Views. Views are the components that display the application’s user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Productobject.
  • Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.

The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.

The loose coupling between the three main components of an MVC application also promotes parallel development. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.

Using Navigation in iOS

A Storyboard is a visual representation of the appearance and flow of your application. Xamarin has introduced a Designer to allow Xamarin.iOS applications to take advantage of storyboards, so you can design your application screen visually and access the views, controllers and segues with C# for more control.

I would recommend that you read through the Xamarin documentation on Storyboards, Navigation, and Segues so you are prepared for this tutorial:

Video walkthrough for iOS –

Using Navigation in Xamarin Android Apps

In this section, you’ll learn how to gather input from the user and make decisions with that information. You’ll also learn how to display information to the user. We’ll also look at how to navigate between multiple views in your Android application.

Adding an Activity

In order to add code to the app that will respond when the user clicks the button, we have to add an Activity. Your app can be made up of many activities that happen together or at various times.

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI

As your apps become more complex, you will need to worry about managing the lifecycle of this activities. More information on this topic is here:

While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup).

There are two methods almost all subclasses of Activity will implement:

  • onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
  • onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).

What do you Intend to do?

From the Android documentation:

An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

That’s some engineering speak, right?

So what is an Intent? An Intent is a description of an operation to be performed. An intent allows you to start an activity in another app by describing a simple action you’d like to perform (such as “view a map” or “take a picture”) in an Intent object.

This type of intent is called an implicit intent because it does not specify the app component to start, but instead specifies an action and provides some data with which to perform the action.

An Intent in Xamarin is pretty easy. You create the Intent object, provide any additional information you want to pass to the Intent and call StartActivity to get it kicked off.

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


Video walkthrough for Android –

Congrats! You’ve made your first user input/navigation app!

Getting Started with Xamarin Apps

When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, are the only choice. However, over the past few years, an entire new ecosystem of platforms for building mobile applications has emerged.

Xamarin is unique in this space by offering a single language – C#, class library, and runtime that works across all three mobile platforms of iOS, Android, and Windows Phone (Windows Phone’s native language is already C#), while still compiling native (non-interpreted) applications that are performing well enough even for demanding games.

7NfISSiVrncNyD (1)

Testing Your Apps

If you do not have a device that you can use for testing, you will need to use an emulator and run your applications in the test environment.SJXUroJDAA4O26 (1)

Xamarin Android Player

The Xamarin Android Player relies on virtualization and OpenGL. This means that it cannot run inside virtual machine instances nor can it work over Remote Desktop or VNC. Further system requirements can be found in the guide linked below.

The Xamarin Android Player was developed to provide a superb simulator that will allow developers to concentrate on creating great applications and see them in action as quickly as possible without having to worry about hardware deployment. Here is the installation guide:

Testing iOS Apps

Xamarin mobile applications can be deployed to physical devices via USB for testing and debugging (Xamarin.Mac apps can be tested directly on the development computer; Apple Watch apps are deployed first to the paired iPhone). You will need to be sure that your device is setup for development if you wish to test on it. Here is the guide that can help you get started:

jfmavsirfDZev5 (1)

I know that the different requirements for testing your applications can be tricky so you can check out the guide here for more help:

Don’t be afraid to ask if you have the right setup!

iOS Development Requirements

iOS development with Xamarin requires:

  • A Mac running OS X Yosemite (10.10) or above.
  • Latest version of Xcode and iOS SDK installed from the App Store .

Xamarin.iOS works with any of the following setups:

  • Latest version of Xamarin Studio on a Mac that fits the above specifications.
  • Latest version of Visual Studio Professional or higher on Windows 7 or above, paired with a Mac build host that fits the above specifications. This setup requires a Xamarin Business License or trial.

The Xamarin.iOS OS X Installation guide is available for step-by-step installation instructions

Now that you understand the Xamarin environment and what you need to get started, let’s check out the videos!

 iOS App Development –

Android App Development –

Object Independant Serialization C#.NET

Creating and storing serialized objects in a database is a fairly easy task.  However, the problem comes when you have created serialized objects with one application (or version of an application) and want to deserialize and use them with another.  Usually the error that you get is:

Unable to find assembly 'MyAssembly; Version=1.0.3463.18923;
Culture=neutral; PublicKeyToken=40e3171cc8066fe6'.


Well the issue here is the objects that have been Serialized have a formatter transmits the information required to create an instance of an object of the correct type and version. This information generally includes the full type name and assembly name of the object. The assembly name includes the name, version, and strong name hash of the assembly.  What this ultimately means is that your serialized object data is now tied to the assembly and version that created it.

By default the deserialization process uses this formatter information to recreate the object as the correct type.  What we can do is override what the serialized object says and provide our own assembly information so that we can open our objects in another application.

First what we need is to create some add-ons for the SerializationBinder class that is part of System.Runtime.Serialization

sealed class SerializationHelper :
public override Type BindToType(string assemblyName, string typeName)

What the SerializationBinder class does is allow us to setup the assembly information and find the current object type that we want to deserialize as in this application, as opposed to the one it was created it.

First thing, we create an object of Type to hold the object type that we want to deserialize as

Type typeToDeserialize = null;

The biggest problem I ran into is the way that System.Reflection.Assembly returns assembly information. We can get the full name of the assembly like so

string currentAssembly = Assembly.GetExecutingAssembly().FullName;

Which gives us the fully qualified name of the current assembly, version and culture information. But we don’t need all that.

// In this case we are always using the current assembly
assemblyName = currentAssembly;

int index = typeName.IndexOf(‘.’);
string obj = typeName.Substring(index+1);

index = currentAssembly.IndexOf(‘,’);
currentAssembly = currentAssembly.Substring(0, index);

string objType = currentAssembly + "." + obj;

So here we use a little string magic to extract just the assembly name andjust the object name so that we can concatenate them together into a fully qualified object name that GetType() will understand.

// Get the type using the typeName and assemblyName
typeToDeserialize = Type.GetType(objType);

This will return the CLR loaded manifest information on the object that matches the AssemblyName.Objectname that we provided to GetType. We can then return this information.

return typeToDeserialize;

Ultimately, to make sure that your deserialization process will use this new binding formatter you need to create your binary format binder as a new instance of our SerializationHelper class.

BinaryFormatter myFormat = new BinaryFormatter();

//set up a new binder so that we can maintain assembly freedom between
//serialized objects
myFormat.Binder = new SerializationHelper();

This way, when the myFormat.Deserialize() is called, the SerializationHelper class and our new overriden method will fire, causing the assembly information to be changed to the current running assembly, allowing you to deserialize objects that your current application (or version of the same application) did not create.

Programming Challenge: Reverse Input

This week’s programming challenge is about Strings!  String is a great C# class with a lot of built-in functionality for manipulating characters and text.

Write a program that reads a string from standard console input and then prints it in reverse order on the screen.

To spice this up, allow the program to take in a number of strings and reverse the whole thing before printing it.  The console should know that the program is done when it encounters the word END.

Example input:





Example output:




See if you can write this program before I post the solution on Friday.

[codesyntax lang=”csharp” title=”Solution” blockstate=”collapsed”]

class Program
        static void Main(string[] args)
            //create a List that allows you to hold the input strings
            List<String> wordList = new List<string>();

            //get the word input from the user until they tell us there are no more words
            string input = "";

                Console.WriteLine("Please enter the word you wish to store or END to quit");

                //get the string from the user
                input = Console.ReadLine();

                //test the input to make sure its not the word END
                if(input == "END")
                    //store the input in the list


            //once the user has entered all of the words they want, we will reverse the list and print it

            foreach(string word in wordList)



Programming Challenge – Roll the Dice

Write a program which simulates two dice with values from 1 to 6. The program takes a single argument which is the number of dice. The output should contain the values of the dice and the probability for this combination to occur. The probability is expressed as a decimal value between 0 and 1 with three decimal points.

How do you find the probability of a dice roll? Check out this explanation:

If you think you have it figured out, post below and email me a link to your source so I can check it out!  I’ll post the solution at the end of the week.


 Post updated with solution below
[codesyntax lang=”csharp” lines_start=”1″ title=”Solution” blockstate=”collapsed]

class Program
        static void Main(string[] args)
            //welcome the user and start the program
            Console.WriteLine("Welcome to the dice probability program");
            Console.WriteLine("Rolling dice");

            //create a new dice object and roll
            Dice newRun = new Dice();

            //display the result of the rolls
            Console.WriteLine("Die 1 rolled a {0}", newRun.Die1);
            Console.WriteLine("Die 2 rolled a {0}", newRun.Die2);

            //Since each die has six sides and the game is played with two dice, there are 36 (6 x 6) combinations 
            //find the total of the two dice
            int total = newRun.Die1 + newRun.Die2;

            double probability = 0;

            //compare the total to the probability out of 36
            switch (total)
                case 2: probability = 1.0 / 36.0; // 1 possible combination of dice 1/36

                case 3: probability = 2.0 / 36.0; // 2 possible combinations of dice 2/36

                case 4: probability = 3.0 / 36.0; // 3 possible combination of dice 3/36

                case 5: probability = 4.0 / 36.0; //4 possible combination of dice 4/36

                case 6: probability = 5.0 / 36.0; //5 possible combination of dice 5/36

                case 7: probability = 6.0 / 36.0; //6 possible combination of dice 6/36

                case 8: probability = 5.0 / 36.0; //5 possible combination of dice 5/36

                case 9: probability = 4.0 / 36.0; //4 possible combination of dice 4/36

                case 10: probability = 3.0 / 36.0; // 3 possible combination of dice 3/36

                case 11: probability = 2.0 / 36.0; // 2 possible combinations of dice 2/36

                case 12: probability = 2.0 / 36.0; // 1 possible combination of dice 1/36


            //output result
            Console.WriteLine("The probability of this roll is {0:F3}", probability);

class Dice
        private int die1;
        private int die2;

        public int Die1
            get { return die1; }
            set { die1 = value; }

        public int Die2
            get { return die2; }
            set { die2 = value; }

        public void Roll()
            //get a random number object we can the use to determine the die face
            Random rand1 = new Random();
            Die1 = rand1.Next(1,6);
            Die2 = rand1.Next(1,6);


Can You Learn to Program?

I don’t believe that everyone has the aptitude to program.

I know that might seem like a strangely bold statement, especially from someone that makes their living teaching people how to program but hear me out.

I think you can agree with me that not everyone is cut out to do everything.

I want to learn how to paint, draw and play the guitar.  I have spent countless hours learning – I have paid for lessons and I have put in a lot of effort.  But do I know how to do any of those things? No.

Why? Because I don’t have the aptitude.

What is aptitude? Aptitude can be defined as having a natural ability or a “fitness” for a task. Aptitude means that you have a competency for a certain kind of task or work. Some of us have the aptitude to be great basketball players because we were born tall.  Some of us can be great runners and participate in 5Ks every weekend because we have good stamina. Some people have the aptitude for mathematics because they were born with strong analytic skills.

So, no – everyone cannot learn how to program just like I cannot learn how to play the guitar.

So how do you know if you have the aptitude or not?

One way to find out is to take tests in areas such as Numerical Reasoning, Logic or Pattern Recognition.  These are all good skills that translate into being able to learn programming languages and concepts faster. You can find some of these tests here:

These tests can help identify whether or not you have some of the necessary skills but they should be considered the end-all voice on whether or not someone is capable of learning how to program.

Some people believe that if you are good at math that you can be a good programmer.  I am almost in this camp but I have to disagree with some of this idea. Most of the programming that you will be doing for a living revolves around business problems. Math isn’t going to help with these but it will help with foundation logic. Since most of the first programming languages were developed by mathematicians, it makes sense that a lot of the same concepts would be applied or borrowed into the concepts used in computer science.  However, being good at math is not a free pass into programming.

Are these tests and scores really going to tell you anything?

In my mind, the only way to find out if you have the aptitude for something is to try it.  Only by trying to learn something, putting in the effort and practicing it are you going to find out if this is something that you like, enjoy, and/or are good at.  Over my years of teaching I have seen all sides of this coin.  Students that want to learn programming so bad but just can’t get it.  I’ve had students that joined the class because someone told them they should and were good at it but hated actually doing it.  I’ve had students think that learning to program was going to be like playing video games and they shy away from it because “its hard” and I’ve had students come in thinking programming was going to be terribly hard and finding it was simple.

What can we learn from this?

Expectations are the common thread between all of these students. Everyone comes into programming expecting something but their expectations do not align with reality they aren’t going to get anywhere. I recommend that you put away what you think programming is going to be like, whether it is easy or hard, whether you are good at it or not and put your butt in the seat.  Do the work. Only then will you know if you can do this.

Sorting Elements in a Object-based Array

Since most C# applications are taking advantage of object-oriented practices, we often end up with arrays of objects instead of simple-types like int.

Let’s imagine, we have a class like this:

[codesyntax lang=”csharp”]

public class Employee
	public string FirstName;
	public string LastName;
	public decimal Salary;
	public int EmpType;




Then we have an application that creates arrays of Employee objects so we can store each instance of the object.  For example:

[codesyntax lang=”csharp”]

Employee[] myList = new Employee[2];


Suppose I want to sort the array by a particular field of Employee?  How could we sort this array of Employee objects by the LastName field?

There are two ways we can accomplish this – delegates and LINQ


A delegate is a special type that references a method.  You can define a parameter list and a return type just like you can in regular methods.  Through this delegate process, we can create a method that sorts the object array by comparison.

[codesyntax lang=”csharp”]

delegate(Employee emp1, Employee emp2)
	return emp1.LastName.CompareTo(emp2.LastName);


The CompareTo method is built-in to the .NET framework and compares two objects of the same type. It will return less than 0 when X < Y, zero when X = Y and greater than 0 when X > Y.


LINQ stands for Language-Integrated Query. It is a feature of the .NET framework and allows you to create queries based on simple patterns and built-in methods.   LINQ has a method OrderBy that is designed to compare and sort two elements.

[codesyntax lang=”csharp”]

var sortedArray = myList.OrderBy(emp => emp.LastName).ToList();


Either of these methods will work when you have an array of objects that need to be sorted by one or more of their elements.  Make sure to let me know if you have questions!

Number Validation Program

Its OK, especially when you are just getting started, to practice learning C# on some smaller code projects.  Don’t underestimate how much you can learn about programming in the console before you move on to more complex tasks.

For this program, we are going to validate a number that the user gives us in a console application. Here are the specifications:

Write a program in console that accepts an Integer value from the user

When you have accepted the value, determine if it is less than or equal to 10.  If so, print the statement: “This value is small”.

If its larger than 10, print the statement: “This value is large”.

If the user enters a number greater than 100, print the statement: “This value is too big!” but don’t print either of the previous statements

Hint: Remember to use Convert.ToInt32 when accepting the integer value from the Console.ReadLine() statement so you can store the incoming value into an integer variable.

Try it out on your own and see if you can get it working. If you get stuck, check the answer below.

[codesyntax lang=”csharp” lines_start=”1″ title=”Solution” blockstate=”collapsed”]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NumberValidation
    class NumberValidationProgram
        static void Main(string[] args)
            //print a welcome statement
            Console.WriteLine("Welcome to the number validation program");
            Console.WriteLine("Please enter a number");

            //accept the number from the console
            int number = Convert.ToInt32(Console.ReadLine());

            //check the number against the validation rules
            if(number <= 10)
                Console.WriteLine("This value is small");
            else if(number > 10 && number <= 100)
                Console.WriteLine("This value is large");
            else if(number > 100)
                Console.WriteLine("This value is too big!");