private async Task<string> SendMessageAsync(ValueSet message)
        {
            using (var connection = new AppServiceConnection())
            {
                connection.AppServiceName = BookServiceName;
                connection.PackageFamilyName = BooksPackageName;

                AppServiceConnectionStatus status = await connection.OpenAsync();
                if (status == AppServiceConnectionStatus.Success)
                {
                    AppServiceResponse response = await connection.SendMessageAsync(message);
                    if (response.Status == AppServiceResponseStatus.Success && response.Message.ContainsKey("result"))
                    {
                        string result = response.Message["result"].ToString();
                        return result;
                    }
                    else
                    {
                        await ShowServiceErrorAsync(response.Status);
                    }

                }
                else
                {
                    await ShowConnectionErrorAsync(status);
                }

                return string.Empty;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Creates the app service connection
        /// </summary>
        static async void ThreadProc()
        {
            connection = new AppServiceConnection();
            connection.AppServiceName = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
            connection.RequestReceived += Connection_RequestReceived;

            AppServiceConnectionStatus status = await connection.OpenAsync();
            switch (status)
            {
                case AppServiceConnectionStatus.Success:
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Connection established - waiting for requests");
                    Console.WriteLine();
                    break;
                case AppServiceConnectionStatus.AppNotInstalled:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("The app AppServicesProvider is not installed.");
                    return;
                case AppServiceConnectionStatus.AppUnavailable:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("The app AppServicesProvider is not available.");
                    return;
                case AppServiceConnectionStatus.AppServiceUnavailable:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(string.Format("The app AppServicesProvider is installed but it does not provide the app service {0}.", connection.AppServiceName));
                    return;
                case AppServiceConnectionStatus.Unknown:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(string.Format("An unkown error occurred while we were trying to open an AppServiceConnection."));
                    return;
            }
        }
        private async void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var message = args.Request.Message;
            string command = message["Command"] as string;

            switch (command)
            {
                case "CalcSum":
                    {
                        var messageDeferral = args.GetDeferral();

                        int value1 = (int)message["Value1"];
                        int value2 = (int)message["Value2"];

                        //Set a result to return to the caller 
                        int result = value1 + value2;
                        var returnMessage = new ValueSet();
                        returnMessage.Add("Result", result);
                        var responseStatus = await args.Request.SendResponseAsync(returnMessage);

                        messageDeferral.Complete();
                        break;
                    }

                case "Quit":
                    {
                        //Service was asked to quit. Give us service deferral 
                        //so platform can terminate the background task 
                        _serviceDeferral.Complete();
                        break;
                    }
            }
        }
Beispiel #4
0
        private async System.Threading.Tasks.Task EnsureConnectionToService()
        {
            if (this.connection == null)
            {
                connection = new AppServiceConnection();

                // See the appx manifest of the AppServicesDemp app for this value
                connection.AppServiceName = "microsoftDX-appservicesdemo";
                // Use the Windows.ApplicationModel.Package.Current.Id.FamilyName API in the 
                // provider app to get this value
                connection.PackageFamilyName = "82a987d5-4e4f-4cb4-bb4d-700ede1534ba_nsf9e2fmhb1sj";

                AppServiceConnectionStatus connectionStatus = await connection.OpenAsync();
                if (connectionStatus == AppServiceConnectionStatus.Success)
                {
                    connection.ServiceClosed += OnServiceClosed;
                    //connection.RequestReceived += OnRequestReceived;
                }
                else
                {
                    //Drive the user to store to install the app that provides 
                    //the app service 
                }
            }
        }
Beispiel #5
0
		private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
		{
			var reqDeferral = args.GetDeferral();
			var message = args.Request.Message;
            var result = new ValueSet();
			if (args.Request.Message.ContainsKey("service"))
			{
				var serviceName = message["service"] as string;
				if (serviceName.Equals("add", StringComparison.OrdinalIgnoreCase))
				{
					if (message.ContainsKey("a") && message.ContainsKey("b"))
					{
						result.Add("result", Add((int)message["a"], (int)message["b"]));
					}
				}
				else if (serviceName.Equals("sub", StringComparison.OrdinalIgnoreCase))
				{
					if (message.ContainsKey("a") && message.ContainsKey("b"))
					{
						result.Add("result", Sub((int)message["a"], (int)message["b"]));
					}
				}
                else
                {
                    result.Add("result", 0);
                }
			}
			await args.Request.SendResponseAsync(result);
			reqDeferral.Complete();
		}
        public AzureIoTHubConnection(AppServiceConnection connection)
        {
            _appServiceConnection = connection;
            deviceClient = DeviceClient.CreateFromConnectionString(DeviceConnectionString);
            _appServiceConnection.RequestReceived += OnRequestReceived;

        }
Beispiel #7
0
 public WebSocketServer(AppServiceConnection connection)
 {
     _appServiceConnection = connection;
     _appServiceConnection.RequestReceived += OnRequestReceived;
     
     _portMapping = new IdHelper(5);
 }
        private async System.Threading.Tasks.Task EnsureConnectionToSynonymsService()
        {
            if (this.synonymsServiceConnection == null)
            {
                synonymsServiceConnection = new AppServiceConnection();

                // See the appx manifest of the AppServicesDemp app for this value
                synonymsServiceConnection.AppServiceName = "MicrosoftDX-SynonymsService";
                // Use the Windows.ApplicationModel.Package.Current.Id.FamilyName API in the 
                // provider app to get this value
                synonymsServiceConnection.PackageFamilyName = "82a987d5-4e4f-4cb4-bb4d-700ede1534ba_nsf9e2fmhb1sj";

                AppServiceConnectionStatus connectionStatus = await synonymsServiceConnection.OpenAsync();
                if (connectionStatus == AppServiceConnectionStatus.Success)
                {
                    synonymsServiceConnection.ServiceClosed += (s, serviceClosedEventArgs) =>
                    {
                        if (ServiceClosed != null)
                        {
                            ServiceClosed(this, serviceClosedEventArgs);
                        }
                    };
                }
                else
                {
                    //Drive the user to store to install the app that provides 
                    //the app service 
                    throw new NotImplementedException("Service not installed on this device");
                }
            }
        }
Beispiel #9
0
        public async Task<ValueSet> MakeUWPCommandCall(string commandCall, string serviceName) {
            if (AppExtension == null) return null;
            using (var connection = new AppServiceConnection())
            {
                connection.AppServiceName = serviceName;
                connection.PackageFamilyName = AppExtension.Package.Id.FamilyName;
                var status = await connection.OpenAsync();
                if (status != AppServiceConnectionStatus.Success)
                {
                    Debug.WriteLine("Failed app service connection");
                }
                else
                {
                    var request = new ValueSet();
                    request.Add("Command", commandCall);
                    AppServiceResponse response = await connection.SendMessageAsync(request);
                    if (response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success)
                    {
                        var message = response.Message as ValueSet;
                        if (message != null && message.Count > 0) {
                            message.Add(new KeyValuePair<string, object>("AppExtensionDisplayName", AppExtension.AppInfo.DisplayInfo.DisplayName));
                        }
                        return (message!=null && message.Count>0)? message: null;
                    }
                }

            }
            return null;
        }
Beispiel #10
0
		private async void CallService_Click(object sender, RoutedEventArgs e)
		{
			var connection = new AppServiceConnection();
			connection.PackageFamilyName = "0df93276-6bbb-46fa-96b7-ec223e226505_cb1hhkscw5m06"; // Windows.ApplicationModel.Package.Current.Id.FamilyName;
			connection.AppServiceName = "CalculatorService";
			var status = await connection.OpenAsync();
			if (status != AppServiceConnectionStatus.Success)
			{
				var dialog = new MessageDialog("Sorry, I can't connect to the service right now :S");
				await dialog.ShowAsync();
				return;
			}
			var message = new ValueSet();
			message.Add("service", OperatorCombo.Items[OperatorCombo.SelectedIndex]);
			message.Add("a", Convert.ToInt32(ValueABox.Text));
			message.Add("b", Convert.ToInt32(ValueBBox.Text));
			AppServiceResponse response = await connection.SendMessageAsync(message);
			if (response.Status == AppServiceResponseStatus.Success)
			{
				if (response.Message.ContainsKey("result"))
				{
					ResultBlock.Text = response.Message["result"] as string;
				}
			}
			else
			{
				var dialog = new MessageDialog(string.Format("Opps, I just get an error :S ({0})", response.Status));
				await dialog.ShowAsync();
			}
		}
        public async Task<IEnumerable<Beer>> GetBeersByFilter(string filter)
        {
            AppServiceConnection connection = new AppServiceConnection();
            connection.AppServiceName = "PlainConcepts-appservicesdemo";
            connection.PackageFamilyName = "cff6d46b-5839-4bb7-a1f2-e59246de63b3_cb1hhkscw5m06";
            AppServiceConnectionStatus connectionStatus = await connection.OpenAsync();

            if (connectionStatus == AppServiceConnectionStatus.Success)
            {
                //Send data to the service
                var message = new ValueSet();
                message.Add("Command", "GetBeersByFilter");
                message.Add("Filter", filter);

                //Send message and wait for response   
                AppServiceResponse response = await connection.SendMessageAsync(message);
                if (response.Status == AppServiceResponseStatus.Success)
                {
                    var resultJson = (string)response.Message["Result"];
                    var list = JsonConvert.DeserializeObject<IEnumerable<Beer>>(resultJson);
                    return list;
                }
            }
            else
            {
                //Drive the user to store to install the app that provides the app service 
                new MessageDialog("Service not installed").ShowAsync();
            }

            return null;
        }
 private async void OnMessageReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
 {
     var message = args.Request.Message;
     string newState = message["State"] as string;
     switch (newState)
     {
         case "On":
             {
                 await Dispatcher.RunAsync(
                       CoreDispatcherPriority.High,
                      () =>
                      {
                          TurnOnLED();
                      }); 
                 break;
             }
         case "Off":
             {
                 await Dispatcher.RunAsync(
                 CoreDispatcherPriority.High,
                 () =>
                 {
                     TurnOffLED();
                  });
                 break;
             }
         case "Unspecified":
         default:
             {
                 // Do nothing 
                 break;
             }
     }
 }
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            Loading.IsActive = true;
            AppServiceConnection connection = new AppServiceConnection();
            connection.PackageFamilyName = Package.Current.Id.FamilyName;
            connection.AppServiceName = "FeedParser";

            var status = await connection.OpenAsync();

            if (status == AppServiceConnectionStatus.Success)
            {
                ValueSet data = new ValueSet();
                data.Add("FeedUrl", "http://blog.qmatteoq.com/feed/");

                var response = await connection.SendMessageAsync(data);
                if (response.Status == AppServiceResponseStatus.Success)
                {
                    string items = response.Message["FeedItems"].ToString();
                    var result = JsonConvert.DeserializeObject<List<FeedItem>>(items);
                    News.ItemsSource = result;
                }
            }

            Loading.IsActive = false;
        }
        private async Task LaunchAppService(string cmd)
        {
            var connection = new AppServiceConnection
            {
                AppServiceName = "uwpdeepdive-appservice",
                PackageFamilyName = "11fc3805-6c54-417b-916c-a4f6e89876b2_2eqywga5gg4gm"
            };
            var appServiceConnectionStatus = await connection.OpenAsync();
            if (appServiceConnectionStatus != AppServiceConnectionStatus.Success)
            {
                _resultsTextBox.Text = appServiceConnectionStatus.ToString();
                return;
            }

            var msg = new ValueSet {["cmd"] = cmd};
            var appServiceResponse = await connection.SendMessageAsync(msg);
            if (appServiceResponse.Status != AppServiceResponseStatus.Success)
            {
                _resultsTextBox.Text = appServiceResponse.Status.ToString();
                return;
            }
            var time = appServiceResponse.Message[cmd] as string;
            _resultsTextBox.Text = time ?? "";

            //note - communication is two-way! can send/receive as needed
            //connection.RequestReceived += delegate(
            //    AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { /* ... */ };
        }
