コード例 #1
0
        // UWP Class emits Message event and can handle async handlers and await them.
        // This method only returns task when creating new child process which takes some time. We need
        // to postpone response to caller (app behind the UWP class) until we have either PID of the process
        // or error message thrown while spawning the process.
        static void OnMessage(ValueSet req)
        {
            // Only command without PID is starting a file.
            string cmd = null;

            if (req.ContainsKey("cmd"))
            {
                cmd = req["cmd"] as string;
            }
            if (cmd == "startProcess")
            {
                var child = StartProcess(req);
            }
            else if (req.ContainsKey("cid"))
            {
                // From now on we deal with exact process.
                // Get PID and Process instance of targetted process.
                var child = GetProcess(req);
                if (child == null)
                {
                    return;
                }
                // Handlers
                if (req.ContainsKey("fd") && req.ContainsKey("data"))
                {
                    var fd = Convert.ToInt32(req["fd"]);
                    child.Write(req["data"] as byte[], fd);
                }
                else if (cmd == "killProcess")
                {
                    child.Kill();
                }
            }
        }
コード例 #2
0
        bool IsValidRequestDataSet(ValueSet valueSet, out Guid characteristicUuid, out string data)
        {
            if (valueSet == null)
            {
                characteristicUuid = Guid.Empty;
                data = string.Empty;
                return(false);
            }

            if (!valueSet.ContainsKey("uuid") || !Guid.TryParse(valueSet["uuid"] as string, out characteristicUuid))
            {
                characteristicUuid = Guid.Empty;
                data = string.Empty;
                return(false);
            }

            if (!valueSet.ContainsKey("data") || valueSet["data"] == null)
            {
                data = string.Empty;
                return(false);
            }

            data = valueSet["data"] as string;

            return(!string.IsNullOrWhiteSpace(data));
        }
コード例 #3
0
 private void SetupInfo()
 {
     Proc.StartInfo = Info = new ProcessStartInfo();
     // Create the process without (visible) window.
     Info.WindowStyle     = ProcessWindowStyle.Hidden;
     Info.CreateNoWindow  = true;
     Info.UseShellExecute = false;
     // Request admin access if needed (prompts UAC dialog)
     //if (req.ContainsKey("admin"))
     //	Info.Verb = "runas";
     // Setup file and to be started and with what arguments.
     Info.FileName = req["file"] as string;
     if (req.ContainsKey("args"))
     {
         // C# strings are utf16 by default. Encoding of arguments property cannot be controlled
         // like stdio streams with so we need to convert the args manually.
         var utf16  = req["args"] as string;
         var buffer = Encoding.Default.GetBytes(utf16);
         var utf8   = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
         Info.Arguments = utf8;
     }
     if (req.ContainsKey("cwd"))
     {
         Info.WorkingDirectory = req["cwd"] as string;
     }
 }
