Create, use, and debug app service (app services) in a UWP app

Source: Internet
Author: User
Tags app service

In Windows 10, Microsoft introduced the new feature of app service (ie, app services) to the UWP to provide inter-application interactivity. Apps that provide app Service are able to receive data from other applications that have passed in parameters for processing.

Create an app service

It's easy to provide app Service with app support. Simply add the service-related code after you configure the app's manifest file correctly.

Configure the app manifest file
    • Open the file in the project Package.appxmanifest .
    • Switch to Declarations tabs.
    • Select in the left Available Declarations App Service and click Add Add it to the Supported Declarations list.
    • Then set the APP Service-related properties on the right.

In general, there are two items that need to be set Name Entry point . Nameis the service name provided by the application, the Entry point entry point, which is the background task class that implements the application service functionality.

You can also manually edit Package.appxmanifest the file to add the APP Service-related configuration:

    • Open the   in the project, package.appxmanifest   file, press  , F7   Switch to code editing mode.
    • found in the manifest file   <applications></applications> node, typically, the node contains only one   <application/>   nodes. (You can also include multiple apps in one app package, but this requires additional permissions, and the general developer doesn't have the right to do so.)
    • in   <application></application> Node continues to find   <extensions></extensions>   Node (if not, add it manually).
    • in   <extensions></extensions>   , add the following code:
<Category= "Windows.appservice"  entrypoint= "entry point">       <name = "Service name"/> </uap: Extension>  
Add app Service Code
    • Adds a Windows Runtime component (Windows Universal) project to the current UWP solution. Note that the project type must be a Windows Runtime component (that is, Windows runtime Component) rather than a class library.
    • Add a reference to the new Windows Runtime component project in the master project of the UWP solution.
    • Add the following code to the Class1.cs file in the new project:
using Windows.ApplicationModel.AppService;   using Windows.ApplicationModel.Background;   using Windows.Foundation.Collections;  
    • Write the IBackgroundTask background task class that implements the interface in the Class1.cs file, assuming we want to provide an App Service that generates a GUID:
 Public Sealed classGuidprovidertask:ibackgroundtask {Privatebackgroundtaskdeferral backgroundtaskdeferral; Privateappserviceconnection appserviceconnection;  Public voidRun (ibackgroundtaskinstance taskinstance) { This. backgroundtaskdeferral =taskinstance.getdeferral (); Taskinstance.canceled+=ontaskcanceled; varDetails = Taskinstance.triggerdetails asappservicetriggerdetails; Appserviceconnection=details.         Appserviceconnection; Appserviceconnection.requestreceived+=onrequestreceived; }     Private Async voidonrequestreceived (appserviceconnection sender, Appservicerequestreceivedeventargs args) {//Get Deferral         varRequestdeferral =args.         Getdeferral (); Try         {             //read messages received by the service             varMessage =args.             Request.message; varresult =NewValueSet (); //detects whether the message contains the contents of the contract             if(Message. ContainsKey ("Requestguid"))             {                 //fill in the generated GUID in the response resultResult. ADD ("GUID", Generateguid ()); }             //Service sends back response results             awaitargs.         Request.sendresponseasync (result); }         Catch(Exception ex) {varresult =NewValueSet (); //write exception to response resultResult. ADD ("Exception", ex); //Service sends back response             awaitargs.         Request.sendresponseasync (result); }         finally         {             //notifies the system that the service has completed its response via deferralRequestdeferral.complete (); }     }     Private voidontaskcanceled (ibackgroundtaskinstance sender, Backgroundtaskcancellationreason reason) {if( This. backgroundtaskdeferral! =NULL)         {             //The Notification Service deferral completed.               This. Backgroundtaskdeferral.complete (); }     }    Private stringGenerateguid () {returnGuid.NewGuid ().    ToString (); }}

The above code is the complete code that implements an APP Service that returns a GUID. Run()called when a background task is created. Because background tasks are Run ended after they are completed, you need to get deferral in your code to keep the background task active in response to requests sent to the service.

OnTaskCanceled()Called when a background task is canceled. There are a number of factors that cause background tasks to be canceled, which may be that the client app is released, the AppServiceConnection client app hangs, the operating system shuts down or goes to sleep, or the operating system does not have sufficient resources to run background tasks.

In the Run method, by taskInstance obtaining AppServiceTriggerDetails . Appservicetriggerdetails represents the details of the App Service trigger. The class contains three properties that can be used to get the service name, the caller package name, and the service connection, that is AppServiceConnecton . The code AppServiceTriggerDetails is established by getting the current call to the service AppServiceConnecton .

Appserviceconnection

The core of implementing APP Service in code is appserviceconnection. AppServiceConnectionclass represents a connection to an APP Service endpoint.

The class consists of two events and four methods:

Event
    • requestreceived The event is triggered when the service receives a request.

    • serviceclosed The event is triggered when the service is closed.

Method
    • Close closes the connection to the service endpoint. This method is used in C++/javascript.

    • Dispose Closes the connection to the service endpoint. This method is used in C#/VB.

    • OpenAsync Open the connection to the service endpoint.

    • Sendmessageasync sends a message to the other end of the service.

Property

AppServiceConnectionThe class also has the following two properties:

    • appservicename Gets or sets the name of the service to connect to.

    • packagefamilyname Gets or sets the PFN (package family name) that contains the app packages for the service.

AppServiceConnectiononce obtained, you can listen RequestReceived to the service request to respond to processing.

In the example code above, the service receives the request, checks whether the request message contains the pre-agreed key "Requestguid", and if it contains the key, generates a GUID and sends back the caller as the result of the response.

Because the method that sends the response result back to the caller Sendresponseasync is an async method, the event-handling method has the OnRequestedReceived async keyword.

To be able to use the Async method normally in the event handling method OnRequestedReceived , you need to get a deferral first. Deferral ensures that the OnRequestedReceived call to the pair will not end before the request message processing is complete. It is important to note that the postback response is independent of the completion of the call, and is not responsible for the completion of the SendResponseAsync OnRequestedReceived notification, SendResponseAsync OnRequestedReceived but rather deferral the method responsible for notifying the client SendMessageAsync has finished processing the event response OnRequestedReceived . ( SendMessageAsync is the method that the client uses to send the request, as detailed below.) )

APP Service uses ValueSet to exchange information. ValueSetthe size of the data that can be passed is determined by the system resource limits. There are no predefined key values in the pass-through ValueSet , and developers need to agree on the key-value agreements required for the service themselves. The client caller must adhere to this protocol construct ValueSet .

When the service end endpoint is closed, the service returns a Appserviceclosedstatus enumeration indicating whether the call to the service was successful. AppServiceClosedStatusFour results may be returned: completion, cancellation, insufficient system resources, and unknown conditions. The server can ValueSet attach detailed state information, such as exception information, to the client caller in response to the result.

Finally, the SendResponseAsync call to the method sends the response back to the client caller.

Hide apps that provide services

Let's say you've developed an application that specializes in providing some kind of service, just want its backend services to provide functionality, and don't want the main program to go through all the programs in the Start menu, simply modify the app's manifest file:

    • Right-click Package.appxmanifest on the Select View Code in the solution browser
    • <uap:VisualElements> Locate <Applications> the node in the open manifest file, and then locate the node. <Application>
    • To <uap:VisualElements> add attributes to a node:
Applistentry = "None"  
Using app Service

For the client app to be able to use the app service provided by the service provider app, you first need to know the PFN package name of the service provider app (Family name).

Get Service Provider App package name

Two ways to get PFN package names are listed on the MSDN documentation:

    • Calls from within the service Delivery application project (for example, from App.xaml.cs within public App() ) Windows.ApplicationModel.Package.Current.Id.FamilyName can be viewed through output to Visual Studio's output window or displayed in the application interface.

    • Deploy the solution ( 生成 > 部署解决方案 ) and note the full package name (>) in the Output window 查看 输出 . Note the full package name is output at deployment time, and you must remove the platform information from the string in the Output window to get the PFN package name. For example, if the full package name is 9fe3058b-3de0-4e05-bea7-84a06f0ee4f0_1.0.0.0_x86__yd7nk54bq29ra rendered in the Output window, it needs to be removed 9fe3058b-3de0-4e05-bea7-84a06f0ee4f0_yd7nk54bq29ra 1.0.0.0_x86__ and left as the required PFN package name.

There is also a simple way to recommend:

    • In the Solution Explorer, double-click the Package.appxmanifest file to open the manifest file designer, switch to the Packaging tab, and view the Package family name values in the column.
Writing a client app that invokes a service

Create a new Windows generic app project as the client Caller app, open the code file that needs to invoke the APP Service, and add the following referenced namespaces at the top of the code:

Using

Suppose our client app needs to get a new GUID from the app Service and display it on a text box, we'll add a button and a text box to the page we're applying and name the text box textBox .

In the background code of the page, declare one AppServiceConnection :

Private Appserviceconnection Guidservice;  

Then add the following code for the button's Click event:

Private Async voidButton_Click (Objectsender, RoutedEventArgs e) {    if(Guidservice = =NULL) {Guidservice=Newappserviceconnection (); Guidservice.appservicename="Guidproviderservice"; Guidservice.packagefamilyname="0e37a0ad-6f9f-41f6-ac5f-ac93c00b9474_21qyshkbc51y2"; varStatus =await  This. Guidservice.openasync (); if(Status! =appserviceconnectionstatus.success) {button. Content="Failed to connect"; return; }    }    varMessage =NewValueSet (); Message. ADD ("Requestguid",NULL); Appserviceresponse Response=await  This. Guidservice.sendmessageasync (message); if(Response. Status = =appserviceresponsestatus.success) {if(Response. Message! =NULL) TextBox.Text= (string) Response. message["GUID"]; }}

The above code is very simple, first check AppServiceConnection whether the instance exists, does not exist to create a new instance. When you create it, you specify the name of the target service and the package name that provides the service app, both of which are consistent with those specified in the manifest file for the service delivery app above.

AppServiceConnectionAfter you create a good instance and set the service name and package name properties, call OpenAsync() the method to open the connection to the service. The method returns a Appserviceconnectionstatus enumeration that indicates the result of opening the connection.

After the connection is successfully established, create ValueSet and fill in a key named in the key requestguid that adheres to the protocol rules defined in the service above. Because the service only checks the key names in this example, the key values do not need to be filled in.

The SendMessageAsync() method is then called to send the previously created ValueSet parameters to the service, and waits for a response. Note that this method is an asynchronous method that requires the await keyword to be carried, so the button's Click event handling code also adds the Async keyword.

The response status sent back by the server can be detected through the Status property, and if AppServiceResponseStatus.Success The enumeration value is the successful response. Next, just check that the response message contains the key guid , and if so, read its key value.

If all the code is written correctly, deploy the above two apps, and run the client app, when the button is clicked, the client correctly obtains a GUID from the server and displays it on the text box.

Debugging

Debugging a client app is as simple as starting debugging directly in Visual Studio just as you would normally debug a UWP app. Or start the client app from the Start menu, and then attach the debugger to the initiated client process through Visual Studio. (Note that there may be two processes in the process list that have a window caption for the client app name, rather than a process that ApplicationFrameHost.exe is the view framework hosting process for the UWP app.) )

The debugging of the app service is a little more cumbersome, with the following steps:

    1. Make sure that the entire solution has been built and deployed (that is, the service provider app and the client caller app have built the deployment).
    2. Open the project properties setting for the service offering app project (note that the project is applied, not a background task), switch to the Debug tab, 启动动作(Start action) tick not start the app, but start debugging when the app starts (does not launch, but debug my Code When it starts).
    3. Right-click the service Provider app project (note that the project is an app, not a background task), and select Set as Startup Project (set as Startup projects).
    4. Set the endpoint in the service code of the background process.
    5. When you press start debugging in the current Visual Studio window, the F5 app should not start, and debugging will not start immediately, but it waits for external requests from the service to activate the background task before debugging begins.
    6. Starting the client Caller app from the Start menu, clicking the button triggers a call to the service, at which point Visual Studio starts debugging and stops at the breakpoint set in step 4th.
Summarize

While it appears that the UWP provides a relatively weak interaction between applications, the app Service can be used for many scenarios. For example, a service provides a token for other applications to access public resources, generate a one-time secure URL for a service, and so on.

This blog for personal blog backup, this text address: http://validvoid.net/uwp-app-service/

Create, use, and debug app service (app services) in a UWP app

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.