使用 Azure 创建 Xamarin.Forms 应用Create a Xamarin.Forms app with Azure

概述Overview

本教程说明如何使用作为后端的 Azure 应用服务的移动应用功能,向 Xamarin.Forms 移动应用添加基于云的后端服务。This tutorial shows you how to add a cloud-based back-end service to a Xamarin.Forms mobile app by using the Mobile Apps feature of Azure App Service as the back end. 请创建一个新的移动应用后端和一个简单的待办事项列表 Xamarin.Forms 应用,此应用将应用数据存储在 Azure 中。You create both a new Mobile Apps back end and a simple to-do list Xamarin.Forms app that stores app data in Azure.

只有在完成本教程后,才可学习有关 Xamarin.Forms 的所有其他移动应用教程。Completing this tutorial is a prerequisite for all other Mobile Apps tutorials for Xamarin.Forms.

先决条件Prerequisites

要完成本教程,需要以下各项:To complete this tutorial, you need the following:

  • 有效的 Azure 帐户。An active Azure account. 如果没有帐户,可以注册 Azure 试用版并获取多达 10 个免费的移动应用,即使在试用期结束之后仍可继续使用这些应用。If you don't have an account, you can sign up for an Azure trial and get up to 10 free Mobile Apps that you can keep using even after your trial ends. 有关详细信息,请参阅 Azure 试用版For more information, see Azure Trial.

  • 用于 Xamarin 的 Visual Studio Tools,包含在 Visual Studio 2017 或更高版本或 Visual Studio for Mac 中。Visual Studio Tools for Xamarin, in Visual Studio 2017 or later, or Visual Studio for Mac. 有关说明,请参阅 Xamarin 安装页See the Xamarin installation page for instructions.

  • (可选)若要生成 iOS 应用,必须使用装有 Xcode 9.0 或更高版本的 Mac。(optional) To build an iOS app, a Mac with Xcode 9.0 or later is required. 可以使用 Visual Studio for Mac 来开发 iOS 应用,也可以使用 Visual Studio 2017 或更高版本(前提是 Mac 在网络上可用)。Visual Studio for Mac can be used to develop iOS apps, or Visual Studio 2017 or later can be used (so long as the Mac is available on the network).

创建新的移动应用后端Create a new Mobile Apps back end

  1. 登录到 Azure 门户Sign in to the Azure portal.

  2. 单击“创建资源” 。Click Create a resource.

  3. 在“搜索”框中键入移动应用In the search box, type Mobile Apps.

  4. 在结果列表中,选择“移动应用” ,然后选择“创建” 。In the results list, select Mobile App, and then select Create.

  5. 选择一个唯一应用名称Choose a unique App name. 此名称也将成为应用服务的域名的一部分。This will also be part of the domain name for your App Service.

  6. 为此移动应用选择“订阅” 。Select the Subscription for this mobile app.

  7. 资源组下,选择现有资源组, 创建新组(使用与应用相同的名称)。Under Resource Group, select an existing resource group or create a new one (using the same name as your app).

  8. 单击创建Click Create. 稍等几分钟,等服务部署成功后再继续。Wait a few minutes for the service to be deployed successfully before proceeding. 查看门户标题中的通知(铃铛)图标以获取状态更新。Watch the Notifications (bell) icon in the portal header for status updates.