Beispiel #15
0
        private async void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var msgDef = args.GetDeferral();
            var msg = args.Request.Message;
            var returnData = new ValueSet();

            var command = msg["Command"] as string;

            switch (command) {
                case "UI":
                    returnData.Add("sketch-test", "X.Extension.ThirdParty.Backgrounds.UI.Test");
                    returnData.Add("sketch-home", "X.Extension.ThirdParty.Backgrounds.UI.Home");
                    break;
                case "RandomBackground":
                    Random rnd = new Random();
                    returnData.Add("filename", $"bkg0{rnd.Next(1, 5)}.jpg");
                    break;
                case "Spritesheet":
                    returnData.Add("spritesheet-img", "bkg-spritesheet.jpg");
                    returnData.Add("spritesheet-xml", "bkg-spritesheet.xml");
                    break;
            }
            
            await args.Request.SendResponseAsync(returnData);
            msgDef.Complete();
        }
Beispiel #16
0
 public RestServer(int serverPort, string serviceConnection)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     appServiceConnection = new AppServiceConnection() { AppServiceName = serviceConnection };
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
 }
Beispiel #17
0
 public RestServer(int serverPort, AppServiceConnection connection)
 {
     listener = new StreamSocketListener();
     port = serverPort;
     appServiceConnection = connection;
     listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);
 }
        private async void SetupAppService()
        {
            // find the installed application(s) that expose the app service PerimeterBreachService
            var listing = await AppServiceCatalog.FindAppServiceProvidersAsync("PerimeterBreachService");
            var packageName = "";
            // there may be cases where other applications could expose the same App Service Name, in our case
            // we only have the one
            if (listing.Count == 1)
            {
                packageName = listing[0].PackageFamilyName;
            }
            _perimeterBreachService = new AppServiceConnection();
            _perimeterBreachService.AppServiceName = "PerimeterBreachService";
            _perimeterBreachService.PackageFamilyName = packageName;
            //open app service connection
            var status = await _perimeterBreachService.OpenAsync();

            if (status != AppServiceConnectionStatus.Success)
            {
                //something went wrong
                txtStatus.Text = "Could not connect to the App Service: " + status.ToString();
            }
            else
            {
                //add handler to receive app service messages (Perimiter messages)
                _perimeterBreachService.RequestReceived += PerimeterBreachService_RequestReceived;
            }
        }
        async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            //Get a deferral so we can use an awaitable API to respond to the message
            var messageDeferral = args.GetDeferral();

            try
            {
                var input = args.Request.Message;
                int minValue = (int)input["minvalue"];
                int maxValue = (int)input["maxvalue"];

                //Create the response
                var result = new ValueSet();
                result.Add("result", randomNumberGenerator.Next(minValue, maxValue));

                //Send the response
                await args.Request.SendResponseAsync(result);

            }
            finally
            {
                //Complete the message deferral so the platform knows we're done responding
                messageDeferral.Complete();
            }
        }
        private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            // if you are doing anything awaitable, you need to get a deferral
            var requestDeferral = args.GetDeferral();
            var returnMessage = new ValueSet();
            try
            {
                //obtain and react to the command passed in by the client
                var message = args.Request.Message["Request"] as string;
                switch (message)
                {
                    case "Turn LED On":
                        _ledPin.Write(GpioPinValue.High);
                        break;
                    case "Turn LED Off":
                        _ledPin.Write(GpioPinValue.Low);
                        break;
                }
                returnMessage.Add("Response", "OK");
            }
            catch (Exception ex)
            {
                returnMessage.Add("Response", "Failed: " + ex.Message);
            }

            await args.Request.SendResponseAsync(returnMessage);
 
            //let the OS know that the action is complete
            requestDeferral.Complete();
        }
