UWP uses AppService to provide services to another UWP client application

Original: UWP uses AppService to provide services to another UWP client application

In the last article, I used WCF hosted on WPF to communicate between two programs. While solving the problem, my colleagues are also thinking about whether to use UWP to do this. So, we discovered App Service, a bridge for communication between two UWP applications.

App Service allows one UWP to provide services to other UWPs in the form of background tasks.

First, we create a new Windows Runtime Component project named "MyCalculatorService", create a new Calculator class, and implement the IBackgroundTask. interface, which is very similar to the ServiceContract in WCF.

public sealed class Calculator : IBackgroundTask
	{
		private BackgroundTaskDeferral backgroundTaskDeferral;
		private AppServiceConnection appServiceConnection;
		public void Run(IBackgroundTaskInstance taskInstance)
		{
			this.backgroundTaskDeferral = taskInstance.GetDeferral();

			var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
			appServiceConnection = details.AppServiceConnection;

			appServiceConnection.RequestReceived += OnRequestReceived;
			taskInstance.Canceled += OnTaskCanceled;
		}

		private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
		{
			var messageDeferral = args.GetDeferral();
			ValueSet message = args.Request.Message;
			ValueSet returnData = new ValueSet();

			string command = message["Command"] as string;      //Add, Subtract, Multiply, Divide
			int? firstNumber = message["Input1"] as int?;
			int? secondNumber = message["Input2"] as int?;
			int? result = 0;

			if (firstNumber.HasValue && secondNumber.HasValue)
			{
				switch (command)
				{
					case "Add":
						{
							result = firstNumber + secondNumber;
							returnData.Add("Result", result.ToString());
							returnData.Add("Status", "Complete");
							break;
						}
					case "Subtract":
						{
							result = firstNumber - secondNumber;
							returnData.Add("Result", result.ToString());
							returnData.Add("Status", "Complete");
							break;
						}
					case "Multiply":
						{
							result = firstNumber * secondNumber;
							returnData.Add("Result", result.ToString());
							returnData.Add("Status", "Complete");
							break;
						}
					case "Divide":
						{
							result = firstNumber / secondNumber;
							returnData.Add("Result", result.ToString());
							returnData.Add("Status", "Complete");
							break;
						}
					default:
						{
							returnData.Add("Status", "Fail: unknown command");
							break;
						}
				}
			}

			await args.Request.SendResponseAsync(returnData);
			messageDeferral.Complete();
		}

		private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
		{
			if (this.backgroundTaskDeferral != null)
			{
				this.backgroundTaskDeferral.Complete();
			}
		}
	}

  Then create a new UWP program named MyCalculatorServiceProvider, which acts as a server, which is equivalent to the WCF hosting service. Reference the wind we just created, then declare an App Service instance named CalculatorService1 in Package.appxmanifest and add the entry point "MyCalculatorService.Calculator".

Now let's create a client named "CalculatorClient" and call the above service. Add the following code

public sealed partial class MainPage : Page
    {
    private AppServiceConnection calculatorService;

    public MainPage()
        {
            this.InitializeComponent();
        }

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        //Add the connection
        if (calculatorService == null)
        {
            calculatorService = new AppServiceConnection();
            calculatorService.AppServiceName = "CalculatorService1";
            calculatorService.PackageFamilyName = "83da5395-2473-49fb-b361-37072e87e9b9_xe3s0d4n4696a";

            var status = await calculatorService.OpenAsync();

            if (status != AppServiceConnectionStatus.Success)
            {
                Result.Content = "Failed to connect";
                return;
            }
        }

        //Call the service
        int num1 = int.Parse(InputtextBox1.Text);
        int num2 = int.Parse(InputtextBox2.Text);
        var message = new ValueSet();

        message.Add("Command", Operation.SelectionBoxItem);
        message.Add("Input1", num1);
        message.Add("Input2", num2);

        AppServiceResponse response = await calculatorService.SendMessageAsync(message);
        string result = "";

        if (response.Status == AppServiceResponseStatus.Success)
        {
            //Get the data that the service sent
            if (response.Message["Status"] as string == "Complete")
            {
                result = response.Message["Result"] as string;
            }
        }
        message.Clear();
        ResulttextBlock.Text = result;
    }
    }

Note that AppServiceName is the name of the App Service we defined in the MyCalculatorServiceProvider project, and PackageFamilyName is the PackageFamilyName of the MyCalculatorServiceProvider project.

After completion, deploy MyCalculatorServiceProvider first and then deploy CalculatorClient. Is the effect similar to WCF?

Well, the above is all I got from https://social.technet.microsoft.com/wiki/contents/articles/36719.wcf-app-services-in-universal-windows-platform-uwp-using-windows-10. aspx copied,,,

The example demo can be downloaded from here http://www.cnblogs.com/luquanmingren/p/7692305.html , yes, I am lazy

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325313072&siteId=291194637
UWP