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 projectPackage.appxmanifest.
    • Switch toDeclarationstabs.
    • Select in the leftAvailable DeclarationsApp Serviceand clickAddAdd it to theSupported Declarationslist.
    • Then set the APP Service-related properties on the right.


In general, there are two items that need to be setNameEntry point.Nameis the service name provided by the application, theEntry pointentry point, which is the background task class that implements the application service functionality.



You can also manually editPackage.appxmanifestthe 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     Node (if not, add it manually).
    • in   <extensions></extensions>  , add the following code:
<uap: Extension Category = "windows.appService" EntryPoint = "Entry Point">
     <uap: AppService 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 theIBackgroundTaskbackground 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 class GUIDProviderTask: IBackgroundTask
{
     private BackgroundTaskDeferral backgroundTaskDeferral;
     private AppServiceConnection appServiceconnection;

     public void Run (IBackgroundTaskInstance taskInstance)
     {
         this.backgroundTaskDeferral = taskInstance.GetDeferral ();

         taskInstance.Canceled + = OnTaskCanceled;

         var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
         appServiceconnection = details.AppServiceConnection;
         appServiceconnection.RequestReceived + = OnRequestReceived;
     }

     private async void OnRequestReceived (AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
     {
         // Get deferral
         var requestDeferral = args.GetDeferral ();

         try
         {
             // Read messages received by the service
             var message = args.Request.Message;

             var result = new ValueSet ();

             // Check if the message contains the agreed content
             if (message.ContainsKey ("requestguid"))
             {
                 // Fill in the generated GUID in the response result
                 result.Add ("guid", GenerateGUID ());
             }

             // The service sends back the response result
             await args.Request.SendResponseAsync (result);
         }
         catch (Exception ex)
         {
             var result = new ValueSet ();

             // Write exception to response result
             result.Add ("exception", ex);

             // The service sends back a response
             await args.Request.SendResponseAsync (result);
         }
         finally
         {
             // Notify the system service has completed the response via deferral
             requestDeferral.Complete ();
         }
     }

     private void OnTaskCanceled (IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
     {
         if (this.backgroundTaskDeferral! = null)
         {
             // Notify the service deferral is complete.
             this.backgroundTaskDeferral.Complete ();
         }
     }

    private string GenerateGUID ()
    {
        return Guid.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 areRunended 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, theAppServiceConnectionclient 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 theRunmethod, bytaskInstanceobtainingAppServiceTriggerDetails. 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 isAppServiceConnecton. The codeAppServiceTriggerDetailsis established by getting the current call to the serviceAppServiceConnecton.


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 listenRequestReceivedto 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 theOnRequestedReceivedasync keyword.



To be able to use the Async method normally in the event handling methodOnRequestedReceived, you need to get a deferral first. Deferral ensures that theOnRequestedReceivedcall 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 theSendResponseAsyncOnRequestedReceivednotification,SendResponseAsyncOnRequestedReceivedbut rather deferral the method responsible for notifying the clientSendMessageAsynchas finished processing the event responseOnRequestedReceived. (SendMessageAsyncis 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-throughValueSet, and developers need to agree on the key-value agreements required for the service themselves. The client caller must adhere to this protocol constructValueSet.



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 canValueSetattach detailed state information, such as exception information, to the client caller in response to the result.



Finally, theSendResponseAsynccall 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, fromApp.xaml.cswithinpublic App())Windows.ApplicationModel.Package.Current.Id.FamilyNamecan 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__yd7nk54bq29rarendered 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 thePackage.appxmanifestfile to open the manifest file designer, switch to thePackagingtab, and view thePackage family namevalues 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 boxtextBox.



In the background code of the page, declare oneAppServiceConnection:


Private Appserviceconnection Guidservice;  


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


 
private async void button_Click(object sender, RoutedEventArgs e)  
{ if (guidService == null)
    {
        guidService = new AppServiceConnection();
        guidService.AppServiceName = "GuidProviderService";
        guidService.PackageFamilyName = "0e37a0ad-6f9f-41f6-ac5f-ac93c00b9474_21qyshkbc51y2"; var status = await this.guidService.OpenAsync(); if (status != AppServiceConnectionStatus.Success)
        {
            button.Content = "Failed to connect"; return;
        }
    } var message = new ValueSet();
    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 checkAppServiceConnectionwhether 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, callOpenAsync()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, createValueSetand fill in a key named in the keyrequestguidthat 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.



TheSendMessageAsync()method is then called to send the previously createdValueSetparameters 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 theStatusproperty, and if AppServiceResponseStatus.Success The enumeration value is the successful response. Next, just check that the response message contains the keyguid, 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 thatApplicationFrameHost.exeis 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, theF5app 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


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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.