Beispiel #21
0
        //TemperatureSensors tempSensors;

        public void Run(IBackgroundTaskInstance taskInstance)
        {
            //if (!_started)
            //{
            //    tempSensors = new TemperatureSensors();
            //    tempSensors.InitSensors();
            //    _started = true;
            //}
            
            // Associate a cancellation handler with the background task. 
            taskInstance.Canceled += TaskInstance_Canceled;

            // Get the deferral object from the task instance
            serviceDeferral = taskInstance.GetDeferral();

            var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
            if (appService != null && appService.Name == "App2AppComService")
            {
                appServiceConnection = appService.AppServiceConnection;
                appServiceConnection.RequestReceived += AppServiceConnection_RequestReceived; ;
            }

            // just run init, maybe don't need the above...
            Initialize();
        }
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var message = args.Request.Message;
            string command = message["Command"] as string;

            switch (command)
            {
                case "Initialize":
                    var messageDeferral = args.GetDeferral();
                    //Set a result to return to the caller
                    var returnMessage = new ValueSet();
                    HttpServer server = new HttpServer(8000, appServiceConnection);
                    IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
                        (workItem) =>
                        {
                            server.StartServer();
                        });
                    returnMessage.Add("Status", "Success");
                    var responseStatus = await args.Request.SendResponseAsync(returnMessage);
                    messageDeferral.Complete();
                    break;
                case "Quit":
                    //Service was asked to quit. Give us service deferral
                    //so platform can terminate the background task
                    serviceDeferral.Complete();
                    break;
            }
        }
