移植 Windows Phone Silverlight 商務與資料層至 UWPPorting Windows Phone Silverlight business and data layers to UWP

前一個主題是 I/O、裝置與 app 模型的移植The previous topic was Porting for I/O, device, and app model.

UI 的背後是商務與資料層。Behind your UI are your business and data layers. 這些層中的程式碼會呼叫作業系統和 .NET Framework API (例如背景處理、位置、相機、檔案系統、網路及其他資料存取)。The code in these layers calls operating system and .NET Framework APIs (for example, background processing, location, the camera, the file system, network, and other data access). 大多數這些皆可供通用 Windows 平台 (UWP) 應用程式使用,因此您應該能夠一成不變地移植此程式碼中的大部分。The vast majority of those are available to a Universal Windows Platform (UWP) app, so you can expect to be able to port much of this code without change.

非同步方法Asynchronous methods

通用 Windows 平台 (UWP) 的其中一個優先考量,是讓您建置能真正一致地回應的應用程式。One of the priorities of the Universal Windows Platform (UWP) is to enable you to build apps that are truly, and consistently, responsive. 動畫永遠流暢,並且觸控互動 (例如移動瀏覽和撥動) 即時而無延遲,感覺起來 UI 就像是黏附著手指一樣。Animations are always smooth, and touch interactions such as panning and swiping are instantaneous and free of lag, making it feel like the UI is glued to your finger. 為了達到這個目的,任何無法保證在 50 毫秒內完成的 UWP API 皆已被設為非同步,並且其名稱後面會加上 AsyncTo achieve this, any UWP API that can't guarantee to complete within 50ms has been made asynchronous and its name suffixed with Async. 您的 UI 執行緒將會從呼叫 Async 方法立即返回,而工作則會在另一個執行緒上執行。Your UI thread will return immediately from calling an Async method, and the work will take place on another thread. 在語法上,藉由使用 C# await 運算子、JavaScript Promise 物件及 C++ 接續,使得取用 Async 方法變得相當簡單Consuming an Async method is made very easy, syntactically, using the C# await operator, JavaScript promise objects, and C++ continuations. (如需詳細資訊,請參閱非同步程式設計)。For more info, see Asynchronous programming.

背景處理Background processing

Windows Phone Silverlight app 可以使用受管理的 ScheduledTaskAgent 物件,以在 app 工作不在前景時執行工作。A Windows Phone Silverlight app can use a managed ScheduledTaskAgent object to perform a task while the app is not in the foreground. UWP app 會使用 BackgroundTaskBuilder 類別,以類似的方式來建立並登錄背景工作。A UWP app uses the BackgroundTaskBuilder class to create and register a background task in a similar way. 您需定義會實作您背景工作之工作的類別。You define a class that implements the work of your background task. 系統會定期執行您的背景工作,藉由呼叫您類別的 Run 方法來執行工作。The system runs your background task periodically, calling the Run method of your class to execute the work. 在 UWP app 中,請記得在 app 套件資訊清單中設定 [背景工作] 宣告。In a UWP app, remember to set the Background Tasks declaration in the app package manifest. 如需詳細資訊,請參閱使用背景工作支援 appFor more info, see Support your app with background tasks.

若要在背景傳輸大量資料檔案,Windows Phone Silverlight app 會使用 BackgroundTransferService 類別。To transfer large data files in the background, a Windows Phone Silverlight app uses the BackgroundTransferService class. UWP app 會在 Windows.Networking.BackgroundTransfer 命名空間中使用 API 來執行這個動作。A UWP app uses APIs in the Windows.Networking.BackgroundTransfer namespace to do this. 這些功能使用類似的模式來起始傳輸,但新 API 已經改進性能和效能。The features use a similar pattern to initiate transfers, but the new API has improved capabilities and performance. 如需詳細資訊,請參閱在背景傳輸資料For more info, see Transferring data in the background.

Windows Phone Silverlight app 會使用 Microsoft.Phone.BackgroundAudio 命名空間中的受管理類別,以在 app 不在前景時播放音訊。A Windows Phone Silverlight app uses the managed classes in the Microsoft.Phone.BackgroundAudio namespace to play audio while the app is not in the foreground. UWP 使用 Windows Phone 市集 app 模型,請參閱背景音訊背景音訊範例。The UWP uses the Windows Phone Store app model, see Background Audio and the Background audio sample.

雲端服務、網路功能及資料庫Cloud services, networking, and databases

