public static async Task <bool> GetCallDurationAsync() { VoipPhoneCall call = VoipCall; AppServiceRequest request = AppRequest; AppServiceDeferral deferal = AppRequestDeferal; TimeSpan timeSpan = new TimeSpan(); if (call != null) { call.NotifyCallActive(); timeSpan = DateTimeOffset.Now.Subtract(call.StartTime); } if (request != null) { ValueSet response = new ValueSet(); response[BackgroundOperation.Result] = timeSpan.ToString(); await request.SendResponseAsync(response); } if (deferal != null) { deferal.Complete(); } return(true); }
public static async void EndCallAsync() { AppServiceRequest request = AppRequest; AppServiceDeferral deferal = AppRequestDeferal; try { EndCall(); if (request != null) { ValueSet response = new ValueSet(); response[BackgroundOperation.Result] = (int)OperationResult.Succeeded; await request.SendResponseAsync(response); } if (deferal != null) { deferal.Complete(); } } finally { AppRequest = null; AppRequestDeferal = null; } }
/// <summary> /// Invokes the method from the message on the handler object and sends back the return value /// </summary> public static async void HandleRequest(AppServiceRequest request, object handler, string message) { var invoker = new ChannelInvoker(handler); var result = invoker.ProcessRequest(message); await SendResponse(request, result); }
/// <summary> /// Serializes and sends the response for the AppServiceRequest /// </summary> private static async Task SendResponse(AppServiceRequest request, InvocationResult result) { if (result.Result == null) { return; } object response = null; var asyncAction = result.Result as IAsyncAction; if (asyncAction != null) { await asyncAction; } else { var awaitAsyncOperationMethod = typeof(AppServiceChannelHelper).GetRuntimeMethods() .Single(method => method.Name == nameof(AwaitAsyncOperation)); var awaitMethod = awaitAsyncOperationMethod.MakeGenericMethod(result.ResultType.GenericTypeArguments[0]); response = awaitMethod.Invoke(null, new[] { result.Result }); } //Send a new ValueSet with the key as a random string and the value as the serialized result await request.SendResponseAsync(new ValueSet { { Guid.NewGuid().ToString(), JsonConvert.SerializeObject(response) } }); }
public ASRequest(AppServiceRequest internalRequest, AppServiceDeferral internalRequestDeferral, ASConnection connection) { _connection = connection; _internalRequest = internalRequest; _internalRequestDeferral = internalRequestDeferral; Message = _connection._serializer.DeserializeFromValueSet(internalRequest.Message); }
private static async Task SendResponse(AppServiceRequest request, InvocationResult result) { if (result.Result == null) return; await request.SendResponseAsync(new ValueSet { {Guid.NewGuid().ToString(), JsonConvert.Serialize(result.Result)} }); }
public async Task HandleDeferral(AppServiceDeferral deferral, AppServiceRequest request) { StartupTask.WriteTelemetryEvent("Action_AppService"); ValueSet returnMessage = new ValueSet(); await request.SendResponseAsync(returnMessage); deferral.Complete(); }
/// <summary> /// Serializes and sends the response for the AppServiceRequest /// </summary> private static async Task SendResponse(AppServiceRequest request, InvocationResult result) { if (result.Result == null) return; //Send a new ValueSet with the key as a random string and the value as the serialized result await request.SendResponseAsync(new ValueSet { {Guid.NewGuid().ToString(), JsonConvert.Serialize(result.Result)} }); }
internal static async Task <RespondResult> SendResponseAsync(this AppServiceRequest request, object message, IObjectSerializer serializer) { var valueSet = serializer.SerializeToValueSet(message); var internalStatus = await request.SendResponseAsync(valueSet); var success = internalStatus == AppServiceResponseStatus.Success; return(new RespondResult(success ? ResponseStatus.Success : ResponseStatus.Failure, internalStatus)); }
private static void SendOrders(AppServiceRequest request, string connectionString) { Console.WriteLine("Received GetOrders request. Working on it..."); var json = GetOrdersAsJson(connectionString); ValueSet returnValues = new ValueSet(); Console.WriteLine("Adding return value. {0} : {1}", "response", json); returnValues.Add("response", json); Console.WriteLine("Returning response with orders as json"); request.SendResponseAsync(returnValues).Completed += delegate { }; }
//[DllImport("user32.dll")] //static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); //private static void Minimize() //{ // var hwnd = Process.GetCurrentProcess().MainWindowHandle; // ShowWindow(hwnd, 2); //} //[DllImport("user32.dll")] //static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); //private static void ExitConoleApp() //{ // Console.WriteLine("Exiting SQL Bridge"); // var hwnd = Process.GetCurrentProcess().MainWindowHandle; // const uint WM_CHAR = 0x0102; // PostMessage(hwnd, WM_CHAR, 13, 0); //} #endregion private static void SendAllProductsAsync(AppServiceRequest request) { Console.WriteLine("Received GetProducts request. Working on it..."); var json = GetProductsAsJson(); ValueSet returnValues = new ValueSet(); //Console.WriteLine("Adding return value. {0} : {1}", "response", json); returnValues.Add("response", json); Console.WriteLine("Returning response with products as json"); request.SendResponseAsync(returnValues).Completed += delegate { }; }
public static IAsyncOperation <AppServiceResponseStatus> SendResponseAsync(this AppServiceRequest request, IResponseMessage message) { var rqmsg = request.Message; var method = rqmsg["Method"].ToString(); var rsType = MappingInfo.RequestToResponseMap[MappingInfo.MethodToRequestMap[method]]; if (!(message is ErrorResponse || message.GetType() == rsType)) { throw new ArgumentException($"类型错误,应为 {rsType} 或 {typeof(ErrorResponse)}。", nameof(message)); } return(request.SendResponseAsync(message.ToValueSet())); }
public static IRequestMessage GetMessage(this AppServiceRequest request) { if (request is null) { throw new ArgumentNullException(nameof(request)); } var message = request.Message; var method = message["Method"].ToString(); var data = message["Data"].ToString(); var requestType = MappingInfo.MethodToRequestMap[method]; return((IRequestMessage)JsonConvert.DeserializeObject(data, requestType)); }
/// <summary> /// Serializes and sends the response for the AppServiceRequest /// </summary> private static async Task SendResponse(AppServiceRequest request, InvocationResult result) { if (result.Result == null) { return; } //Send a new ValueSet with the key as a random string and the value as the serialized result await request.SendResponseAsync(new ValueSet { { Guid.NewGuid().ToString(), JsonConvert.Serialize(result.Result) } }); }
private static void SaveOrderAsync(AppServiceRequest request, string json) { Console.WriteLine("Received SaveOrder request. Working on it..."); Order order = new Order(); order.LoadFromJson(json); var orderID = SaveOrderAndDetails(order); ValueSet returnValues = new ValueSet(); returnValues.Add("response", string.IsNullOrEmpty(orderID)? "ERROR": orderID); request.SendResponseAsync(returnValues).Completed += delegate { }; }
public async Task MessageCarrierReceivedAsync(AppServiceRequest request) { Guid guid = Guid.NewGuid(); latestCarrierCode = guid; int counter = 0; HasWaitingMessageCarrier = true; while (true) { await sendQueueSemaphore.WaitAsync(); var queueItem = sendQueue.FirstOrDefault(x => x.RemoteSystemId == (string)request.Message["SenderId"]); if (queueItem == null) { sendQueueSemaphore.Release(); if (latestCarrierCode != guid) { Debug.WriteLine($"A newer carrier is here. I will retire now. I was waiting for {counter} cycles."); break; } else if (counter > _maxWaitTime) { Debug.WriteLine($"Okay I've waited {counter} cycles, that's enough. Bye!"); break; } Debug.WriteLine($"Queue is empty. Message Carrier is waiting for some message to arrive... {counter}"); await Task.Delay(1000); counter++; continue; } var vs = queueItem.Data.ToValueSet(); var result = await request.SendResponseAsync(vs); queueItem.SetSendResult((RomeAppServiceResponseStatus)result); sendQueue.Remove(queueItem); sendQueueSemaphore.Release(); HasWaitingMessageCarrier = false; break; } }
private async void AppServiceConnectionRequestReceived(AppServiceRequest request) { this.LogMessage("Received AppService request. Sending response."); var status = await request.SendResponseAsync(this.CreatePongMessage(request.Message)); if (status == AppServiceResponseStatus.Success) { this.LogMessage("Successfully sent response."); } else { this.LogMessage("Failed to send response."); } }
public static async Task <ASConnection> AcceptConnectionAsync(AppServiceTriggerDetails e, BackgroundTaskDeferral connectionDeferral, IObjectSerializer serializer) { // Receive connection request, send connection response AppServiceRequest request = null; AppServiceDeferral deferral = null; var gotRequest = new SemaphoreSlim(0); e.AppServiceConnection.RequestReceived += OnRequestReceived; await gotRequest.WaitAsync(); e.AppServiceConnection.RequestReceived -= OnRequestReceived; var message = serializer.DeserializeFromValueSet(request.Message); if (message is ConnectionRequestMessage connectionRequest) { // Accept connection request var connectionId = "AS_" + Guid.NewGuid(); var connectionResponse = new ConnectionResponseMessage(connectionId); await request.SendResponseAsync(serializer.SerializeToValueSet(connectionResponse)); deferral.Complete(); return(new ASConnection( connectionId, e.AppServiceConnection, connectionDeferral, e.IsRemoteSystemConnection, serializer)); } else { // Wrong message received => reject connection var connectionResponse = new ConnectionResponseMessage(null); await request.SendResponseAsync(serializer.SerializeToValueSet(connectionResponse)); deferral.Complete(); connectionDeferral.Complete(); e.AppServiceConnection.Dispose(); return(null); } void OnRequestReceived(AppServiceConnection _, AppServiceRequestReceivedEventArgs r) { request = r.Request; deferral = r.GetDeferral(); gotRequest.Release(); } }
public async Task ProcessRequest(AppServiceRequest request) { ValueSet message = request.Message; string result = ""; if (message["command"] is string command) { switch (command) { case "pause": _dispatcherQueue.TryEnqueue(_player.Pause); result = "Ok"; break; case "resume": _dispatcherQueue.TryEnqueue(_player.Play); result = "Ok"; break; default: result = "Unknown command: " + command; break; } } else if (message["state"] is string state) { switch (state) { case "playback": result = _player.PlaybackState.ToString(); break; case "volume": result = _player.GlobalVolume.ToString(); break; } } else { result = "No valid keys found"; } ValueSet returnMessage = new ValueSet(); returnMessage.Add("result", result); await request.SendResponseAsync(returnMessage); }
public void Run(IBackgroundTaskInstance taskInstance) { if (!(taskInstance.TriggerDetails is AppServiceTriggerDetails appServiceTriggerDetails)) { return; } AppServiceConnection appServiceConnection = appServiceTriggerDetails.AppServiceConnection; appServiceConnection.RequestReceived += async(sender, args) => { AppServiceDeferral appServiceDeferral = args.GetDeferral(); AppServiceRequest appServiceRequest = args.Request; ValueSet request = appServiceRequest.Message; await appServiceRequest.SendResponseAsync(new ValueSet { { "count", request.Count } }); appServiceDeferral.Complete(); }; }
public static async void SendResponse(ValueSet response) { AppServiceRequest request = AppRequest; AppServiceDeferral deferal = AppRequestDeferal; try { if (request != null) { await request.SendResponseAsync(response); } } finally { if (deferal != null) { deferal.Complete(); deferal = null; } AppRequest = null; } }
private async Task <AppServiceResponseStatus> DisconnectAsync(string deviceID, AppServiceRequest request) { var device = _devices.FirstOrDefault(D => D.Id == deviceID); if (device == null) { return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, $"Not found device by DeviceID. DeviceID=[{deviceID}]" }, })); } try { device.DeviceStatusUpdated -= OnDeviceStatusUpdated; await device.DisconnectAsync(); _connectedDevice = null; return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, true }, { Parameters.Details, String.Empty }, })); } catch (Exception e) { return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, e.Message }, })); } }
public AppServiceRequestWrapper(AppServiceRequest request) { _request = request; }
private async Task <AppServiceResponseStatus> RequestSetupTemperatureChangeAsync(string deviceID, int leftTemperature, int rightTemperature, AppServiceRequest request) { var device = _devices.FirstOrDefault(D => D.Id == deviceID); if (device == null) { return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, $"Not found device by DeviceID. DeviceId=[{deviceID}]" }, })); } try { await device.RequestSetupTemperatureChangeAsync(leftTemperature, rightTemperature); return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, true }, { Parameters.Details, JsonConvert.SerializeObject(new int[] { device.SetupLeftTemperature, device.SetupRightTemperature }, Formatting.Indented) }, })); } catch (Exception e) { return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, e.Message }, })); } }
/// <summary> /// Handles unknown request and return error message` /// </summary> private static IAsyncOperation <AppServiceResponseStatus> SendUnknownRequestErrorAsync(AppServiceRequest request, string requestString) { ConsoleColor oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Received unknown request: \"{0}\"", requestString); string message = "Unknown Request"; ValueSet returnValues = new ValueSet(); returnValues.Add("ErrorMessage", message); Console.WriteLine("Sending error message: \"{0}\"", message); Console.WriteLine(); Console.ForegroundColor = oldColor; return(request.SendResponseAsync(returnValues)); }
private async Task <AppServiceResponseStatus> RequestVolumeChangeAsync(string deviceID, VolumeLevels volumeLevel, AppServiceRequest request) { var device = _devices.FirstOrDefault(D => D.Id == deviceID); if (device == null) { return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, $"Not found device by DeviceID. DeviceId=[{deviceID}]" }, })); } try { await device.RequestVolumeChangeAsync(volumeLevel); return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, true }, { Parameters.Details, device.VolumeLevel.ToString() }, })); } catch (Exception e) { return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, e.Message }, })); } }
/// <summary> /// Handles "GetCategories" request and returns data of product categories to UWA /// </summary> private static IAsyncOperation <AppServiceResponseStatus> SendCategoriesAsync(AppServiceRequest request) { ConsoleColor oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Received GetCategories request."); ValueSet returnValues = new ValueSet(); try { var db = new Database(dbFileFolder); // Serialize all DB query results into JSON // Because AppService only support passing data of primitive types int count = 0; JsonArray categories = new JsonArray(); foreach (var cat in db.GetCategories()) { Console.WriteLine("Adding return value. {0} : {1}", count.ToString(), cat.Name); JsonObject jsonCat = new JsonObject(); jsonCat.Add("ID", JsonValue.CreateNumberValue(cat.ID)); jsonCat.Add("Name", JsonValue.CreateStringValue(cat.Name)); jsonCat.Add("Description", JsonValue.CreateStringValue(cat.Description)); categories.Add(jsonCat); count++; } returnValues.Add("Result", categories.Stringify()); Console.WriteLine("Adding return value. {0} : {1}", "ResultCount", count); returnValues.Add("ResultCount", count); Console.WriteLine("Adding return value. {0} : {1}", "ErrorMessage", "Succeeded"); returnValues.Add("ErrorMessage", "Succeeded"); Console.WriteLine("Sending result with \"{0}\" categories", count); Console.WriteLine(); Console.ForegroundColor = oldColor; } catch (Exception e) { Console.WriteLine(e.Message); returnValues.Add("ErrorMessage", e.Message); } return(request.SendResponseAsync(returnValues)); }
private async Task <AppServiceResponseStatus> ScanAsync(int timeoutMilliseconds, AppServiceRequest request) { _devices = await _bluetoothLEService.ScanAsync(timeoutMilliseconds); var jsonResult = JsonConvert.SerializeObject(_devices, Formatting.Indented); return(await request.SendResponseAsync(new ValueSet() { { Parameters.Devices, jsonResult }, })); }
private async Task <AppServiceResponseStatus> ConnectAsync(string deviceID, string uniqueId, AppServiceRequest request) { var device = _devices.FirstOrDefault(D => D.Id == deviceID); if (device == null) { return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, $"Not found device by DeviceID. DeviceID=[{deviceID}]" }, })); } try { uniqueId = await device.ConnectAsync(uniqueId); _connectedDevice = device; _connectedDevice.DeviceStatusUpdated += OnDeviceStatusUpdated; return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, true }, { Parameters.Details, JsonConvert.SerializeObject(device, Formatting.Indented) }, { Parameters.UniqueID, uniqueId }, })); } catch (Exception e) { if (device.IsConnected) { await device.DisconnectAsync(); } return(await request.SendResponseAsync(new ValueSet() { { Parameters.Result, false }, { Parameters.Details, e.Message }, })); } }
/// <summary> /// Handles "GetProducts" request and returns data of products of give category to UWA /// </summary> private static IAsyncOperation <AppServiceResponseStatus> SendProductsByCategoryAsync(AppServiceRequest request, int categoryId) { ConsoleColor oldColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Received GetProducts request for category id: \"{0}\".", categoryId); ValueSet returnValues = new ValueSet(); try { var db = new Database(dbFileFolder); // Serialize all DB query results into JSON // Because AppService only support passing data of primitive types int count = 0; JsonArray products = new JsonArray(); foreach (var prod in db.GetProductsByCategory(categoryId)) { Console.WriteLine("Adding return value. {0} : {1}", count.ToString(), prod.Name); JsonObject jsonProd = new JsonObject(); jsonProd.Add("ID", JsonValue.CreateNumberValue(prod.ID)); jsonProd.Add("Name", JsonValue.CreateStringValue(prod.Name)); jsonProd.Add("QuantityPerUnit", JsonValue.CreateStringValue(prod.QuantityPerUnit)); jsonProd.Add("UnitPrice", JsonValue.CreateNumberValue(prod.UnitPrice)); jsonProd.Add("UnitsInStock", JsonValue.CreateNumberValue(prod.UnitsInStock)); jsonProd.Add("UnitsOnOrder", JsonValue.CreateNumberValue(prod.UnitsOnOrder)); jsonProd.Add("ReorderLevel", JsonValue.CreateNumberValue(prod.ReorderLevel)); jsonProd.Add("Discontinued", JsonValue.CreateBooleanValue(prod.Discontinued)); jsonProd.Add("SupplierID", JsonValue.CreateNumberValue(prod.SupplierID)); jsonProd.Add("CategoryID", JsonValue.CreateNumberValue(prod.CategoryID)); products.Add(jsonProd); count++; } returnValues.Add("Result", products.Stringify()); Console.WriteLine("Adding return value. {0} : {1}", "ResultCount", count); returnValues.Add("ResultCount", count); Console.WriteLine("Adding return value. {0} : {1}", "ErrorMessage", "Succeeded"); returnValues.Add("ErrorMessage", "Succeeded"); Console.WriteLine("Sending result with \"{0}\" products", count); Console.WriteLine(); Console.ForegroundColor = oldColor; } catch (Exception e) { Console.WriteLine(e.Message); returnValues.Add("ErrorMessage", e.Message); } return(request.SendResponseAsync(returnValues)); }