Beispiel #23
0
        private async void InitializeService()
        {
            _appServiceConnection = new AppServiceConnection
            {
                PackageFamilyName = "ConnectionService-uwp_5gyrq6psz227t",
                AppServiceName = "App2AppComService"
            };

            // Send a initialize request 
            var res = await _appServiceConnection.OpenAsync();
            if (res == AppServiceConnectionStatus.Success)
            {
                var message = new ValueSet {{"Command", "Connect"}};

                var response = await _appServiceConnection.SendMessageAsync(message);
                if (response.Status == AppServiceResponseStatus.Success)
                {
                    InitializeSerialBridge();
                    //InitializeBluetoothBridge();
                    _appServiceConnection.RequestReceived += _serialBridge.OnCommandRecived;
                    //_appServiceConnection.RequestReceived += _bluetoothBridge.OnCommandRecived;
                    //_appServiceConnection.RequestReceived += _appServiceConnection_RequestReceived;
                    
                }
            }
        }
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            AppServiceDeferral deferral = args.GetDeferral();
            try
            {
                ValueSet message = args.Request.Message;
                ValueSet result = null;

                switch (message["command"].ToString())
                {
                    case "GET":
                        result = GetBooks();
                        break;
                    case "POST":
                        result = AddBook(message["book"].ToString());
                        break;
                    default:
                        break;
                }

                await args.Request.SendResponseAsync(result);

            }
            finally
            {
                deferral.Complete();
            }
        }
        public async Task<IEnumerable<FeedItem>> GetNewsAsync(string url)
        {
            AppServiceConnection connection = new AppServiceConnection();
            connection.PackageFamilyName = "637bc306-acb1-4e73-bbe0-70ecc919ca1c_e8f4dqfvn1be6";
            connection.AppServiceName = "FeedParser";

            var status = await connection.OpenAsync();

            if (status == AppServiceConnectionStatus.Success)
            {
                ValueSet data = new ValueSet();
                data.Add("FeedUrl", url);

                var response = await connection.SendMessageAsync(data);
                if (response.Status == AppServiceResponseStatus.Success)
                {
                    string items = response.Message["FeedItems"].ToString();
                    var result = JsonConvert.DeserializeObject<List<FeedItem>>(items);
                    return result;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
 private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
 {
     var deferral = args.GetDeferral();
     var response = new ValueSet();
     bool stop = false;
     try
     {
         var request = args.Request;
         var message = request.Message;
         if (message.ContainsKey(BackgroundOperation.NewBackgroundRequest))
         {
             switch ((BackgroundRequest)message[BackgroundOperation.NewBackgroundRequest])
             {
                 default:
                     stop = true;
                     break;
             }
         }
     }
     finally
     {
        
         if (stop)
         {
             _deferral.Complete();
         }
     }
 }
        private async void InitializeAppSvc()
        {
            string WebServerStatus = "PoolWebServer failed to start. AppServiceConnectionStatus was not successful.";

            // Initialize the AppServiceConnection
            appServiceConnection = new AppServiceConnection();
            appServiceConnection.PackageFamilyName = "PoolWebServer_hz258y3tkez3a";
            appServiceConnection.AppServiceName = "App2AppComService";

            // Send a initialize request 
            var res = await appServiceConnection.OpenAsync();
            if (res == AppServiceConnectionStatus.Success)
            {
                var message = new ValueSet();
                message.Add("Command", "Initialize");
                var response = await appServiceConnection.SendMessageAsync(message);
                if (response.Status != AppServiceResponseStatus.Success)
                {
                    WebServerStatus = "PoolWebServer failed to start.";
                    throw new Exception("Failed to send message");
                }
                appServiceConnection.RequestReceived += OnMessageReceived;
                WebServerStatus = "PoolWebServer started.";
            }

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                txtWebServerStatus.Text = WebServerStatus;
            });
        }
Beispiel #28
0
		private async void CallService_Click(object sender, RoutedEventArgs e)
		{
			var connection = new AppServiceConnection();
			connection.PackageFamilyName = "041cdcf9-8ef3-40e4-85e2-8f3de5e06155_ncrzdc1cmma1g"; // Windows.ApplicationModel.Package.Current.Id.FamilyName;
			connection.AppServiceName = "CalculatorService";
			var status = await connection.OpenAsync();
			if (status != AppServiceConnectionStatus.Success)
			{
				var dialog = new MessageDialog("Sorry, I can't connect to the service right now :S");
				await dialog.ShowAsync();
				return;
			}
			var message = new ValueSet();
			message.Add("service", (OperatorCombo.SelectedValue as ComboBoxItem).Content);
			message.Add("a", Convert.ToInt32(ValueABox.Text));
			message.Add("b", Convert.ToInt32(ValueBBox.Text));
			AppServiceResponse response = await connection.SendMessageAsync(message);
			if (response.Status == AppServiceResponseStatus.Success)
			{
				if (response.Message.ContainsKey("result"))
				{
					ResultBlock.Text = response.Message["result"].ToString();
				}
			}
			else
			{
				var dialog = new MessageDialog(string.Format("Opps, I just get an error :S ({0})", response.Status));
				await dialog.ShowAsync();
			}
		}
Beispiel #29
0
		private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
		{
			var lDeferral = args.GetDeferral();
			try
			{
				var message = args.Request.Message;
				if(message.ContainsKey("MessageType") && message.ContainsKey("Message"))
				{
					var type = message["MessageType"] as String;
					var mes = message["Message"] as String;
					if(type != null && mes != null)
					{
						using(var lh = new LoggingHelper())
						{
							var result = lh.LogEntry(type, mes);
							var vs = new ValueSet();
							vs["result"] = result;
							await args.Request.SendResponseAsync(vs);
						}
					}
				}
			}
			catch { }
			lDeferral.Complete();	
		}
        private async void GetEmployeeById(object sender, RoutedEventArgs e)
        {

            appServiceConnection = new AppServiceConnection
            {
                AppServiceName = "EmployeeLookupService",
                PackageFamilyName = "3598a822-2b34-44cc-9a20-421137c7511f_4frctqp64dy5c"
            };

            var status = await appServiceConnection.OpenAsync();

            switch (status)
            {
                case AppServiceConnectionStatus.AppNotInstalled:
                    await LogError("The EmployeeLookup application is not installed. Please install it and try again.");
                    return;
                case AppServiceConnectionStatus.AppServiceUnavailable:
                    await LogError("The EmployeeLookup application does not have the available feature");
                    return;
                case AppServiceConnectionStatus.AppUnavailable:
                    await LogError("The package for the app service to which a connection was attempted is unavailable.");
                    return;
                case AppServiceConnectionStatus.Unknown:
                    await LogError("Unknown Error.");
                    return;
            }

            var items = this.EmployeeId.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            var message = new ValueSet();

            for (int i = 0; i < items.Length; i++)
            {
                message.Add(i.ToString(), items[i]);
            }

            var response = await appServiceConnection.SendMessageAsync(message);

            switch (response.Status)
            {
                case AppServiceResponseStatus.ResourceLimitsExceeded:
                    await LogError("Insufficient resources. The app service has been shut down.");
                    return;
                case AppServiceResponseStatus.Failure:
                    await LogError("Failed to receive response.");
                    return;
                case AppServiceResponseStatus.Unknown:
                    await LogError("Unknown error.");
                    return;
            }

            foreach (var item in response.Message)
            {
                this.Items.Add(new Employee
                {
                    Id = item.Key,
                    Name = item.Value.ToString()
                });
            }
        }
Beispiel #31
0
        public SystrayApplicationContext()
        {
            var sendMessageMenuItem = new MenuItem("Send Message", SendMessageToApp);
            var launchMenuItem      = new MenuItem("Launch", LaunchApp);
            var exitMenuItem        = new MenuItem("Exit", ExitApp);

            launchMenuItem.DefaultItem = true;

            var notifyIcon = new NotifyIcon();

            notifyIcon.DoubleClick += LaunchApp;
            notifyIcon.Icon         = Properties.Resources.IconMaPhone;
            notifyIcon.ContextMenu  = new ContextMenu(new[]
            {
                sendMessageMenuItem, launchMenuItem, exitMenuItem
            });
            notifyIcon.Visible = true;

            _appServiceConnection = CreateAppServiceConnection();
        }
Beispiel #32
0
        public override ValueSet OnRequest(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            string versionID = args.Request.Message["version"].ToString();

            KMCCC.Launcher.Version ver = Program.Launcher.Core.GetVersion(versionID);

            if (ver == null)
            {
                return(null);
            }

            ValueSet ret = new ValueSet();

            ret["client"]      = ver.Downloads.Client.Url;
            ret["client-sha1"] = ver.Downloads.Client.SHA1;
            ret["server"]      = ver.Downloads.Server.Url;
            ret["server-sha1"] = ver.Downloads.Server.SHA1;

            return(ret);
        }
Beispiel #33
0
        private async void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var msgDef     = args.GetDeferral();
            var msg        = args.Request.Message;
            var returnData = new ValueSet();

            var command = msg["Command"] as string;

            switch (command)
            {
            case "UI":
                returnData.Add("sketch-test", "X.Extension.ThirdParty.AWS.UI.Test");
                returnData.Add("sketch-home", "X.Extension.ThirdParty.AWS.UI.Home");
                break;
            }

            await args.Request.SendResponseAsync(returnData);

            msgDef.Complete();
        }
Beispiel #34
0
        private async void InitializeAppServiceConnection()
        {
            Connection = new AppServiceConnection();
            Connection.AppServiceName    = "FilesInteropService";
            Connection.PackageFamilyName = Package.Current.Id.FamilyName;
            Connection.RequestReceived  += Connection_RequestReceived;
            Connection.ServiceClosed    += Connection_ServiceClosed;

            AppServiceConnectionStatus status = await Connection.OpenAsync();

            if (status != AppServiceConnectionStatus.Success)
            {
                // TODO: error handling
                Connection.Dispose();
                Connection = null;
            }

            // Launch fulltrust process
            await FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
        }