コード例 #4
0
        public override async Task <object> ExecuteAsync(ValueSet parameters)
        {
            if (_serviceName.IsNullorEmpty())
            {
                throw new InvalidProgramException("Extension is not a service");
            }
            try
            {
                // do app service call
                using (var connection = new AppServiceConnection())
                {
                    // service name was in properties
                    connection.AppServiceName = _serviceName;

                    // package Family Name is in the extension
                    connection.PackageFamilyName = this.AppExtension.Package.Id.FamilyName;

                    // open connection
                    AppServiceConnectionStatus status = await connection.OpenAsync();

                    if (status != AppServiceConnectionStatus.Success)
                    {
                        throw new InvalidOperationException(status.ToString());
                    }
                    else
                    {
                        // send request to service
                        // get response
                        AppServiceResponse response = await connection.SendMessageAsync(parameters);

                        if (response.Status == AppServiceResponseStatus.Success)
                        {
                            ValueSet message = response.Message as ValueSet;
                            if (message.ContainsKey("status") && (int)message["status"] == 1)
                            {
                                if (message.ContainsKey("search_result") && message["search_result"] is string s)
                                {
                                    return(GetGenericMusicItem(s));
                                }
                                if (message.ContainsKey("song_result") && message["song_result"] is string t)
                                {
                                    return(GetOnlineSong(t));
                                }
                                if (message.ContainsKey("album_result") && message["album_result"] is string r)
                                {
                                    return(GetAlbum(r, message["songs"] as string, message["album_artists"] as string));
                                }
                            }
                        }
                    }
                }
                return(null);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #5
0
        public void LoadSettings(ValueSet settings)
        {
            if (settings.ContainsKey("GazeCursor.CursorRadius"))
            {
                CursorRadius = (int)settings["GazeCursor.CursorRadius"];
            }

            if (settings.ContainsKey("GazeCursor.CursorVisibility"))
            {
                IsCursorVisible = (bool)settings["GazeCursor.CursorVisibility"];
            }
        }
コード例 #6
0
        private bool Update(ThreeAddrLine line, ValueSet vals)
        {
            if (!ThreeAddrOpType.IsDefinition(line.OpType))
            {
                return(false);
            }

            var ret = ReachingValues.Compute(line, vals);

            vals[line.Accum] = ret;
            bool ok = false;


            if (ComputeHelper.IsConst(ret))
            {
                if (ThreeAddrOpType.Assign == line.OpType && line.RightOp == ret)
                {
                    return(false);
                }

                line.OpType  = ThreeAddrOpType.Assign;
                line.LeftOp  = null;
                line.RightOp = ret;



                return(true);
            }



            if (line.LeftOp != null && vals.ContainsKey(line.LeftOp))
            {
                if (vals[line.LeftOp] != "NAC")
                {
                    line.LeftOp = vals[line.LeftOp];
                    ok          = true;
                }
            }


            if (line.RightOp != null && vals.ContainsKey(line.RightOp))
            {
                if (vals[line.RightOp] != "NAC")
                {
                    line.RightOp = vals[line.RightOp];
                    ok           = true;
                }
            }


            return(ok);
        }
コード例 #7
0
        private async void OnAppServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            AppServiceDeferral messageDeferral = args.GetDeferral();
            ValueSet           message         = args.Request.Message;

            if (message.ContainsKey("LIDAR"))
            {
                await args.Request.SendResponseAsync(_lidar.ReturnData());

                messageDeferral.Complete();
                return;
            }

            Device receivedFromAddress = (Device)message["ADDRESS"];

            switch (receivedFromAddress)
            {
            case Device.Wheel:
                _wheel.ExecuteWheelCommand(message);
                break;

            case Device.Ultrasonic:
                if (message.ContainsKey("REQUEST"))
                {
                    await args.Request.SendResponseAsync(_ultrasound.ReturnData());
                }
                break;

            case Device.EncoderLeft:
                if (message.ContainsKey("REQUEST"))
                {
                    await args.Request.SendResponseAsync(_encoderLeft.ReturnData());
                }
                break;

            case Device.EncoderRight:
                if (message.ContainsKey("REQUEST"))
                {
                    await args.Request.SendResponseAsync(_encoderRight.ReturnData());
                }
                break;

            case Device.GyroAccelerometer:
                break;

            default:
                throw new ArgumentOutOfRangeException($"Received request from invalid device address {receivedFromAddress}");
            }

            messageDeferral.Complete();
        }
コード例 #8
0
        private static void AddTarget(ApplicationDataContainer settings, Dictionary <string, WOLTarget> macList, ValueSet message, ValueSet resValues)
        {
            resValues[nameof(Keys.Result)] = false.ToString();
            if (!message.ContainsKey(nameof(Keys.PhysicalAddress)))
            {
                resValues[nameof(Keys.StatusMessage)] = nameof(CommandStatus.S_IncompleteParameters);
                return;
            }
            if (!(message[nameof(Keys.PhysicalAddress)] is string physical))
            {
                resValues[nameof(Keys.StatusMessage)] = nameof(CommandStatus.S_NoPhysicalAddress);
                return;
            }
            if (!NormalizePhysical(ref physical))
            {
                resValues[nameof(Keys.StatusMessage)] = nameof(CommandStatus.S_InvalidPhysicalFormat);
                return;
            }

            if (!message.ContainsKey(nameof(Keys.IpAddress)) || !(message[nameof(Keys.IpAddress)] is string address) || !IsValidAddress(address))
            {
                address = DEFAULT_DEST_ADDRESS;
            }
            if (!message.ContainsKey(nameof(Keys.PortNo)) || !(message[nameof(Keys.PortNo)] is string port) || !IsValidPort(port))
            {
                port = DEFAULT_PORT;
            }
            if (!message.ContainsKey(nameof(Keys.DelaySec)) || !(message[nameof(Keys.DelaySec)] is string delay) || !IsValidDelay(delay))
            {
                delay = DEFAULT_DELAY;
            }

            message.TryGetValue(nameof(Keys.Comment), out object comment);
            var target = new WOLTarget()
            {
                Physical = physical as string, Comment = comment as string, Address = address as string, Port = port as string, Delay = delay
            };

            if (string.IsNullOrWhiteSpace(target.Physical))
            {
                resValues[nameof(Keys.StatusMessage)] = nameof(CommandStatus.S_NoPhysicalAddress);
            }
            else
            {
                macList[target.Physical] = target;
                SaveMacList(settings, macList.Values);
                resValues[nameof(Keys.StatusMessage)] = nameof(CommandStatus.S_Success);
                resValues[nameof(Keys.Result)]        = true.ToString();
            }
        }
コード例 #9
0
        public static AppMessage FromValueSet(ValueSet values)
        {
            AppMessage lc = new AppMessage();

            if (values.ContainsKey(commandName))
            {
                lc.Command = (CommandType)Enum.Parse(typeof(CommandType), values[commandName].ToString());
            }
            if (values.ContainsKey(paramName))
            {
                lc.Param = (string)values[paramName];
            }
            return(lc);
        }
コード例 #10
0
        private async void Grayscale_Click(object sender, RoutedEventArgs e)
        {
            using (var connection = new AppServiceConnection())
            {
                connection.AppServiceName    = "com.microsoft.grayscaleservice";
                connection.PackageFamilyName = "AppExtensibility.Extension.Grayscale_byq669axdz8jy";

                AppServiceConnectionStatus status = await connection.OpenAsync();

                if (status == AppServiceConnectionStatus.Success)
                {
                    #region SendMessage
                    // send request to service
                    var request = new ValueSet();
                    request.Add("Command", "Grayscale");
                    request.Add("Pixels", ImageTools.GetBitmapBytes(AppData.currentImage));
                    request.Add("Height", AppData.currentImage.PixelHeight);
                    request.Add("Width", AppData.currentImage.PixelWidth);

                    // get response
                    AppServiceResponse response = await connection.SendMessageAsync(request);

                    if (response.Status == AppServiceResponseStatus.Success)
                    #endregion
                    #region HandleMessage
                    {
                        #region ErrorHandling
                        // convert imagestring back
                        ValueSet message = response.Message as ValueSet;
                        if (message.ContainsKey("Pixels") &&
                            message.ContainsKey("Height") &&
                            message.ContainsKey("Width"))
                        {
                            #endregion
                            byte[] pixels = message["Pixels"] as byte[];
                            int    height = (int)message["Height"];
                            int    width  = (int)message["Width"];

                            // encode the bytes to a string, and then the image.
                            string encodedImage = await ImageTools.EncodeBytesToPNGString(pixels, (uint)width, (uint)height);

                            await AppData.currentImage.SetSourceAsync(ImageTools.DecodeStringToBitmapSource(encodedImage));

                            AppData.currentImageString = encodedImage;
                        }
                    }
                    #endregion
                }
            }
        }
コード例 #11
0
        /// <summary>
        /// Handle messages from host to client - FYI: SlideshowClientPage handles the events fired from here
        /// </summary>
        private async Task <bool> HandleMessageFromHostAsync(ValueSet message, ValueSet responseMessage)
        {
            if (!message.ContainsKey("type"))
            {
                responseMessage.Add("error", "type not found");
                return(false);
            }

            var args = new SlideshowMessageReceivedEventArgs()
            {
                Message         = message,
                ResponseMessage = responseMessage,
                QueryType       = (SlideshowMessageTypeEnum)Enum.Parse(typeof(SlideshowMessageTypeEnum), (string)message["type"])
            };

            var taskCompletionSource = new TaskCompletionSource <object>();
            var dispatcher           = CoreApplication.MainView.CoreWindow.Dispatcher;

            var t = dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ReceivedMessageFromHost?.Invoke(this, args);
                taskCompletionSource.SetResult(null);
            });

            await taskCompletionSource.Task.ConfigureAwait(false);

            return(ReceivedMessageFromHost != null);
        }
