Switch branches/tags
Nothing to show
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
..
Failed to load latest commit information.
README.md Added Xamarin Live Player enable instructions, fixed formatting Aug 4, 2017

README.md

Getting started building cloud-connected mobile apps in Visual Studio for Mac

Overview

Visual Studio for Mac and Visual Studio Tools for Xamarin enable you to deliver native Android, iOS, and Windows apps, using existing development skills, teams, and code. You can then integrate those apps with backend cloud services powered by Azure App Service.

In this lab you'll use Visual Studio for Mac to create a simple to-do app that makes use of a portable cross-platform library and an Azure App Service backend.

Objectives

  • Create a cross-platform mobile app using Xamarin.Forms
  • Create a mobile backend using Azure App Service
  • Build, deploy, and debug the mobile app

Prerequisites

  • Visual Studio for Mac (https://www.visualstudio.com/vs/visual-studio-mac)
  • An Azure account (sign up for free at https://azure.com/free)
  • If using a physical device, install the Xamarin Live Player from your device's app store
    • Note that Xamarin Live Player is currently in preview and will require you to switch to the Alpha updater channel in Visual Studio for Mac.
    • To enable Xamarin Live Player, click on Preferences in the top menu and find the Enable Xamarin Live Player option under the Projects > Xamarin Live Player (Preview) node.

Intended Audience

This lab is intended for developers who are familiar with C#, although deep experience is not required.

Exercise 1: Getting started building cloud-connected mobile apps in Visual Studio for Mac

Task 1: Creating a cross-platform mobile app

  1. Launch Visual Studio for Mac.

  2. Select File > New Solution.

  3. From the Multiplatform > App category, select the Blank Forms App template. Click Next.

  4. Set the App Name to "MobileCloudLab". Note that you have the option to select specific target platforms and whether to use Shared Code or a Portable Class Library. Leave the defaults and click Next.

  5. Make sure the Project Name is set to "MobileCloudLab" and click Create.

Task 2: Creating an Azure mobile backend with Azure App Services

  1. The Getting Started view should be visible by default. Click Add an Azure Mobile Backend.

  2. Click Add to begin the process of setting up an Azure App Service and configuring the mobile app to connect to it.

  3. As part of the process, relevant NuGet packages will be added to the various projects. In addition to the portable project, you can also add these dependencies to the platform-specific project. Click Continue.

  4. The Microsoft.Azure.Mobile.Client package contains the key functionality required to easily work with the backend being created. It is dependent on a few other packages, so click Accept to agree to the terms for all of them.

  5. Click Accept to accept the terms of the SQLiteStore package.

  6. Now that the client projects have been configured, you'll turn your attention to setting up the Azure service. Click Sign in with your Microsoft account to get started.

    Note: if you already have an account associated with Visual Studio for Mac, you won't see this dialog and your services will show up automatically.

  7. Sign in with your Azure account credentials. Once the account has been authenticated and is loaded with the avatar and Visual Studio license information, close the dialog.

  8. Click New to create a new app service.

  9. You'll need to set App Service Name to a globally unique name, so consider appending your name to "MobileCloudLab", such as "MobileCloudLabJohnDoe" as shown below. You can also configure the subscription, resource group, and service plan settings (such as the F1 - Free pricing). Click Create.

  10. Click OK to begin the provisioning.

  11. Once the service has been provisioned, select it from the list. Note the URL provided in the sample code below. You will need this later to configure the MobileServiceClient in code.

Task 3: Configuring Easy tables in an Azure App Service

  1. Open a browser window to https://portal.azure.com and log in.

  2. Search for the app service you just created and select it when shown.

  3. This lab uses Easy tables, a feature that makes it incredibly easy to set up and integrate with backend table data. Scroll down in the list under the Search box to find Easy tables and select it.

  4. If this is the first time you're configuring this service, you will need to configure it. Click the Need to configure... link to continue.

  5. To use Easy tables you will need a database. Click the You need a database... link to continue.

  6. Click Add to add a data connection.

  7. Ensure the Type is set to SQL Database and click Configure required settings.

  8. Click Create a new database.

  9. Set the Name to "mobilecloudlab" and click Configure required settings.

  10. You may opt here to select an existing server if you have one you want to use. Otherwise, click Create a new server.

  11. Fill out the required fields and click Select. You will not need these settings again in the lab since the Easy Tables data connection will handle everything for you transparently.

  12. Click Pricing tier to select a Pricing tier (such as the Free option) and click Select.

  13. Click to configure the Connection string and click OK. You can use the default name.

  14. Click OK to finish setting up the data connection.

  15. It will take a minute or so for the resources to be created and initialized. Once ready, you will be returned to the mobile app blade.

  16. Click the Need to configure... link. You may need to refresh the browser window for this option to become visible.

  17. Now that you have a data connection, you can check the acknowledgment box and click Initialize App.

  18. Once the app has been initialized, click Add to add a table.

  19. Set the Name to "todoitem" and click OK. Note that you'll be using the default "Allow anonymous access" for all operations, which is okay for the purposes of this lab. However, you will want to consider the options more carefully for a production app.

Task 4: Integrating the mobile app with the cloud service

  1. Leave the browser window open to the portal and return to Visual Studio for Mac.

  2. This solution has three projects: a portable MobileCloudLab project, an Android platform-specific MobileCloudLab.Droid, and a MobileCloudLab.iOS project. The portable project should contain as much functionality as possible so that it can be easily shared across the other platform projects without requiring additional work. However, when there is platform-specific code or functionality required, it can be either put in the portable project within platform checks or added directly to the platform-specific project. The platform-specific projects are also responsible for producing the appropriate output for their respective platforms so that you don't need to worry about those details when developing your business logic and data access in the portable library.

  3. From Solution Explorer, right-click the MobileCloudLab project node and select Add > New File.

  4. From the General category, select the Empty Class template. Set the Name to "TodoItem" and click New.

  5. The TodoItem class will represent the model for this application. It will include the data fields that are sent back and forth to the backend service. Replace the class definition with the code below. It's a simple object with Id, Name, Done, and Version properties. Also note that JsonProperty is used to specify how exactly the property names should be serialized.

    public class TodoItem
    {
        string id;
        string name;
        bool done;
    
        [JsonProperty(PropertyName = "id")]
        public string Id
        {
            get { return id; }
            set { id = value; }
        }
    
        [JsonProperty(PropertyName = "text")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    
        [JsonProperty(PropertyName = "complete")]
        public bool Done
        {
            get { return done; }
            set { done = value; }
        }
    
        [Version]
        public string Version { get; set; }
    }
  6. Since we started with an empty class, there are some compile errors in our pasted code (red squiggles). Right-click one of the JsonProperty attributes to see what Quick Fix options there are from Visual Studio. Click Using Newtonsoft.Json; to add an appropriate using statement to the top of the file.

  7. Do the same for the Version attribute further down. Now there should be no more errors.

  8. Add another file to the MobileCloudLab project.

  9. Name this class TodoItemManager and click New.

  10. The TodoItemManager class will be responsible for managing communication with the backend service. Replace the default body of the TodoItemManager class with the code below. Be sure to update the service URL set in the constructor call to the MobileServiceClient constructor to match the URL of the service you created earlier. The remaining methods provide access to retrieve all open items and a way to insert/update an item.

    static TodoItemManager defaultInstance = new TodoItemManager();
    MobileServiceClient client;
    IMobileServiceTable<TodoItem> todoTable;
    
    private TodoItemManager()
    {
        // TODO: Replace this URL with the URL to the service you created earlier.
        this.client = new MobileServiceClient(
            "https://mobilecloudlabjohndoe.azurewebsites.net");
        this.todoTable = client.GetTable<TodoItem>();
    }
    
    // Managing the to-do items via singleton instance.
    public static TodoItemManager DefaultManager
    {
        get { return defaultInstance; }
        private set { defaultInstance = value; }
    }
    
    // Retrieves all items that have not been completed.
    public async Task<ObservableCollection<TodoItem>> GetTodoItemsAsync()
    {
        IEnumerable<TodoItem> items = await todoTable
            .Where(todoItem => !todoItem.Done)
            .ToEnumerableAsync();
    
        return new ObservableCollection<TodoItem>(items);
    }
    
    // Saves a task by inserting or updating it, depending on whether it's new.
    public async Task SaveTaskAsync(TodoItem item)
    {
        if (item.Id == null)
        {
            await todoTable.InsertAsync(item);
        }
        else
        {
            await todoTable.UpdateAsync(item);
        }
    }
  11. Use the Quick Fix feature from earlier to add using statements for each of the compile errors (red squiggles).

  12. Open MobileCloudLabPage.xaml. This XAML file defines the first (and only) page of our app.

  13. Replace the default Label element with the markup below (inside the outermost ContentPage tags). This XAML defines a UI with a text box at the top for accepting new to-do items, which are added with a + button. The rest of the screen is filled with a list of existing to-do items. Each of those items may be marked as complete using their context behavior. There are also a few outstanding methods the XAML expects to call in its code-behind C# class (OnAdd, OnSelected, and OnComplete).

    <ContentPage.Content>
      <Grid RowSpacing="0">
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto" />
          <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackLayout Grid.Row="0" BackgroundColor="#5ABAFF" Padding="10,30,10,5">
          <Label TextColor="#555555" Text="Mobile Cloud Lab" />
          <Grid>
            <Grid.ColumnDefinitions>
              <ColumnDefinition/>
              <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>
            <Entry x:Name="newItemName" Placeholder="Item name" />
            <StackLayout x:Name="buttonsPanel" Grid.Column="1" Orientation="Horizontal"
              HorizontalOptions="StartAndExpand">
              <Button Text="+" MinimumHeightRequest="30" Clicked="OnAdd" />
            </StackLayout>
          </Grid>
        </StackLayout>
        <ListView x:Name="todoList" ItemSelected="OnSelected" Grid.Row="1">
          <ListView.ItemTemplate>
            <DataTemplate>
              <ViewCell>
                <ViewCell.ContextActions>
                  <MenuItem Clicked="OnComplete" Text="Complete"
                    CommandParameter="{Binding .}"/>
                </ViewCell.ContextActions>
                <StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal"
                  Padding="15,5,0,0">
                  <StackLayout Padding="5,0,0,0" VerticalOptions="StartAndExpand"
                    Orientation="Vertical">
                    <Label Text="{Binding Name}"  />
                  </StackLayout>
                </StackLayout>
              </ViewCell>
            </DataTemplate>
          </ListView.ItemTemplate>
        </ListView>
      </Grid>
    </ContentPage.Content>
  14. Open MobileCloudLabPage.xaml.cs. This is the code-behind class that fulfills imperative initialization and event handlers for the XAML page you just updated.

  15. Replace the body of the MobileCloudLabPage class with the code below. It obtains an instance of the TodoItemManager class and uses it to relay calls from the UI to the backend service. The code should be easy to walk through.

    TodoItemManager manager;
    
    public MobileCloudLabPage()
    {
        InitializeComponent();
        manager = TodoItemManager.DefaultManager;
    }
    
    protected override async void OnAppearing()
    {
        base.OnAppearing();
        await RefreshItems();
    }
    
    async Task AddItem(TodoItem item)
    {
        await manager.SaveTaskAsync(item);
        todoList.ItemsSource = await manager.GetTodoItemsAsync();
    }
    
    async Task CompleteItem(TodoItem item)
    {
        item.Done = true;
        await manager.SaveTaskAsync(item);
        todoList.ItemsSource = await manager.GetTodoItemsAsync();
    }
    
    public async void OnAdd(object sender, EventArgs e)
    {
        var todo = new TodoItem { Name = newItemName.Text };
        await AddItem(todo);
        newItemName.Text = string.Empty;
        newItemName.Unfocus();
    }
    
    public async void OnComplete(object sender, EventArgs e)
    {
        var todo = (sender as MenuItem).CommandParameter as TodoItem;
        await CompleteItem(todo);
    }
    
    private async Task RefreshItems()
    {
        todoList.ItemsSource = await manager.GetTodoItemsAsync();
    }
    
    public void OnSelected(object sender, SelectedItemChangedEventArgs e)
    {
        // prevents background getting highlighted
        todoList.SelectedItem = null;
    }
  16. Use the Quick Fix feature from earlier to add using statements for each of the compile errors (red squiggles).

Task 5: Running and debugging the application

  1. If you have a physical device to test with, select Tools > Manage Devices. If not, skip ahead to the step 5 below to use the default emulator.

  2. Launch Xamarin Live Player on your device and follow the directions to pair it with Visual Studio.

  3. Once your device appears in the Visual Studio pairing dialog, close the dialog.

  4. Your device should now be configured as the deployment target. If not, select it from the dropdown. You may have to change the project right next to the Play button from MobileCloudLab.iOS to MobileCloudLab.Android if you are deploying to an Android phone.

  5. Press F5 to build, deploy, and run the project.

  6. While the app is being deployed, open MobileCloudLabPage.xaml.cs and set a breakpoint on the first line of the AddItem method. You can do this by clicking in the margin next to the line or by setting the cursor on the line and pressing F9.

  7. Once the app loads, type "First item" in the textbox and tap the + button to add it to the list.

  8. The breakpoint will now trigger. Press F10 to step into the method.

  9. You will now be in the SaveTaskAsync method of the TodoItemManager class. You can hover over the item parameter to view its properties.

  10. Press F5 to continue execution.

  11. The app should update with the new item added to the list of to-dos retrieved from the backend cloud service.

  12. Return to the Azure portal browser window.

  13. Click the todoitem table to view its data.

  14. There will now be one record that matches the one added earlier. Note that you didn't even need to worry about the schema-it was all handled for you.

  15. Back in the mobile app, slide the item left and tap Complete to mark the item as completed on iOS. For Android, tap and hold and tap on Complete in the top-right. This will update that item in the backend to have its Completed property set to true.

  16. Return to the portal and click Refresh to see the updated field.

Summary

In this lab, you've learned how to get started developing cloud-connected mobile apps with Visual Studio for Mac. To learn more about creating mobile apps with Xamarin, check out Xamarin University.