Beispiel #35
0
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var pkgFamilyName = Package.Current.Id.FamilyName;

            System.Diagnostics.Debug.WriteLine(pkgFamilyName);

            //Take a service deferral so the service isn't terminated
            serviceDeferral = taskInstance.GetDeferral();

            taskInstance.Canceled += OnTaskCanceled;

            if (taskInstance.TriggerDetails != null)
            {
                var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
                connection = details.AppServiceConnection;

                //Listen for incoming app service requests
                connection.RequestReceived += OnRequestReceived;
            }
        }
Beispiel #36
0
        private async void AppServiceRequestHandler(AppServiceConnection connection, AppServiceRequestReceivedEventArgs args)
        {
            TwinCollection collection = null;

            foreach (var pair in args.Request.Message)
            {
                if (pair.Key.StartsWith("Config"))
                {
                    if (collection == null)
                    {
                        collection = new TwinCollection();
                    }
                    collection[pair.Key] = pair.Value;
                }
            }
            if (collection != null)
            {
                await _client.UpdateReportedPropertiesAsync(collection);
            }
        }
Beispiel #37
0
        public static async Task <VoiceViewModel> StartNewAsync(DiscordChannel channel)
        {
            var model = new VoiceViewModel();

            var service = new AppServiceConnection
            {
                AppServiceName    = "com.wankerr.Unicord.Voice",
                PackageFamilyName = Package.Current.Id.FamilyName
            };

            var status = await service.OpenAsync();

            if (status != AppServiceConnectionStatus.Success)
            {
                throw new Exception("Whoops??");
            }

            var resp = await service.SendMessageAsync(new ValueSet()
            {
                ["request"] = "connect",
                ["token"]   = App.Discord.Configuration.Token,
                ["server"]  = channel.GuildId.ToString(),
                ["channel"] = channel.Id.ToString()
            });

            if (resp.Status == AppServiceResponseStatus.Success)
            {
                var connected = (bool)resp.Message["connected"];
                if (connected)
                {
                    service.RequestReceived += model.RequestRecieved;
                    return(model);
                }
                else
                {
                    throw new Exception(resp.Message["error"] as string);
                }
            }

            return(null);
        }
Beispiel #38
0
        private async void Track_Click(object sender, RoutedEventArgs e)
        {
            if (serviceConnection == null)
            {
                serviceConnection = new AppServiceConnection();
                serviceConnection.AppServiceName    = "TrackingServiceEndpoint";
                serviceConnection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;

                var status = await serviceConnection.OpenAsync();

                if (status != AppServiceConnectionStatus.Success)
                {
                    this.StatusLog.Items.Add("Failed to open connection: " + status.ToString());
                    return;
                }

                this.StatusLog.Items.Add("Connection open!");
            }

            var message = new ValueSet();

            message.Add("PackageID", "12345");

            this.StatusLog.Items.Add("Sending a message");
            AppServiceResponse response = await serviceConnection.SendMessageAsync(message);

            this.StatusLog.Items.Add("Message sent. Response received (" + response.Status + ")");

            if (response.Status == AppServiceResponseStatus.Success)
            {
                if (response.Message.Keys.Count() > 0)
                {
                    string key = response.Message.Keys.First();
                    this.StatusLog.Items.Add("Status: " + response.Message[key] as string);
                }
            }
            else
            {
                this.StatusLog.Items.Add("Message send failed!");
            }
        }
Beispiel #39
0
        private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            // Get a deferral because we use an awaitable API below to respond to the message
            // and we don't want this call to get cancelled while we are waiting.
            var messageDeferral = args.GetDeferral();

            // The fulltrust process signaled that something in the recycle bin folder has changed
            if (args.Request.Message.ContainsKey("FileSystem"))
            {
                var folderPath = (string)args.Request.Message["FileSystem"];
                var itemPath   = (string)args.Request.Message["Path"];
                var changeType = (string)args.Request.Message["Type"];
                var newItem    = JsonConvert.DeserializeObject <ShellFileItem>(args.Request.Message.Get("Item", ""));
                Debug.WriteLine("{0}: {1}", folderPath, changeType);
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    // If we are currently displaying the reycle bin lets refresh the items
                    if (CurrentInstance.FilesystemViewModel?.CurrentFolder?.ItemPath == folderPath)
                    {
                        switch (changeType)
                        {
                        case "Created":
                            CurrentInstance.FilesystemViewModel.AddFileOrFolderFromShellFile(newItem);
                            break;

                        case "Deleted":
                            CurrentInstance.FilesystemViewModel.RemoveFileOrFolder(itemPath);
                            break;

                        default:
                            CurrentInstance.FilesystemViewModel.RefreshItems();
                            break;
                        }
                    }
                });
            }

            // Complete the deferral so that the platform knows that we're done responding to the app service call.
            // Note for error handling: this must be called even if SendResponseAsync() throws an exception.
            messageDeferral.Complete();
        }
Beispiel #40
0
        async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            //Get a deferral so we can use an awaitable API to respond to the message
            var messageDeferral = args.GetDeferral();

            ValueSet message    = args.Request.Message;
            ValueSet returnData = new ValueSet();

            try
            {
                string packageFamilyName = message["PackageFamilyName"] as string;
                string packageLocation   = message["PackageLocation"] as string;
                ApplicationData.Current.LocalSettings.Values["PackageLocation"] = packageLocation;
                ApplicationData.Current.LocalSettings.Values["PackageStatus"]   = "start update";

                PackageManager packagemanager = new PackageManager();
                var            x =
                    await
                    packagemanager.UpdatePackageAsync(new Uri(packageLocation), null,
                                                      DeploymentOptions.ForceApplicationShutdown);

                ApplicationData.Current.LocalSettings.Values["PackageStatus"] = x.ErrorText + "," +
                                                                                x.ActivityId.ToString();
                //Don't need to send anything back since the app is killed during updating but you might want this if you ask to update another app instead
                //of yourself.

//                returnData.Add("Status", "OK");
//                await args.Request.SendResponseAsync(returnData);
            }
            catch (Exception e)
            {
                ApplicationData.Current.LocalSettings.Values["PackageStatus"] = e.Message;
                Debug.WriteLine(e.Message);
                //
            }
            finally
            {
                //Complete the message deferral so the platform knows we're done responding
                messageDeferral.Complete();
            }
        }