コード例 #12
0
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            AppServiceDeferral deferral = args.GetDeferral();
            ValueSet           message  = args.Request.Message;

            if (message == null || !message.ContainsKey("type"))
            {
                return;
            }

            switch (message["type"])
            {
            case "speaking":
                Speak speak = JsonConvert.DeserializeObject <Speak>(message["payload"] as string);
                Messenger.Default.Send(new SpeakMessage(speak));
                break;

            case "audioInData":
                AudioInData?.Invoke(this, message["data"] as float[]);
                break;

            case "audioOutData":
                AudioOutData?.Invoke(this, message["data"] as float[]);
                break;
            }
            deferral.Complete();
        }
コード例 #13
0
ファイル: StartupTask.cs プロジェクト: wastegate711/samples
        private void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var messageDeferral = args.GetDeferral();

            //The message is provided as a ValueSet (IDictionary<String,Object)
            //The only message this server understands is with the name "requestedPinValue" and values of "Low" and "High"
            ValueSet message           = args.Request.Message;
            string   requestedPinValue = (string)message["requestedPinValue"];


            if (message.ContainsKey("requestedPinValue"))
            {
                if (requestedPinValue.Equals("High"))
                {
                    pin.Write(GpioPinValue.High);
                }
                else if (requestedPinValue.Equals("Low"))
                {
                    pin.Write(GpioPinValue.Low);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("Reqested pin value is not understood: " + requestedPinValue);
                    System.Diagnostics.Debug.WriteLine("Valid values are 'High' and 'Low'");
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Message not understood");
                System.Diagnostics.Debug.WriteLine("Valid command is: requestedPinValue");
            }

            messageDeferral.Complete();
        }