使用 Azure 在雲端裝載資料與應用程式服務是可行的。Hosting data and app services in the cloud is possible using Azure. 請參閱開始使用行動服務See Getting Started with Mobile Services. 針對需要線上和離線資料的解決方案,請參閱:使用行動服務中的離線資料同步For solutions that require both online and offline data see: Using offline data sync in Mobile Services.

UWP 部分支援 System.Net.HttpWebRequest 類別,但是不支援 System.Net.WebClient 類別。The UWP has partial support for the System.Net.HttpWebRequest class, but the System.Net.WebClient class is not supported. 建議的預見替代方案是 Windows.Web.Http.HttpClient 類別 (或者是 System.Net.Http.HttpClient,如果您需要能夠移植到其他支援 .NET 之平台的程式碼)。The recommended, forward-looking alternative is the Windows.Web.Http.HttpClient class (or System.Net.Http.HttpClient if you need your code to be portable to other platforms that support .NET). 這些 API 使用 System.Net.Http.HttpRequestMessage 來代表 HTTP 要求。These APIs use System.Net.Http.HttpRequestMessage to represent an HTTP request.

UWP app 目前沒有內建處理大量資料案例 (如企業營運系統 (LOB) 案例) 的支援。UWP apps do not currently include built-in support for data-intensive scenarios such as line of business (LOB) scenarios. 不過,您可以使用 SQLite 來執行本機異動資料庫服務。However, you can make use SQLite for local transactional database services. 如需詳細資訊,請參閱 SQLiteFor more info, see SQLite.

將絕對 URI (而非相對 URI) 傳遞至 Windows 執行階段類型。Pass absolute URIs, not relative URIs, to Windows Runtime types. 請參閱將 URI 傳送到 Windows 執行階段See Passing a URI to the Windows Runtime.

啟動程式與選擇器Launchers and Choosers

使用「啟動程式」和「選擇器」(可在 Microsoft.Phone.Tasks 命名空間中找到),Windows Phone Silverlight app 便可以與作業系統互動以執行常見的作業,例如撰寫電子郵件、選擇相片,或是與另一個 app 中共用某些類型的資料。With Launchers and Choosers (found in the Microsoft.Phone.Tasks namespace), a Windows Phone Silverlight app can interact with the operating system to perform common operations such as composing an email, choosing a photo, or sharing certain kinds of data with another app. Windows Phone Silverlight 到 Windows 10 命名空間與類別對應主題中搜尋 Microsoft.Phone.Tasks,以尋找對等的 UWP 類型。Search for Microsoft.Phone.Tasks in the topic Windows Phone Silverlight to Windows 10 namespace and class mappings to find the equivalent UWP type. 這些範圍包括從類似的機制 (稱為啟動程式和選擇器),到實作在 app 之間共用資料的協定。These range from similar mechanisms, called launchers and pickers, to implementing a contract for sharing data between apps.

Windows Phone Silverlight 應用程式可被置於休眠狀態,或甚至是被標記起來 (例如使用相片「選擇器」工作時)。A Windows Phone Silverlight app can be put into a dormant state or even tombstoned when using, for example, the photo Chooser task. 使用 FileOpenPicker 類別的同時,UWP app 仍會保持使用中並且執行。A UWP app remains active and running while using the FileOpenPicker class.

賺錢 (試用模式和在 app 內購買)Monetization (trial mode and in-app purchases)

Windows Phone Silverlight app 可以將 UWP CurrentApp 類別用於其大部分的試用模式與 app 內購買功能,因此不需要移植該程式碼。A Windows Phone Silverlight app can use the UWP CurrentApp class for most of its trial mode and in-app purchase functionality, so that code doesn't need to be ported. 但是 Windows Phone Silverlight app 會呼叫 MarketplaceDetailTask.Show 來提供要供購買的 app:But, a Windows Phone Silverlight app calls MarketplaceDetailTask.Show to offer the app for purchase:

    private void Buy()
        MarketplaceDetailTask marketplaceDetailTask = new MarketplaceDetailTask();
        marketplaceDetailTask.ContentType = MarketplaceContentType.Applications;

移植該程式碼以呼叫 UWP RequestAppPurchaseAsync 方法:Port that code to call the UWP RequestAppPurchaseAsync method:

    private async void Buy()
        await Windows.ApplicationModel.Store.CurrentApp.RequestAppPurchaseAsync(false);

如果您有模擬 app 購買和在 app 內購買功能的程式碼以供測試,則您可以移植該程式碼來改用 CurrentAppSimulator 類別。If you have code that simulates your app purchase and in-app purchase features for testing purposes, then you can port that to use the CurrentAppSimulator class instead.

磚或快顯通知更新的通知Notifications for tile or toast updates