Beispiel #41
0
        private async void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var    message = args.Request.Message;
            string command = message["Command"] as string;

            switch (command)
            {
            case "Initialize":
            {
                //Sensors.InitSensors();
                //Devices.InitDevices();

                var messageDeferral = args.GetDeferral();
                Initialize();
                ////Define a new instance of our HTTPServer on Port 8888
                //HttpServer server = new HttpServer(8888, appServiceConnection);
                //IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
                //    (workItem) =>
                //    {   //Start the Sever
                //        server.StartServer();
                //    });

                //Set a result to return to the caller
                var returnMessage = new ValueSet();
                //Respond back to PoolWebService with a Status of Success
                returnMessage.Add("Status", "Success");
                var responseStatus = await args.Request.SendResponseAsync(returnMessage);

                messageDeferral.Complete();
                break;
            }

            case "Quit":
            {
                //Service was asked to quit. Give us service deferral
                //so platform can terminate the background task
                serviceDeferral.Complete();
                break;
            }
            }
        }
Beispiel #42
0
        private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var deferral = args.GetDeferral();

            try
            {
                // Determine which of those must be run on main thread?
                // Or do we run them all on the main thread to be on the safe side?
                var    message = args.Request.Message;
                string action  = (string)message["ACTION"];
                switch (action)
                {
                case ConnectionHelper.VALUE_SLEEP:
                    OnSuspendRequested();
                    break;

                case ConnectionHelper.VALUE_SLEEP_ALT:
                    OnMonitorStandbyRequested();
                    break;

                case ConnectionHelper.VALUE_DISPLAY_OFF:
                    OnMonitorOffRequested();
                    break;

                case ConnectionHelper.VALUE_HOTKEY_SETTINGS:
                    OnHotkeySettingsChanged();
                    break;

                default:
                    break;
                }

                var result = new ValueSet();
                result.Add(ConnectionHelper.KEY_RESULT, ConnectionHelper.VALUE_OK);
                await args.Request.SendResponseAsync(result);
            }
            finally
            {
                deferral.Complete();
            }
        }
Beispiel #43
0
        protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
        {
            base.OnBackgroundActivated(args);

            IBackgroundTaskInstance  taskInstance = args.TaskInstance;
            AppServiceTriggerDetails appService   = taskInstance.TriggerDetails as AppServiceTriggerDetails;

            if (appService?.Name == "com.roamit.notificationservice")
            {
                notificationAppServiceDeferral   = taskInstance.GetDeferral();
                taskInstance.Canceled           -= OnNotificationAppServicesCanceled;
                taskInstance.Canceled           += OnNotificationAppServicesCanceled;
                notificationAppServiceConnection = appService.AppServiceConnection;
                notificationAppServiceConnection.RequestReceived -= OnNotificationAppServiceRequestReceived;
                notificationAppServiceConnection.RequestReceived += OnNotificationAppServiceRequestReceived;
                notificationAppServiceConnection.ServiceClosed   -= NotificationAppServiceConnection_ServiceClosed;
                notificationAppServiceConnection.ServiceClosed   += NotificationAppServiceConnection_ServiceClosed;
            }
            else if (appService?.Name == "com.roamit.messagecarrierservice")
            {
                messageCarrierAppServiceDeferral   = taskInstance.GetDeferral();
                taskInstance.Canceled             -= OnMessageCarrierAppServicesCanceled;
                taskInstance.Canceled             += OnMessageCarrierAppServicesCanceled;
                messageCarrierAppServiceConnection = appService.AppServiceConnection;
                messageCarrierAppServiceConnection.RequestReceived -= OnMessageCarrierAppServiceRequestReceived;
                messageCarrierAppServiceConnection.RequestReceived += OnMessageCarrierAppServiceRequestReceived;
                messageCarrierAppServiceConnection.ServiceClosed   -= MessageCarrierAppServiceConnection_ServiceClosed;
                messageCarrierAppServiceConnection.ServiceClosed   += MessageCarrierAppServiceConnection_ServiceClosed;
            }
            else if (appService?.Name == "com.roamit.pcservice")
            {
                pcAppServiceDeferral   = taskInstance.GetDeferral();
                taskInstance.Canceled -= OnPCAppServicesCanceled;
                taskInstance.Canceled += OnPCAppServicesCanceled;
                pcAppServiceConnection = appService.AppServiceConnection;
                pcAppServiceConnection.RequestReceived -= OnPCAppServiceRequestReceived;
                pcAppServiceConnection.RequestReceived += OnPCAppServiceRequestReceived;
                pcAppServiceConnection.ServiceClosed   -= PCAppServiceConnection_ServiceClosed;
                pcAppServiceConnection.ServiceClosed   += PCAppServiceConnection_ServiceClosed;
            }
        }
Beispiel #44
0
        private async Task StartAppService()
        {
            if (this.appService == null)
            {
                this.appService = new AppServiceConnection();

                // Here, we use the app service name defined in the app service
                // provider's Package.appxmanifest file in the <Extension> section.
                this.appService.AppServiceName = "InProcessAppService";

                // Use Windows.ApplicationModel.Package.Current.Id.FamilyName
                // within the app service provider to get this value.
                this.appService.PackageFamilyName = "30812FreistLi.HoloDomino_33rssfepyhexc";

                var status = await this.appService.OpenAsync();

                if (status != AppServiceConnectionStatus.Success)
                {
                    Debug.WriteLine("Failed to create");
                    return;
                }
            }

            var message = new ValueSet();

            message.Add("Request", "StartAnimator");
            AppServiceResponse response = await this.appService.SendMessageAsync(message);

            string result = "";

            if (response.Status == AppServiceResponseStatus.Success)
            {
                // Get the data  that the service sent to us.
                if (response.Message["Response"] as string == "OK")
                {
                    result = response.Message["StatusCode"] as string;
                }
            }

            message.Clear();
        }