コード例 #14
0
        private static void RemoveTarget(ApplicationDataContainer settings, Dictionary <string, WOLTarget> macList, ValueSet resValues, ValueSet message)
        {
            bool result = false;

            if (!message.ContainsKey(nameof(Keys.PhysicalAddress)))
            {
                resValues[nameof(Keys.StatusMessage)] = nameof(CommandStatus.S_IncompleteParameters);
            }
            else if (!(message[nameof(Keys.PhysicalAddress)] is string physical))
            {
                resValues[nameof(Keys.StatusMessage)] = nameof(CommandStatus.S_NoPhysicalAddress);
            }
コード例 #15
0
        public static async void SetEndDevices(ObservableCollection <ZigBeeEndDevice> collection)
        {
            List <ValueSet> list = new List <ValueSet>();

            foreach (ZigBeeEndDevice endDevice in collection)
            {
                foreach (ZigBeeEndPoint endPoint in endDevice.EndPoints)
                {
                    ValueSet vs = new ValueSet();
                    Debug.WriteLine(string.Format("endPoint.Id {0} #  endPoint.CustomName {1}", endPoint.Id, endPoint.CustomName));
                    list.Add(new ValueSet {
                        { "Id", endPoint.Id }, { "Name", endPoint.CustomName }
                    });
                }
            }

            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    var message = new ValueSet();
                    message.Add("Type", "ZigBee");
                    message.Add("Command", "SetEndDevices");
                    message.Add("Param", JsonConvert.SerializeObject(list));

                    ValueSet ReturnData = IOTOI.Common.CommonService.GetReturnData(message);

                    Debug.WriteLine(ReturnData["Status"].ToString());

                    string phList = null;
                    if (ReturnData.ContainsKey("Status"))
                    {
                        if (ReturnData["Status"] != null)
                        {
                            Debug.WriteLine(ReturnData["Status"].ToString());
                            phList = ReturnData["Result"].ToString();
                        }
                    }

                    #region Call Cortana Update
                    VoiceCommandHandler voiceCommandHandler = new VoiceCommandHandler();
                    await Task.Run(async() => await voiceCommandHandler.SetPhraseList(phList));
                    #endregion
                }
                catch (Exception e)
                {
                    String test = e.Message;
                }
            });
        }
コード例 #16
0
        private void RelayClient_OnMessageReceived(ValueSet message)
        {
            Write("DEBUG", "RelayClient_OnMessageReceived");
            if (message.ContainsKey("command"))
            {
                string payload = (string)message["command"];

                OwlCommand c = BigOwl.StatusRelay.RelayClient.DeSerializeOwlCommand(payload);
                //OwlCommand c = (OwlCommand)message["command"];
                if (c != null)
                {
                    CommandQueue().Add(c);
                    string msg = "Command: " + c.Command.ToString();
                    Write("DEBUG", msg);
                    System.Diagnostics.Debug.WriteLine("Command: " + msg);
                    relayClient.SendAck(c.Id.ToString());
                }
                else
                {
                    Write("DEBUG", "command was null");
                    System.Diagnostics.Debug.WriteLine("Command was null.");
                    relayClient.SendNack(c.Id.ToString());
                }
            }
            else if (message.ContainsKey("ack"))
            {
                Write("DEBUG", "message was ack");
            }
            else if (message.ContainsKey("nack"))
            {
                Write("DEBUG", "message was nack");
            }
            else
            {
                //was something else.
            }
        }
コード例 #17
0
        /// <summary>
        /// Handles any received messages and routes them to the correct handler
        /// </summary>
        /// <param name="message"></param>
        /// <param name="returnMessage"></param>
        /// <param name="appServiceConnection"> used when message is to start a connection</param>
        /// <returns></returns>
        public async Task <ValueSet> HandleMessageReceivedAsync(ValueSet message, ValueSet returnMessage, AppServiceConnection appServiceConnection = null)
        {
            if (returnMessage == null)
            {
                returnMessage = new ValueSet();
            }

            if (message.ContainsKey("query"))
            {
                var query = (ConnectedServiceQuery)Enum.Parse(typeof(ConnectedServiceQuery), (string)message["query"]);
                switch (query)
                {
                case ConnectedServiceQuery.CheckStatus:
                    returnMessage.Add("status", _status.ToString());
                    returnMessage.Add("success", "true");
                    break;

                case ConnectedServiceQuery.StartHostingSession:
                    returnMessage.Add("success", StartHostingSessionHandle(appServiceConnection));
                    returnMessage.Add("status", _status.ToString());
                    break;

                case ConnectedServiceQuery.StopHostingSession:
                    returnMessage.Add("success", StopHostingSessionHandle());
                    returnMessage.Add("status", _status.ToString());
                    break;

                case ConnectedServiceQuery.MessageFromClient:
                    var hostListening = await HandleMessageFromClientAsync(message, returnMessage).ConfigureAwait(false);

                    returnMessage.Add("success", true);
                    returnMessage.Add("message_received", hostListening);
                    break;

                case ConnectedServiceQuery.MessageFromHost:
                    var clientListening = await HandleMessageFromHostAsync(message, returnMessage).ConfigureAwait(false);

                    returnMessage.Add("success", true);
                    returnMessage.Add("message_received", clientListening);
                    break;
                }
            }
            else
            {
                returnMessage.Add("error", "message unknown");
            }

            return(returnMessage);
        }