通知是 Windows Phone Silverlight 應用程式的推播通知模型延伸。Notifications are an extension of the push notification model for Windows Phone Silverlight apps. 當您從「Windows 推播通知服務」(WNS) 收到通知時,您可以藉由磚更新或快顯通知將資訊顯示到 UI 上。When you receive a notification from the Windows Push Notification Service (WNS), you can surface the info to the UI with a tile update or with a toast. 如需移植您通知功能的 UI 端,請參閱磚和快顯通知For porting the UI side of your notification features, see Tiles and toasts.

如需有關在 UWP app 中使用通知的詳細資料,請參閱傳送快顯通知For more details on the use of notifications in a UWP app, see Sending toast notifications.

如需有關在使用 C++、C# 或 Visual Basic 的 Windows 執行階段應用程式中使用磚、快顯通知、徽章、橫幅以及通知的資訊和教學課程,請參閱使用磚、徽章以及快顯通知For info and tutorials on using tiles, toasts, badges, banners, and notifications in a Windows Runtime app using C++, C#, or Visual Basic, see Working with tiles, badges, and toast notifications.

儲存區 (檔案存取)Storage (file access)

您可以輕鬆移植將應用程式設定以機碼值組方式儲存在隔離儲存區中的 Windows Phone Silverlight 程式碼。Windows Phone Silverlight code that stores app settings as key-value pairs in isolated storage is easily ported. 以下是移植前和移植後的對照範例,首先是 Windows Phone Silverlight 版本:Here is a before-and-after example, first the Windows Phone Silverlight version:

    var propertySet = IsolatedStorageSettings.ApplicationSettings;
    const string key = "favoriteAuthor";
    propertySet[key] = "Charles Dickens";
    string myFavoriteAuthor = propertySet.Contains(key) ? (string)propertySet[key] : "<none>";

和 UWP 對等物件:And the UWP equivalent:

    var propertySet = Windows.Storage.ApplicationData.Current.LocalSettings.Values;
    const string key = "favoriteAuthor";
    propertySet[key] = "Charles Dickens";
    string myFavoriteAuthor = propertySet.ContainsKey(key) ? (string)propertySet[key] : "<none>";

雖然有 Windows.Storage 命名空間子集可供其使用,但是許多 Windows Phone Silverlight app 仍然會使用 IsolatedStorageFile 類別來執行檔案 I/O,因為其受支援的時間較久。Although a subset of the Windows.Storage namespace is available to them, many Windows Phone Silverlight apps perform file i/o with the IsolatedStorageFile class because it has been supported for longer. 假設目前使用 IsolatedStorageFile,以下是寫入和讀取檔案的前後對照範例,首先是 Windows Phone Silverlight 版本:Assuming that IsolatedStorageFile is being used, here's a before-and-after example of writing and reading a file, first the Windows Phone Silverlight version:

    const string filename = "FavoriteAuthor.txt";
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
        using (var streamWriter = new StreamWriter(store.CreateFile(filename)))
            streamWriter.Write("Charles Dickens");
        using (var StreamReader = new StreamReader(store.OpenFile(filename, FileMode.Open, FileAccess.Read)))
            string myFavoriteAuthor = StreamReader.ReadToEnd();

和使用 UWP 的相同功能:And the same functionality using the UWP:

    const string filename = "FavoriteAuthor.txt";
    var store = Windows.Storage.ApplicationData.Current.LocalFolder;
    Windows.Storage.StorageFile file = await store.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);
    await Windows.Storage.FileIO.WriteTextAsync(file, "Charles Dickens");
    file = await store.GetFileAsync(filename);
    string myFavoriteAuthor = await Windows.Storage.FileIO.ReadTextAsync(file);

Windows Phone Silverlight 應用程式對選用的 SD 記憶卡具有唯讀存取權。A Windows Phone Silverlight app has read-only access to the optional SD card. UWP app 擁有 SD 記憶卡的讀寫存取權限。A UWP app has read-write access to the SD card. 如需詳細資訊,請參閱存取 SD 記憶卡For more info, see Access the SD card.

如需有關在 UWP 應用程式中存取相片、音樂與影片檔案的資訊,請參閱音樂、圖片及影片媒體櫃中的檔案和資料夾For info about accessing photos, music, and video files in a UWP app, see Files and folders in the Music, Pictures, and Videos libraries.

如需詳細資訊,請參閱檔案、資料夾和媒體櫃For more info, see Files, folders, and libraries.

下一個主題是尺寸與 UX 的移植The next topic is Porting for form factor and UX.