Beispiel #45
0
        private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var Deferral = args.GetDeferral();

            try
            {
                if (SpinWait.SpinUntil(() => Connections.Count == 2, 8000))
                {
                    AppServiceConnection AnotherConnection = Connections.FirstOrDefault((Con) => Con != sender);

                    AppServiceResponse AnotherRespose = await AnotherConnection.SendMessageAsync(args.Request.Message);

                    if (AnotherRespose.Status == AppServiceResponseStatus.Success)
                    {
                        await args.Request.SendResponseAsync(AnotherRespose.Message);
                    }
                }
                else
                {
                    ValueSet Value = new ValueSet
                    {
                        { "Error", "Another device failed to make a peer-to-peer connection within the specified time" }
                    };

                    await args.Request.SendResponseAsync(Value);
                }
            }
            catch
            {
                ValueSet Value = new ValueSet
                {
                    { "Error", "Some exceptions were thrown while transmitting the message" }
                };

                await args.Request.SendResponseAsync(Value);
            }
            finally
            {
                Deferral.Complete();
            }
        }
        private void CommunicationService_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            AppServiceDeferral messageDeferral = args.GetDeferral();
            ValueSet           message         = args.Request.Message;
            string             cmd             = message["Command"] as string;

            try
            {
                // Return the data to the caller.
                if (cmd == "Log")
                {
                    string level = message["Level"] as string;
                    string msg   = message["Message"] as string;

                    switch (level)
                    {
                    case "Comment":
                        Log.Comment("[Host] {0}", msg);
                        break;

                    case "Warning":
                        Log.Warning("[Host] {0}", msg);
                        break;

                    case "Error":
                        Log.Error("[Host] {0}", msg);
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Exception receiving message: {0}", e.Message);
            }
            finally
            {
                // Complete the deferral so that the platform knows that we're done responding to the app service call.
                // Note: for error handling: this must be called even if SendResponseAsync() throws an exception.
                messageDeferral.Complete();
            }
        }
Beispiel #47
0
            private async void Initialize()
            {
                try
                {
                    // this is the unique package family name of the Console Ouput app
                    const string consoleOutputPackageFamilyName = "49752MichaelS.Scherotter.ConsoleOutput_9eg5g21zq32qm";
                    var          options = new LauncherOptions
                    {
                        PreferredApplicationDisplayName       = "Console Output",
                        PreferredApplicationPackageFamilyName = consoleOutputPackageFamilyName,
                        TargetApplicationPackageFamilyName    = consoleOutputPackageFamilyName,
                    };
                    // launch the ConsoleOutput app
                    var uri = new Uri(string.Format("consoleoutput:?Title={0}&input=true", Windows.ApplicationModel.Package.Current.DisplayName));
                    if (!await Launcher.LaunchUriAsync(uri, options))
                    {
                        return;
                    }

                    var appServiceConnection = new AppServiceConnection
                    {
                        AppServiceName    = "consoleoutput",
                        PackageFamilyName = consoleOutputPackageFamilyName
                    };

                    var status = await appServiceConnection.OpenAsync();

                    if (status == AppServiceConnectionStatus.Success)
                    {
                        _appServiceConnection = appServiceConnection;

                        // because we want to get messages back from the console, we
                        // launched the app with the input=true parameter
                        _appServiceConnection.RequestReceived += OnRequestReceived;
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Error initializing {0} -- {1}", nameof(UwpConsoleOutputProvider), ex);
                }
            }
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            AppServiceDeferral deferral = args.GetDeferral();
            ValueSet           message  = args.Request.Message;

            switch (message["type"])
            {
            case "connect":
            {
                VoiceServerUpdate data  = JsonConvert.DeserializeObject <VoiceServerUpdate>(message["config"] as string);
                VoiceState        state = JsonConvert.DeserializeObject <VoiceState>(message["state"] as string);
                webrtcManager.SetRecordingDevice(message["inputId"] as string);
                webrtcManager.SetPlaybackDevice(message["outputId"] as string);
                ConnectToVoiceChannel(data, state);
            }
            break;

            case "disconnect":
                webrtcManager.Destroy();
                voipCall?.NotifyCallEnded();
                voipCall        = null;
                voiceConnection = null;
                break;

            case "voiceStateUpdate":
            {
                // Todo: handle here
                VoiceState state = JsonConvert.DeserializeObject <VoiceState>(message["state"] as string);
            }
            break;

            case "inputDevice":
                webrtcManager.SetRecordingDevice(message["id"] as string);
                break;

            case "outputDevice":
                webrtcManager.SetPlaybackDevice(message["id"] as string);
                break;
            }
            deferral.Complete();
        }
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var    message = args.Request.Message;
            string cmd     = message["cmd"] as string;
            string txt     = message["txt"] as string;

            switch (cmd)
            {
            case "Encode":
            {
                var messageDeferral = args.GetDeferral();

                string result        = Encode(txt);
                var    returnMessage = new ValueSet();
                returnMessage.Add("result", result);
                var responseStatus = await args.Request.SendResponseAsync(returnMessage);

                messageDeferral.Complete();
                break;
            }

            case "Decode":
            {
                var messageDeferral = args.GetDeferral();

                string result        = Decode(txt);
                var    returnMessage = new ValueSet();
                returnMessage.Add("result", result);
                var responseStatus = await args.Request.SendResponseAsync(returnMessage);

                messageDeferral.Complete();
                break;
            }

            case "Quit":
            {
                serviceDeferral.Complete();
                break;
            }
            }
        }
Beispiel #50
0
        /// <summary>
        /// Creates the app service connection
        /// </summary>
        static void ThreadProc()
        {
            connection = new AppServiceConnection();
            connection.AppServiceName    = "CommunicationService";
            connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
            connection.RequestReceived  += Connection_RequestReceived;
            var ax = connection.OpenAsync();

            ax.Completed = (info, asyncStatus) =>
            {
                AppServiceConnectionStatus status = info.GetResults();
                switch (status)
                {
                case AppServiceConnectionStatus.Success:
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Connection established - waiting for requests");
                    Console.WriteLine();
                    break;

                case AppServiceConnectionStatus.AppNotInstalled:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("The app AppServicesProvider is not installed.");
                    return;

                case AppServiceConnectionStatus.AppUnavailable:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("The app AppServicesProvider is not available.");
                    return;

                case AppServiceConnectionStatus.AppServiceUnavailable:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("The app AppServicesProvider is installed but it does not provide the app service {0}.", connection.AppServiceName);
                    return;

                case AppServiceConnectionStatus.Unknown:
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(string.Format("An unkown error occurred while we were trying to open an AppServiceConnection."));
                    return;
                }
            };
        }
        private async void FileReceiver_FileTransferProgress(FileTransfer.FileTransferProgressEventArgs e)
        {
            ShowFileTransferProgressToast(e);

            await notificationSemaphoreSlim.WaitAsync();

            waitingNumSemaphore++;
#if NOTIFICATIONHANDLER_DEBUGINFO
            System.Diagnostics.Debug.WriteLine("Progress " + e.CurrentPart + "/" + e.Total + " : " + e.State);
#endif

            if (!await ConnectToNotificationService())
            {
                waitingNumSemaphore--;
                notificationSemaphoreSlim.Release();
                return;
            }

            try
            {
                // Call the service.
                var message = new ValueSet();
                message.Add("Type", "FileTransferProgress");
                message.Add("Data", JsonConvert.SerializeObject(e));

                AppServiceResponse response = await this.notificationService.SendMessageAsync(message);

                if (response.Status != AppServiceResponseStatus.Success)
                {
                    Debug.WriteLine("Failed to send message to notification service: " + response.Status);
                    notificationService = null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to send message to notification service (an exception was thrown): " + ex.ToString());
                notificationService = null;
            }
            waitingNumSemaphore--;
            notificationSemaphoreSlim.Release();
        }
Beispiel #52
0
        private async Task SendMessageToRemoteAppServiceAsync(AppServiceConnection connection)
        {
            // Send message if connection to the remote app service is open.
            if (connection != null)
            {
                //Set up the inputs and send a message to the service.
                ValueSet inputs = new ValueSet();
                inputs.Add("minvalue", m_minimumValue);
                inputs.Add("maxvalue", m_maximumValue);
                UpdateStatus("Sent message to remote app service. Waiting for a response...", NotifyType.StatusMessage);
                AppServiceResponse response = await connection.SendMessageAsync(inputs);

                if (response.Status == AppServiceResponseStatus.Success)
                {
                    if (response.Message.ContainsKey("result"))
                    {
                        string resultText = response.Message["result"].ToString();
                        if (string.IsNullOrEmpty(resultText))
                        {
                            UpdateStatus("Remote app service did not respond with a result.", NotifyType.ErrorMessage);
                        }
                        else
                        {
                            UpdateStatus("Result = " + resultText, NotifyType.StatusMessage);
                        }
                    }
                    else
                    {
                        UpdateStatus("Response from remote app service does not contain a result.", NotifyType.ErrorMessage);
                    }
                }
                else
                {
                    UpdateStatus("Sending message to remote app service failed with error - " + response.Status.ToString(), NotifyType.ErrorMessage);
                }
            }
            else
            {
                UpdateStatus("Not connected to any app service. Select a device to open a connection.", NotifyType.ErrorMessage);
            }
        }
Beispiel #53
0
        private void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            // win32 component finished
            if (taskCompletionSource == null)
            {
                return;
            }

            object result;

            args.Request.Message.TryGetValue("RESULT", out result);
            if ((string)result == "SUCCESS")
            {
                taskCompletionSource.TrySetResult(true);
            }
            else
            {
                LogService.Log.Error($"FullTrustProcess returned an error. ({ApplicationData.Current.LocalSettings.Values["fullTrustProcessError"]})");
                taskCompletionSource.TrySetResult(false);
            }
        }
        private void Close()
        {
            var taskDeferral = Interlocked.Exchange(ref this.taskDeferral, null);

            if (taskDeferral is null)
            {
                return;
            }

            AppServiceHandler.RemoveUnused(this.appServiceConnection);

            this.appServiceConnection.RequestReceived -= OnAppServiceRequestReceived;
            this.appServiceConnection.ServiceClosed   -= OnServiceClosed;
            this.appServiceConnection.Dispose();
            this.appServiceConnection = null;

            this.taskInstance.Canceled -= OnBackgroundTaskCanceled;
            this.taskInstance           = null;

            taskDeferral.Complete();
        }