创建数据库连接并配置客户端和服务器项目Create a database connection and configure the client and server project

  1. 下载以下平台的客户端 SDK 快速入门:Download the client SDK quickstarts for the following platforms:

    iOS (Objective-C)iOS (Objective-C)
    iOS (Swift)iOS (Swift)
    Android (Java)Android (Java)
    Xamarin.iOSXamarin.iOS
    Xamarin.AndroidXamarin.Android
    Xamarin.FormsXamarin.Forms
    CordovaCordova
    Windows (C#)Windows (C#)

    Note

    如果使用 iOS 项目,则需从最新 GitHub 版本中下载“azuresdk-iOS-*.zip”。If you use the iOS project you need to download "azuresdk-iOS-*.zip" from latest GitHub release. MicrosoftAzureMobile.framework 文件解压缩并添加到项目的根目录中。Unzip and add the MicrosoftAzureMobile.framework file to the project's root.

  2. 需要添加数据库连接,或者连接到现有的连接。You will have to add a database connection or connect to an existing connection. 首先,确定是要创建数据存储,还是使用现有的数据存储。First, determine whether you’ll create a data store or use an existing one.

    • 创建新的数据存储:若要创建数据存储,请使用以下快速入门:Create a new data store: If you’re going to create a data store, use the following quickstart:

      快速入门:开始使用 Azure SQL 数据库中的单一数据库Quickstart: Getting started with single databases in Azure SQL Database

    • 现有数据源:若要使用现有的数据库连接,请按以下说明操作Existing data source: Follow the instructions below if you want to use an existing database connection

      1. SQL 数据库连接字符串格式 - Data Source=tcp:{your_SQLServer},{port};Initial Catalog={your_catalogue};User ID={your_username};Password={your_password}SQL Database Connection String format - Data Source=tcp:{your_SQLServer},{port};Initial Catalog={your_catalogue};User ID={your_username};Password={your_password}

        {your_SQLServer} :服务器的名称,此项可以在数据库的概览页中找到,通常采用“server_name.database.chinacloudapi.cn”格式。{your_SQLServer} Name of the server, this can be found in the overview page for your database and is usually in the form of “server_name.database.chinacloudapi.cn”. {port} :通常为 1433。{port} usually 1433. {your_catalogue} :数据库的名称。{your_catalogue} Name of the database. {your_username} :用于访问数据库的用户名。{your_username} User name to access your database. {your_password} :用于访问数据库的密码。{your_password} Password to access your database.

        详细了解 SQL 连接字符串格式Learn more about SQL Connection String format

      2. 移动应用添加连接字符串。可以在应用服务中管理应用程序的连接字符串,方法是使用菜单中的“配置”选项。 Add the connection string to your mobile app In App Service, you can manage connection strings for your application by using the Configuration option in the menu.

        若要添加连接字符串,请执行以下操作:To add a connection string:

        1. 单击“应用程序设置” 选项卡。Click on the Application settings tab.

        2. 单击“[+] 新建连接字符串”。 Click on [+] New connection string.

        3. 需为连接字符串提供“名称”、“值”和“类型”。 You will need to provide Name, Value and Type for your connection string.

        4. 键入 MS_TableConnectionString 作为“名称” Type Name as MS_TableConnectionString

        5. “值”应该是在前面的步骤中生成的连接字符串。Value should be the connecting string you formed in the step before.

        6. 如果向 SQL Azure 数据库添加连接字符串,请在“类型”下选择“SQLAzure”。 If you are adding a connection string to a SQL Azure database choose SQLAzure under type.

  3. Azure 移动应用有适用于 .NET 和 Node.js 后端的 SDK。Azure Mobile Apps has SDKs for .NET and Node.js backends.

    • Node.js backendNode.js backend

      若要使用 Node.js 快速入门应用,请按以下说明操作。If you’re going to use Node.js quickstart app, follow the instructions below.

      1. 在 Azure 门户中转到“简易表”即可看到以下屏幕。 In the Azure portal, go to Easy Tables, you will see this screen.

        Node 简易表

      2. 确保已在“配置”选项卡中添加 SQL 连接字符串。 然后勾选“我已了解此操作会覆盖所有站点内容”框,并单击“创建 TodoItem 表”按钮 。Make sure the SQL connection string is already added in the Configuration tab. Then check the box of I acknowledge that this will overwrite all site contents and click the Create TodoItem table button.

        Node 简易表的“配置”

      3. 在“简易表”中单击“+ 添加”按钮。 In Easy Tables, click the + Add button.

        Node 简易表的“添加”按钮

      4. 创建允许匿名访问的 TodoItem 表。Create a TodoItem table with anonymous access.

        Node 简易表的“添加表”

    • .NET 后端.NET backend

      若要使用 .NET 快速入门应用,请按以下说明操作。If you’re going to use .NET quickstart app, follow the instructions below.

      1. azure-mobile-apps-quickstarts 存储库下载 Azure 移动应用 .NET 服务器项目。Download the Azure Mobile Apps .NET server project from the azure-mobile-apps-quickstarts repository.

      2. 在 Visual Studio 中以本地方式生成 .NET 服务器项目。Build the .NET server project locally in Visual Studio.

      3. 在 Visual Studio 中打开解决方案资源管理器,右键单击 ZUMOAPPNAMEService 项目,单击“发布”, 此时会出现“Publish to App Service”窗口。In Visual Studio, open Solution Explorer, right-click on ZUMOAPPNAMEService project, click Publish, you will see a Publish to App Service window. 如果在 Mac 上工作,请单击此处了解部署应用的其他方式。If you are working on Mac, check out other ways to deploy the app here.

        Visual Studio 发布

      4. 选择“应用服务” 作为发布目标,接着单击“选择现有”,然后单击窗口底部的“发布”按钮。 Select App Service as publish target, then click Select Existing, then click the Publish button at the bottom of the window.

      5. 首先需通过 Azure 订阅登录 Visual Studio。You will need to log into Visual Studio with your Azure subscription first. 选择 SubscriptionResource Group,然后选择应用的名称。Select the Subscription, Resource Group, and then select the name of your app. 准备就绪后,单击“确定”,这样就会将本地的 .NET 服务器项目部署到应用服务后端。 When you are ready, click OK, this will deploy the .NET server project that you have locally into the App Service backend. 部署完成后,系统会在浏览器中将你重定向到 http://{zumoappname}.chinacloudsites.cn/When deployment finishes, you will be redirected to http://{zumoappname}.chinacloudsites.cn/ in the browser.

运行 Xamarin.Forms 解决方案Run the Xamarin.Forms solution

必须使用用于 Xamarin 的 Visual Studio Tools 来打开解决方案,详见 Xamarin 安装说明The Visual Studio Tools for Xamarin are required to open the solution, see the Xamarin installation instructions. 如果该工具已安装,请按以下步骤来下载并打开解决方案:If the tools are already installed, follow these steps to download and open the solution:

Visual Studio(Windows 和 Mac)Visual Studio (Windows and Mac)

  1. 转到 Azure 门户,并导航到已创建的移动应用。Go to the Azure portal and navigate to the mobile app that you created. Overview 边栏选项卡上,查找作为移动应用公共终结点的 URL。On the Overview blade, look for the URL which is the public endpoint for your mobile app. 示例 - 我的应用名称“test123”的站点名将为 https://test123.azurewebsites.netExample - the sitename for my app name "test123" will be https://test123.chinacloudsites.cn.

  2. 打开此文件夹(xamarin.forms/ZUMOAPPNAME)中的文件 Constants.csOpen the file Constants.cs in this folder - xamarin.forms/ZUMOAPPNAME. 应用程序名称为 ZUMOAPPNAMEThe application name is ZUMOAPPNAME.

  3. Constants.cs 类中,将 ZUMOAPPURL 变量替换为上面的公共终结点。In Constants.cs class, replace ZUMOAPPURL variable with public endpoint above.

    public static string ApplicationURL = @"ZUMOAPPURL";

    变为becomes

    public static string ApplicationURL = @"https://test123.chinacloudsites.cn";

  4. 按照下面的说明运行 Android 或 Windows 项目;如果有联网的 Mac 计算机可用,则运行 iOS 项目。Follow the instructions below to run the Android or Windows projects; and if there is a networked Mac computer available, the iOS project.

(可选)运行 Android 项目(Optional) Run the Android project

在本部分,请运行 Xamarin.Android 项目。In this section, you run the Xamarin.Android project. 如果不使用 Android 设备,可以跳过本部分。You can skip this section if you are not working with Android devices.

Visual StudioVisual Studio

  1. 右键单击 Android (Droid) 项目,然后选择“设为启动项目” 。Right-click the Android (Droid) project, and then select Set as StartUp Project.

  2. 在“生成”菜单上,选择“配置管理器” 。On the Build menu, select Configuration Manager.

  3. 在“配置管理器”对话框中,选中 Android 项目旁边的“生成”和“部署”复选框,并确保共享的代码项目已将“生成”框选中 。In the Configuration Manager dialog box, select the Build and Deploy check boxes next to the Android project, and ensure the shared code project has the Build box checked.

  4. 若要生成项目并在 Android 模拟器中启动应用,请按 F5 键或单击“启动”按钮。 To build the project and start the app in an Android emulator, press the F5 key or click the Start button.

Visual Studio for MacVisual Studio for Mac

  1. 右键单击 Android 项目,然后选择“设为启动项目” 。Right-click the Android project, and then select Set As Startup Project.

  2. 若要生成项目,并在 Android 模拟器中启动应用,请选择“运行”菜单,然后选择“开始调试” 。To build the project and start the app in an Android emulator, select the Run menu, then Start Debugging.

在应用中键入有意义的文本(例如“Learn Xamarin” ),然后选择加号 (+ )。In the app, type meaningful text, such as Learn Xamarin, and then select the plus sign (+).

Android 待办事项应用

此操作向在 Azure 中托管的新移动应用后端发送 post 请求。This action sends a post request to the new Mobile Apps back end that's hosted in Azure. 来自请求的数据插入到 TodoItem 表。Data from the request is inserted into the TodoItem table. 存储在表中的项由移动应用后端返回,数据显示在列表中。Items that are stored in the table are returned by the Mobile Apps back end, and the data is displayed in the list.

Note

用于访问移动应用后端的代码位于解决方案的共享代码项目的 TodoItemManager.cs C# 文件中。The code that accesses your Mobile Apps back end is in the TodoItemManager.cs C# file of the shared code project in the solution.

(可选)运行 iOS 项目(Optional) Run the iOS project

在本部分,请运行适用于 iOS 设备的 Xamarin iOS 项目。In this section, you run the Xamarin.iOS project for iOS devices. 如果不使用 iOS 设备,可以跳过本部分。You can skip this section if you are not working with iOS devices.

Visual StudioVisual Studio

  1. 右键单击 iOS 项目,然后选择“设为启动项目” 。Right-click the iOS project, and then select Set as StartUp Project.

  2. 在“生成”菜单上,选择“配置管理器” 。On the Build menu, select Configuration Manager.

  3. 在“配置管理器”对话框中,选中 iOS 项目旁边的“生成”和“部署”复选框,并确保共享的代码项目已将“生成”框选中 。In the Configuration Manager dialog box, select the Build and Deploy check boxes next to the iOS project, and ensure the shared code project has the Build box checked.

  4. 若要生成项目并在 iPhone 模拟器中启动应用,请选择 F5 键。To build the project and start the app in the iPhone emulator, select the F5 key.

Visual Studio for MacVisual Studio for Mac

  1. 右键单击 iOS 项目,然后选择“设为启动项目” 。Right-click the iOS project, and then select Set As Startup Project.

  2. 在“运行”菜单上,选择“开始调试”以生成项目,并在 iPhone 模拟器中启动应用 。On the Run menu, select Start Debugging to build the project and start the app in the iPhone emulator.

在应用中键入有意义的文本(例如“Learn Xamarin” ),然后选择加号 (+ )。In the app, type meaningful text, such as Learn Xamarin, and then select the plus sign (+).

iOS 待办事项应用

此操作向在 Azure 中托管的新移动应用后端发送 post 请求。This action sends a post request to the new Mobile Apps back end that's hosted in Azure. 来自请求的数据插入到 TodoItem 表。Data from the request is inserted into the TodoItem table. 存储在表中的项由移动应用后端返回,数据显示在列表中。Items that are stored in the table are returned by the Mobile Apps back end, and the data is displayed in the list.

Note

你会发现,用于访问移动应用后端的代码位于解决方案的共享代码项目的 TodoItemManager.cs C# 文件中。You'll find the code that accesses your Mobile Apps back end in the TodoItemManager.cs C# file of the shared code project in the solution.

(可选)运行 Windows 项目(Optional) Run the Windows project

在本部分,请运行适用于 Windows 设备的 Xamarin.Forms 通用 Windows 平台 (UWP) 项目。In this section, you run the Xamarin.Forms Universal Windows Platform (UWP) project for Windows devices. 如果不使用 Windows 设备,可以跳过本部分。You can skip this section if you are not working with Windows devices.

Visual StudioVisual Studio

  1. 右键单击任意 UWP 项目,然后选择“设为启动项目” 。Right-click any the UWP project, and then select Set as StartUp Project.

  2. 在“生成”菜单上,选择“配置管理器” 。On the Build menu, select Configuration Manager.

  3. 在“配置管理器”对话框中,选中所选 Windows 项目旁边的“生成”和“部署”复选框,并确保共享的代码项目已将“生成”框选中 。In the Configuration Manager dialog box, select the Build and Deploy check boxes next to the Windows project that you chose, and ensure the shared code project has the Build box checked.

  4. 若要生成项目并在 Windows 模拟器中启动应用,请按 F5 键或单击“启动”按钮(应该显示为“本地计算机”)。 To build the project and start the app in a Windows emulator, press the F5 key or click the Start button (which should read Local Machine).

Note

Windows 项目不能在 macOS 上运行。The Windows project cannot be run on macOS.

在应用中键入有意义的文本(例如“Learn Xamarin” ),然后选择加号 (+ )。In the app, type meaningful text, such as Learn Xamarin, and then select the plus sign (+).

此操作向在 Azure 中托管的新移动应用后端发送 post 请求。This action sends a post request to the new Mobile Apps back end that's hosted in Azure. 来自请求的数据插入到 TodoItem 表。Data from the request is inserted into the TodoItem table. 存储在表中的项由移动应用后端返回,数据显示在列表中。Items that are stored in the table are returned by the Mobile Apps back end, and the data is displayed in the list.

UWP 待办事项应用

Note

可在解决方案的可移植类库项目的 TodoItemManager.cs C# 文件中找到用于访问移动应用后端的代码。You'll find the code that accesses your Mobile Apps back end in the TodoItemManager.cs C# file of the portable class library project of your solution.

故障排除Troubleshooting

如果在生成解决方案时遇到问题,请运行 NuGet 包管理器并更新到 Xamarin.Forms 的最新版本,然后在 Android 项目中更新 Xamarin.Android 支持包。If you have problems building the solution, run the NuGet package manager and update to the latest version of Xamarin.Forms, and in the Android project, update the Xamarin.Android support packages. 快速入门项目并非始终包含最新版本。Quickstart projects might not always include the latest versions.

请注意,在 Android 项目中引用的所有支持包必须都具有相同的版本。Please note that all the support packages referenced in your Android project must have the same version. 对于 Android 平台,Azure 移动应用 NuGet 包具有 Xamarin.Android.Support.CustomTabs 依赖项,因此,如果你的项目使用较新的支持包,则你需要直接安装具有所需版本的此包以避免冲突。The Azure Mobile Apps NuGet package has Xamarin.Android.Support.CustomTabs dependency for Android platform, so if your project uses newer support packages you need to install this package with required version directly to avoid conflicts.