Category Archives: Tutorials

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 – https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

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: https://developer.xamarin.com/guides/ios/user_interface/introduction_to_storyboards/

Video walkthrough for iOS – https://www.youtube.com/watch?v=8f2mEmbLv40

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:http://developer.android.com/training/basics/activity-lifecycle/index.html

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));                

StartActivity(intent);

Video walkthrough for Android – https://www.youtube.com/watch?v=R5cR34f19Fk

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

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:

one

two

three

END

Example output:

three

two

one

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 = "";

            while(true)
            {
                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")
                {
                    break;
                }
                else
                {
                    //store the input in the list
                    wordList.Add(input);
                }

            }

            //once the user has entered all of the words they want, we will reverse the list and print it
            wordList.Reverse();

            foreach(string word in wordList)
            {
                Console.WriteLine(word);
            }

        }
    }

[/codesyntax]

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: http://www.math.hawaii.edu/~ramsey/Probability/TwoDice.html

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("-------------------------");
            Console.WriteLine("Rolling dice");

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

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

            //probability
            //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
                        break;

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

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

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

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

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

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

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

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

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

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

            }

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

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);
        }
    }

[/codesyntax]

Which Version of Visual Studio 2013 Do I Need?

One of the confusing things about getting started with a .NET language is figuring out which version of Visual Studio that you need.  Microsoft typically puts out many different versions of the Visual Studio software with each release and they can differ in the types of programs and projects they can create, features, functionality or limitations.  With the current version of Visual Studio 2013, there are five different versions of the main product and three versions of the Express edition so its no wonder that people just getting started or that are looking to upgrade to 2013 feel confused.  Here are the differences so you can determine which version you need.

Visual Studio Express

Visual Studio Express is the free version of the product that is usually released alongside the full version of the product.  Giving a free edition of Visual Studio allows people who want to learn a .NET language an easy way in. Since the Express version is free, it is often pared down and contains less functionality than the full version. Applications created in the Express version can be later maintained in other versions of Visual Studio if you decide to upgrade.

For 2013, there are three versions of Express: Web, Windows, and Windows Desktop.

 

Visual Studio Express Web

The Web version of Express allows you to create ASP.NET and Azure projects as well as other web-based projects like web services or web APIs.  This version is good if you won’t be creating other types of applications and the install will be slimmer since it only has the minimum necessary for these types of projects.

 

Visual Studio Express for Windows

The Windows version of Express allows you to create Windows Phone or Windows Store applications for Windows 8.1.  If you are thinking about getting into the app space, this is the version for you. It has support for HTML, JavaScript, C++, C# and Visual Basic and a built-in device simulator so you can test your apps on various phone and tablet devices.

 

Visual Studio Express for Windows Desktop

The Windows Desktop version is different from the previous version as it allows you to create full Windows desktop applications using Windows Presentation Foundation (XAML), regular Windows Forms or Console applications. If you are targeting the Windows desktop and wanting to make regular Win32 desktop applications, this is the version for you.

 

Visual Studio 2013

The full versions of Visual Studio are of course more powerful since they come with a full-sized price tag. There are five versions of the full product: Ultimate, Premium, Professional Online, Test Professional, and Professional.    All of the full versions of the program also allow you to connect to code collaboration platforms such as Team Foundation Servers (internal and at Visual Studio Online) and Github.

Here is the difference:

Visual Studio Professional Online

The Professional Online edition gives you all the functionality to create applications for Windows Desktop, Azure, Server and Windows Phone but does not include a lot of the functionality of the regular Professional edition. It is also limited when it comes to the number of users that can be connected to a project via Visual Studio Online.  For Professional Online, there is a maximum of 10 users and projects can only be hosted to Team Foundation Server Online and not to an in-house TFS installation.

 

Visual Studio Professional

The professional edition gives you the ability to create all of the project types that are available in all three versions of the Express edition. Windows desktop, Windows phone, Web, etc…It also gives you the ability to create cloud-based applications with Azure and Office integration add-ons.  There is no maximum for the number of users that can be connected to a project via Visual Studio Online.

 

Visual Studio Test Professional

Test Professional gives you a lot of the functionality of the Professional version along with tools for testing and integrating with workflows and collaboration.  The big difference with Test Professional is the lack of project availability. This edition is really for testing and QA personnel and does not include the ability to create projects.  However, if you are wanting a solution to create lab environments, capture requirements, or create and manage test cases, this is the version for you.

 

Visual Studio Premium

Premium is going to give you everything that is in Professional plus integrated testing tools to plan, develop, test and operate applications.   There are features included that allow you to workflow your code through a peer-review process and helps with multitasking and productivity by allowing you to suspend and resume tasks. Code coverage analysis tools and interface tests are also included.

 

Visual Studio Ultimate

Ultimate gives you everything in Professional and Premium as well as extensive testing tools. There is built-in functionality for capturing and reproducing bugs, diagnostic data, and performing web performance and loading testing. A new design interface allows you to create diagrams that validate code and implement architecture.

 

To help better understand all of the differences, here is a comparison chart:

Categories and capabilities Visual Studio 2013 Ultimate with MSDN Visual Studio 2013 Premium with MSDN Visual Studio 2013 Test Professional with MSDN Visual Studio 2013 Professional with MSDN Visual Studio Online Professional
Work in the same IDE to create solutions for the web, desktop, cloud, server, and phone checkmark checkmark checkmark checkmark
Take your apps to the cloud, Windows and Windows Phone Stores with included services as subscription benefits checkmark checkmark checkmark checkmark
Get access to Microsoft platforms and tools past and present, with new releases added all the time, including Visual Studio checkmark checkmark checkmark checkmark
Get access to Microsoft platforms and tools past and present, with new releases added all the time checkmark checkmark checkmark checkmark
Organize and define your test plans with test case management and exploratory testing checkmark checkmark checkmark
Provision and manage virtual lab environments for testing with consistent configurations checkmark checkmark checkmark
Improve code quality with a peer code review workflow within Visual Studio checkmark checkmark
Improve developer productivity when multitasking with task suspend and resume checkmark checkmark
Automate user interface tests to validate application UI checkmark checkmark
Find and manage duplicate code in your code base to improve your architecture checkmark checkmark
Determine how much code is being tested with code coverage analysis checkmark checkmark
Reliably capture and reproduce bugs found during manual and exploratory testing to eliminate “no repro” bugs checkmark
Collect and analyze runtime diagnostic data from production systems checkmark
Perform web performance and load testing checkmark
Design architectural layer diagrams to then validate that code implements the architecture checkmark
Maximum number of users on a Visual Studio Online account Unlimited Unlimited Unlimited Unlimited 10
Host team projects on-premises or in the cloud checkmark checkmark checkmark checkmark Cloud only

 

 

All of these versions can be downloaded from the Visual Studio Download site: http://www.visualstudio.com/downloads/download-visual-studio-vs

If you want to try these out you can get a 90 day free trial from www.visualstudio.com or if you are a student at a school that participates in the Dreamspark program, you can get a free version of the Professional edition at www.dreamspark.com.

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;

}

[/codesyntax]

 

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];

[/codesyntax]

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

Delegates

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);
});

[/codesyntax]

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

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();

[/codesyntax]

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!");
            }
        }
    }
}

[/codesyntax]