Beispiel #55
0
        /// <summary>
        /// Receives message from UWP app and sends a response back
        /// </summary>
        private static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var input = args.Request.Message;

            if (input["Request"].ToString() == "Conversion")
            {
                ValueSet returnData = new ValueSet();

                double amount = Convert.ToInt32(input["Amount"] as string);
                int    period = Convert.ToInt32(input["Period"] as string);
                double rate   = Convert.ToDouble(input["Rate"] as string);

                ValueSet valueSet = new ValueSet();
                valueSet.Add("Response", GEtEMI(amount, period, rate).ToString());
                args.Request.SendResponseAsync(valueSet).Completed += delegate { };
            }
            else if (input["Request"].ToString() == "ColorChange")
            {
                mainWindowCallback.OnBackgroundColorChange(input["ColorCode"].ToString());
            }
        }
Beispiel #56
0
        private async Task <bool> ConnectAsync()
        {
            if (_appServiceConnection != null)
            {
                return(true);
            }

            var appServiceConnection = new AppServiceConnection();

            appServiceConnection.AppServiceName    = "InProcessAppService";
            appServiceConnection.PackageFamilyName = Package.Current.Id.FamilyName;
            appServiceConnection.RequestReceived  += AppServiceConnection_RequestReceived;
            var r = await appServiceConnection.OpenAsync() == AppServiceConnectionStatus.Success;

            if (r)
            {
                _appServiceConnection = appServiceConnection;
            }

            return(r);
        }
Beispiel #57
0
        private async void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var deferral = args.GetDeferral();
            var op       = args.Request.Message["Op"] as string;
            var res      = new ValueSet();

            if (op == "Clipboard")
            {
                res.Add("Res", await RunAsync(GetClipboard));
            }
            else
            {
                res.Add("Res", string.Empty);
            }

            Debug.WriteLine($"Clipboard: {res["Res"].ToString()}");
            var status = await args.Request.SendResponseAsync(res);

            deferral.Complete();
            Debug.WriteLine($"SendStatus: {status.ToString()}");
        }
Beispiel #58
0
        public static async void CreateAppService(RemoteSystem remoteSystem)
        {
            AppServiceConnection connection = new AppServiceConnection();

            connection.AppServiceName    = "com.microsoft.test.cdppingpongservice";
            connection.PackageFamilyName = Package.Current.Id.FamilyName;

            RemoteSystemConnectionRequest connectionRequest = new RemoteSystemConnectionRequest(remoteSystem);
            var status = await connection.OpenRemoteAsync(connectionRequest);

            if (SuccessfulAppServiceClientConnectionStatus(status, connection, remoteSystem) == true)
            {
                connection.RequestReceived += PingPongConnection.OnRequestReceived;

                NotifyAppServiceConnected(connection);
            }
            else
            {
                DebugWrite($"Failed to create app service connection to ({remoteSystem.DisplayName}, {remoteSystem.Id})");
            }
        }
Beispiel #59
0
        /// <summary>
        /// Handles AppServiceConnection opening.
        /// </summary>
        /// <param name="args">Background Activation details.</param>
        protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)
        {
            base.OnBackgroundActivated(args);

            IBackgroundTaskInstance taskInstance = args.TaskInstance;

            if (taskInstance.Task.Name == "SuspendBackgroundTask")
            {
                _suspendDeferral       = taskInstance.GetDeferral();
                taskInstance.Canceled += SuspendTask_OnCanceled;
            }
            else
            {
                AppServiceTriggerDetails appService = taskInstance.TriggerDetails as AppServiceTriggerDetails;
                _appServiceDeferral    = taskInstance.GetDeferral();
                taskInstance.Canceled += TaskInstance_OnCanceled;
                _appServiceConnection  = appService.AppServiceConnection;
                _appServiceConnection.RequestReceived += HandleServiceRequest;
                ConnectedToAppService?.Invoke(null, null);
            }
        }
        private async Task <string> ResubmitRequestAppServiceAsync(HwandazaCommand command)
        {
            //re-establish appservice connection
            await AppServiceInstance.SetAppServiceConnection();

            _appServiceConnection = AppServiceInstance.Instance.GetAppServiceConnection();

            var responseContent = "{}";

            var appServiceResponse = RequestAppServiceAsync(command).Result;

            if (appServiceResponse != null)
            {
                if (appServiceResponse.Status == AppServiceResponseStatus.Success)
                {
                    responseContent = appServiceResponse.Message["Response"] as string;
                }
            }

            return(responseContent);
        }