コード例 #18
0
        public void Handle(ValueSet valueSet)
        {
            bool write = Key != "SongPositionPrimary";

            try
            {
                if (write)
                {
                    MobileDebug.Service.WriteEvent("Handle1", Key, valueSet.ContainsKey(Key));
                }
                if (valueSet.ContainsKey(Key))
                {
                    messageReceived(valueSet, valueSet[Key].ToString());
                }
                if (write)
                {
                    MobileDebug.Service.WriteEvent("Handle2", Key, valueSet.ContainsKey(Key));
                }
            }
            catch (Exception e)
            {
                MobileDebug.Service.WriteEvent("HandleFail", e, Key, valueSet[Key].ToString());
            }
        }
コード例 #19
0
        public async Task <string> InvokeAndGetJSON(string _queryword, string _sourcelanguage, string _targetlanguage)
        {
            if (Loaded)
            {
                try
                {
                    ValueSet message = new ValueSet();
                    message.Add("QueryWord", _queryword);
                    message.Add("SourceLanguage", _sourcelanguage);
                    message.Add("TargetLanguage", _targetlanguage);

                    // make the app service call
                    using (var connection = new AppServiceConnection())
                    {
                        // service name is defined in appxmanifest properties
                        connection.AppServiceName = _serviceName;
                        // package Family Name is provided by the extension
                        connection.PackageFamilyName = AppExtension.Package.Id.FamilyName;

                        // open the app service connection
                        AppServiceConnectionStatus status = await connection.OpenAsync();

                        if (status != AppServiceConnectionStatus.Success)
                        {
                            Debug.WriteLine("Failed App Service Connection");
                        }
                        else
                        {
                            AppServiceResponse response = await connection.SendMessageAsync(message);

                            if (response.Status == AppServiceResponseStatus.Success)
                            {
                                ValueSet answer = response.Message as ValueSet;
                                if (answer.ContainsKey("Result")) // When our app service returns "Result", it means it succeeded
                                {
                                    return((string)answer["Result"]);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine("Calling the App Service failed");
                }
            }
            return(""); // indicates an error from the app service
        }
コード例 #20
0
ファイル: App.xaml.cs プロジェクト: lee12180/winiot-uwp
        private async void CommonInit()
        {
            Debug.WriteLine("CommonInit()");
            #region ZigBee Adapter Init
            var message = new ValueSet();
            message.Add("Command", "Init");
            message.Add("Type", "Common");

            var rtnMessage = new ValueSet();
            await Task.Run(() => {
                Debug.WriteLine("Start Init");
                rtnMessage = IOTOI.Common.CommonService.GetReturnData(message);
                string rst = "CommonService Init ERROR";
                if (rtnMessage["Status"].ToString() == "OK")
                {
                    rst = "CommonService Init OK";
                }

                Debug.WriteLine(rst);
                Debug.WriteLine("End Init");
            });

            if (rtnMessage["Status"].ToString() == "OK")
            {
                Debug.WriteLine("Start Footer");
                var FooterVM = ServiceLocator.Current.GetInstance <FooterViewModel>();
                FooterVM.CheckZigbeeAccess();
                Debug.WriteLine("End Footer");
            }

            #endregion

            #region Cortana Phrase List
            message = new ValueSet();
            message.Add("Command", "GetPhraseList");
            message.Add("Type", "Common");

            rtnMessage = IOTOI.Common.CommonService.GetReturnData(message);

            if (rtnMessage.ContainsKey("Result"))
            {
                await VoiceCommandHandler.SetPhraseList(rtnMessage["Result"] as string);
            }
            #endregion
        }
コード例 #21
0
        /// <summary>
        /// Invoke the extension's app service
        /// </summary>
        /// <param name="message">The parameters for the app service call</param>
        public async Task <double> Invoke(ValueSet message)
        {
            if (Loaded)
            {
                try
                {
                    // make the app service call
                    using (var connection = new AppServiceConnection())
                    {
                        // service name is defined in appxmanifest properties
                        connection.AppServiceName = _serviceName;
                        // package Family Name is provided by the extension
                        connection.PackageFamilyName = AppExtension.Package.Id.FamilyName;

                        // open the app service connection
                        AppServiceConnectionStatus status = await connection.OpenAsync();

                        if (status != AppServiceConnectionStatus.Success)
                        {
                            Debug.WriteLine("Failed App Service Connection");
                        }
                        else
                        {
                            // Call the app service
                            AppServiceResponse response = await connection.SendMessageAsync(message);

                            if (response.Status == AppServiceResponseStatus.Success)
                            {
                                ValueSet answer = response.Message as ValueSet;
                                if (answer.ContainsKey("Result")) // When our app service returns "Result", it means it succeeded
                                {
                                    return((double)answer["Result"]);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine("Calling the App Service failed");
                }
            }
            return(double.NaN); // indicates an error from the app service
        }
コード例 #22
0
        private void BackgroundMediaPlayer_MessageReceivedFromForeground(object sender, MediaPlayerDataReceivedEventArgs e)
        {
            // 接收訊息
            ValueSet val = e.Data;

            if (val.ContainsKey("action"))
            {
                string msg = val["action"] as string;
                if (msg.Equals("play")) //播放
                {
                    isFirstPlaying = true;
                    Play();
                    isFirstPlaying = false;
                }
                else //暫停
                {
                    Pause();
                }
            }
        }
コード例 #23
0
        private async void validateStep1(ValueSet result)
        {
            if (result.Count != 1)
            {
                await new MessageDialog("ERROR: Expected 1 user input value, but there were " + result.Count).ShowAsync();
            }

            else if (!result.ContainsKey("message"))
            {
                await new MessageDialog("ERROR: Expected a user input value for 'message', but there was none.").ShowAsync();
            }

            else if (!(result["message"] as string).Equals("Windows 10"))
            {
                await new MessageDialog("ERROR: User input value for 'message' was not 'Windows 10'").ShowAsync();
            }

            else
            {
                stepsControl.Step = int.MaxValue;
            }
        }
コード例 #24
0
        public async Task ParseArgumentsAsync(NamedPipeServerStream connection, Dictionary <string, object> message, string arguments)
        {
            switch (arguments)
            {
            case "NetworkDriveOperation":
                await ParseNetworkDriveOperationAsync(connection, message);

                break;

            case "GetOneDriveAccounts":
                try
                {
                    using var oneDriveAccountsKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\OneDrive\Accounts");

                    if (oneDriveAccountsKey == null)
                    {
                        await Win32API.SendMessageAsync(connection, new ValueSet()
                        {
                            { "Count", 0 }
                        }, message.Get("RequestID", (string)null));

                        return;
                    }

                    var oneDriveAccounts = new ValueSet();
                    foreach (var account in oneDriveAccountsKey.GetSubKeyNames())
                    {
                        var accountKeyName = @$ "{oneDriveAccountsKey.Name}\{account}";
                        var displayName    = (string)Registry.GetValue(accountKeyName, "DisplayName", null);
                        var userFolder     = (string)Registry.GetValue(accountKeyName, "UserFolder", null);
                        var accountName    = string.IsNullOrWhiteSpace(displayName) ? "OneDrive" : $"OneDrive - {displayName}";
                        if (!string.IsNullOrWhiteSpace(userFolder) && !oneDriveAccounts.ContainsKey(accountName))
                        {
                            oneDriveAccounts.Add(accountName, userFolder);
                        }
                    }
                    oneDriveAccounts.Add("Count", oneDriveAccounts.Count);
                    await Win32API.SendMessageAsync(connection, oneDriveAccounts, message.Get("RequestID", (string)null));
                }
コード例 #25
0
        private void validateStep1(ValueSet result)
        {
            if (result.Count != 1)
            {
                Error("Expected 1 user input value, but there were " + result.Count);
            }

            else if (!result.ContainsKey("message"))
            {
                Error("Expected a user input value for 'message', but there was none.");
            }

            else if (!(result["message"] as string).Equals("Windows 10"))
            {
                Error("User input value for 'message' was not 'Windows 10'");
            }

            else
            {
                stepsControl.Step = int.MaxValue;
            }
        }
コード例 #26
0
        private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            var messageDeferral = args.GetDeferral();

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

            if (message.ContainsKey("Command"))
            {
                string command = message["Command"] as string;
                // ... //
                if (command == "CurrentWeather")
                {
                    string resultJson = string.Empty;

                    var weatherData = await WeatherService.GetWeatherData();

                    var index = DateTime.Now.Hour / 6;

                    returnData.Add("Temperature", weatherData.Today[index].Temperature);
                    returnData.Add("State", weatherData.Today[index].Weather);
                    returnData.Add("Status", "OK");
                }
                else
                {
                    returnData.Add("Status", "Fail: Unknown command");
                }
            }
            else
            {
                returnData.Add("Status", "Fail: Missing command");
            }

            await args.Request.SendResponseAsync(returnData); // Return the data to the caller.

            messageDeferral.Complete();                       // Complete the deferral so that the platform knows that we're done responding to the app service call.
        }
コード例 #27
0
        public static ValueSet Combine(IEnumerable <ValueSet> valSets)
        {
            ValueSet ret = new ValueSet();

            foreach (var vs in valSets)
            {
                foreach (var vk in vs)
                {
                    if (ret.ContainsKey(vk.Key))
                    {
                        if (ret[vk.Key] != vk.Value)
                        {
                            ret[vk.Key] = "NAC";
                        }
                    }
                    else
                    {
                        ret[vk.Key] = vk.Value;
                    }
                }
            }

            return(ret);
        }
コード例 #28
0
        private async void RunAppServiceTask(object sender, RoutedEventArgs e)
        {
            IReadOnlyList <AppInfo> readOnlyList =
                (await AppServiceCatalog.FindAppServiceProvidersAsync("AppServiceServer_kj4sv7dv9awfe")).ToList();

            foreach (AppInfo _ in readOnlyList)
            {
            }

            var appServiceConnection = new AppServiceConnection
            {
                AppServiceName    = "AppServiceServerBackgroundTaskName",
                PackageFamilyName = "AppServiceServer_kj4sv7dv9awfe"
            };

            AppServiceConnectionStatus status = await appServiceConnection.OpenAsync();

            if (status == AppServiceConnectionStatus.Success)
            {
                AppServiceResponse appServiceResponse = await appServiceConnection.SendMessageAsync(new ValueSet { { "a", null }, { "b", null } });

                ValueSet responseValueSet = appServiceResponse.Message;
                if (responseValueSet == null)
                {
                    RunAppServiceTextBlock.Text = "response is null";
                    return;
                }
                string response = responseValueSet.ContainsKey("count")
                    ? responseValueSet["count"].ToString()
                    : "missing response key";
                RunAppServiceTextBlock.Text = response;
                return;
            }

            RunAppServiceTextBlock.Text = "Failed to connect";
        }
コード例 #29
0
        private void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
        {
            ValueSet message = args.Request.Message;

            if (message.ContainsKey("InterCommunication"))
            {
                Common.InterCommunication interCommunication = JsonSerializer.Deserialize <Common.InterCommunication>(message["InterCommunication"] as string);

                switch (interCommunication.InterCommunicationType)
                {
                case Common.InterCommunicationType.Exit:
                {
                    connection.Dispose();
                    Application.Exit();
                    break;
                }

                case Common.InterCommunicationType.StartISOConversionProcess:
                {
                    async void callback(Common.ProcessPhase phase, bool IsIndeterminate, int ProgressInPercentage, string SubOperation)
                    {
                        var prog = new Common.ISOConversionProgress()
                        {
                            Phase                = phase,
                            IsIndeterminate      = IsIndeterminate,
                            ProgressInPercentage = ProgressInPercentage,
                            SubOperation         = SubOperation
                        };

                        var comm = new Common.InterCommunication()
                        {
                            InterCommunicationType = Common.InterCommunicationType.ReportISOConversionProgress, ISOConversionProgress = prog
                        };

                        var val = new ValueSet();

                        val.Add("InterCommunication", JsonSerializer.Serialize(comm));

                        await SendToUWP(val);
                    }

                    Thread thread = new Thread(async() =>
                        {
                            try
                            {
                                MediaCreationLib.MediaCreator.CreateISOMedia(
                                    interCommunication.ISOConversion.ISOPath,
                                    interCommunication.ISOConversion.UUPPath,
                                    interCommunication.ISOConversion.Edition,
                                    interCommunication.ISOConversion.LanguageCode,
                                    interCommunication.ISOConversion.IntegrateUpdates,
                                    interCommunication.ISOConversion.CompressionType,
                                    callback);
                            }
                            catch (Exception ex)
                            {
                                var prog = new Common.ISOConversionProgress()
                                {
                                    Phase                = Common.ProcessPhase.Error,
                                    IsIndeterminate      = true,
                                    ProgressInPercentage = 0,
                                    SubOperation         = ex.ToString()
                                };

                                var comm = new Common.InterCommunication()
                                {
                                    InterCommunicationType = Common.InterCommunicationType.ReportISOConversionProgress, ISOConversionProgress = prog
                                };

                                var val = new ValueSet();
                                val.Add("InterCommunication", JsonSerializer.Serialize(comm));

                                await SendToUWP(val);
                            }
                        });

                    thread.Start();
                    break;
                }
                }
            }
        }
コード例 #30
0
        private static async Task ParseArgumentsAsync(AppServiceRequestReceivedEventArgs args, AppServiceDeferral messageDeferral, string arguments, ApplicationDataContainer localSettings)
        {
            switch (arguments)
            {
            case "Terminate":
                // Exit fulltrust process (UWP is closed or suspended)
                appServiceExit.Set();
                messageDeferral.Complete();
                break;

            case "RecycleBin":
                var binAction = (string)args.Request.Message["action"];
                await ParseRecycleBinActionAsync(args, binAction);

                break;

            case "StartupTasks":
                // Check QuickLook Availability
                QuickLook.CheckQuickLookAvailability(localSettings);
                break;

            case "ToggleQuickLook":
                var path = (string)args.Request.Message["path"];
                QuickLook.ToggleQuickLook(path);
                break;

            case "ShellCommand":
                // Kill the process. This is a BRUTAL WAY to kill a process.
#if DEBUG
                // In debug mode this kills this process too??
#else
                var pid = (int)args.Request.Message["pid"];
                Process.GetProcessById(pid).Kill();
#endif

                Process process = new Process();
                process.StartInfo.UseShellExecute = true;
                process.StartInfo.FileName        = "explorer.exe";
                process.StartInfo.CreateNoWindow  = false;
                process.StartInfo.Arguments       = (string)args.Request.Message["ShellCommand"];
                process.Start();
                break;

            case "LoadContextMenu":
                var contextMenuResponse        = new ValueSet();
                var loadThreadWithMessageQueue = new Win32API.ThreadWithMessageQueue <ValueSet>(HandleMenuMessage);
                var cMenuLoad = await loadThreadWithMessageQueue.PostMessageAsync <Win32API.ContextMenu>(args.Request.Message);

                contextMenuResponse.Add("Handle", handleTable.AddValue(loadThreadWithMessageQueue));
                contextMenuResponse.Add("ContextMenu", JsonConvert.SerializeObject(cMenuLoad));
                await args.Request.SendResponseAsync(contextMenuResponse);

                break;

            case "ExecAndCloseContextMenu":
                var menuKey = (string)args.Request.Message["Handle"];
                var execThreadWithMessageQueue = handleTable.GetValue <Win32API.ThreadWithMessageQueue <ValueSet> >(menuKey);
                if (execThreadWithMessageQueue != null)
                {
                    await execThreadWithMessageQueue.PostMessage(args.Request.Message);
                }
                // The following line is needed to cleanup resources when menu is closed.
                // Unfortunately if you uncomment it some menu items will randomly stop working.
                // Resource cleanup is currently done on app closing,
                // if we find a solution for the issue above, we should cleanup as soon as a menu is closed.
                //handleTable.RemoveValue(menuKey);
                break;

            case "InvokeVerb":
                var filePath = (string)args.Request.Message["FilePath"];
                var split    = filePath.Split('|').Where(x => !string.IsNullOrWhiteSpace(x));
                using (var cMenu = Win32API.ContextMenu.GetContextMenuForFiles(split.ToArray(), Shell32.CMF.CMF_DEFAULTONLY))
                {
                    cMenu?.InvokeVerb((string)args.Request.Message["Verb"]);
                }
                break;

            case "Bitlocker":
                var bitlockerAction = (string)args.Request.Message["action"];
                if (bitlockerAction == "Unlock")
                {
                    var drive    = (string)args.Request.Message["drive"];
                    var password = (string)args.Request.Message["password"];
                    Win32API.UnlockBitlockerDrive(drive, password);
                    await args.Request.SendResponseAsync(new ValueSet()
                    {
                        { "Bitlocker", "Unlock" }
                    });
                }
                break;

            case "SetVolumeLabel":
                var driveName = (string)args.Request.Message["drivename"];
                var newLabel  = (string)args.Request.Message["newlabel"];
                Win32API.SetVolumeLabel(driveName, newLabel);
                break;

            case "FileOperation":
                await ParseFileOperationAsync(args);

                break;

            case "GetIconOverlay":
                var fileIconPath  = (string)args.Request.Message["filePath"];
                var thumbnailSize = (int)args.Request.Message["thumbnailSize"];
                var iconOverlay   = Win32API.GetFileIconAndOverlay(fileIconPath, thumbnailSize);
                await args.Request.SendResponseAsync(new ValueSet()
                {
                    { "Icon", iconOverlay.icon },
                    { "Overlay", iconOverlay.overlay },
                    { "HasCustomIcon", iconOverlay.isCustom }
                });

                break;

            case "GetOneDriveAccounts":
                using (var oneDriveAccountsKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\OneDrive\Accounts", false))
                {
                    var oneDriveAccounts = new ValueSet();
                    foreach (var account in oneDriveAccountsKey.GetSubKeyNames())
                    {
                        var accountKeyName = @$ "{oneDriveAccountsKey.Name}\{account}";
                        var displayName    = (string)Registry.GetValue(accountKeyName, "DisplayName", null);
                        var userFolder     = (string)Registry.GetValue(accountKeyName, "UserFolder", null);
                        var accountName    = string.IsNullOrWhiteSpace(displayName) ? "OneDrive" : $"OneDrive - {displayName}";
                        if (!string.IsNullOrWhiteSpace(userFolder) && !oneDriveAccounts.ContainsKey(accountName))
                        {
                            oneDriveAccounts.Add(accountName, userFolder);
                        }
                    }
                    await args.Request.SendResponseAsync(oneDriveAccounts);
                }
                break;
コード例 #31
0
        private void validateStep1(ValueSet result)
        {
            if (result.Count != 1)
                Error("Expected 1 user input value, but there were " + result.Count);

            else if (!result.ContainsKey("message"))
                Error("Expected a user input value for 'message', but there was none.");

            else if (!(result["message"] as string).Equals("Windows 10"))
                Error("User input value for 'message' was not 'Windows 10'");

            else
            {
                stepsControl.Step = int.MaxValue;
            }
        }
コード例 #32
0
        private async void validateStep1(ValueSet result)
        {
            if (result.Count != 1)
                await new MessageDialog("ERROR: Expected 1 user input value, but there were " + result.Count).ShowAsync();

            else if (!result.ContainsKey("message"))
                await new MessageDialog("ERROR: Expected a user input value for 'message', but there was none.").ShowAsync();

            else if (!(result["message"] as string).Equals("Windows 10"))
                await new MessageDialog("ERROR: User input value for 'message' was not 'Windows 10'").ShowAsync();

            else
            {
                stepsControl.Step = int.MaxValue;
            }
        }