private async void LaunchUriForResult_Click(object sender, RoutedEventArgs e) { var protocol = "win10demo2://"; var packageFamilyName = "0df93276-6bbb-46fa-96b7-ec223e226505_cb1hhkscw5m06"; var status = await Launcher.QueryUriSupportAsync(new Uri(protocol), LaunchQuerySupportType.UriForResults, packageFamilyName); if (status == LaunchQuerySupportStatus.Available) { var options = new LauncherOptions { TargetApplicationPackageFamilyName = packageFamilyName }; var values = new ValueSet(); values.Add("TwitterId", "danvy"); var result = await Launcher.LaunchUriForResultsAsync(new Uri(protocol), options, values); if (result.Status == LaunchUriStatus.Success) { var authorized = result.Result["Authorized"] as string; if (authorized == true.ToString()) { var dialog = new MessageDialog("You are authorized :)"); await dialog.ShowAsync(); } } } }
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 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 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(); }
private async void SendMessageToServer(string message) { var command = new ValueSet(); command.Add("Command", "Bridge"); command.Add("SendToServer", message); var response = await _appServiceConnection.SendMessageAsync(command); }
private async Task NotifyClientsOfPerimeterState() { var _sensorCurrentValue = _sensorPin.Read(); var messages = new ValueSet(); //name value pair if (_sensorCurrentValue == GpioPinValue.High) { //send perimeter breached messages.Add("Perimeter Notification", "Breached"); } else { //send perimeter secure messages.Add("Perimeter Notification", "Secure"); } //send message to the client var response = await _connection.SendMessageAsync(messages); if (response.Status == AppServiceResponseStatus.Success) { var result = response.Message["Response"]; //optionally log result from client } }
public async void PostBookAsync() { var message = new ValueSet(); message.Add("command", "POST"); string json = new Book { Title = NewBookTitle, Publisher = NewBookPublisher }.ToJson(); message.Add("book", json); string result = await SendMessageAsync(message); }
public static ValueSet ConstructMessage(string tag, string content) { var valueSet = new ValueSet(); valueSet.Add(MessageTag, tag); valueSet.Add(MessageContent, content); return valueSet; }
private async void AppServiceConnection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var message = args.Request.Message; string command = (string)message["Command"]; switch (command) { case "GetSynonym": { var messageDeferral = args.GetDeferral(); string term = (string)message["Term"]; // Call the synonyms service SynonymApi api = new SynonymApi(BING_KEY); var returnMessage = new ValueSet(); try { var synonyms = await api.GetSynonymsAsync(term); if ((synonyms != null) && (synonyms.Count() > 0)) { //Set a result to return to the caller //Serialize the IEnumerable<string> to Json so we can insert into ValueSet returnMessage.Add("Result", JSONHelper.SerializeObject(synonyms)); } else { // Report an error back to the caller returnMessage.Add("Error", "No results found"); } } catch (Exception ex) { // Error accessing the service // Report an error back to the caller returnMessage.Add("Error", "Synonyms Service not available " + ex.Message + " term=" + term); } 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; } } }
private void ReturnResult() { if (pfrArgs != null) { var values = new ValueSet(); values.Add("TimeStamp", DateTime.Now.ToString()); values.Add("Authorized", (IdBlock.Text == "danvy").ToString()); pfrArgs.ProtocolForResultsOperation.ReportCompleted(values); } }
private async void OnOpenAnotherAppWithDataClicked(object sender, RoutedEventArgs e) { LauncherOptions options = new LauncherOptions(); options.TargetApplicationPackageFamilyName = "8a1341de-3acd-4d5a-91f2-98d9cd2c1c6e_e8f4dqfvn1be6"; ValueSet data = new ValueSet(); data.Add("Customer", "Contoso"); data.Add("Price", "25"); await Launcher.LaunchUriAsync(new Uri("invoice:"), options, data); }
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 ValueSet AddBook(string book) { BooksRepository.Instance.AddBook(book.ToBook()); var result = new ValueSet(); result.Add("result", "ok"); return result; }
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; } } }
private async void pickerBtb_Click(object sender, RoutedEventArgs e) { //Set a result to return to the caller var returnMessage = new ValueSet(); server = new HttpServer(8080); server.StartServer(); returnMessage.Add("Status", "Success"); // var myPictures = await StorageLibrary.GetLibraryAsync(Windows.Storage.KnownLibraryId.Pictures); var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { // Application now has read/write access to the picked file Log("Picked photo: " + file.Path, "Success"); server.FilePath = file.Path; } else { Log("Operation cancelled.", "Error"); } }
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() }); } }
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(); } }
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(); } }
private async void LaunchUriForResult_Click(object sender, RoutedEventArgs e) { var protocol = "win10demo2://"; var packageFamilyName = "041cdcf9-8ef3-40e4-85e2-8f3de5e06155_ncrzdc1cmma1g"; var status = await Launcher.QueryUriSupportAsync(new Uri(protocol), LaunchQuerySupportType.UriForResults, packageFamilyName); if (status == LaunchQuerySupportStatus.Available) { var options = new LauncherOptions { TargetApplicationPackageFamilyName = packageFamilyName }; var values = new ValueSet(); values.Add("TwitterId", "danvy"); var result = await Launcher.LaunchUriForResultsAsync(new Uri(protocol), options, values); if ((result.Status == LaunchUriStatus.Success) && (result.Result != null)) { var authorized = result.Result["Authorized"] as string; if (authorized == true.ToString()) { var dialog = new MessageDialog("You are authorized :)"); await dialog.ShowAsync(); } } } }
private async void OnPlayClick(object sender, RoutedEventArgs e) { String url = txtURL.Text; String tag = "ra000001"; Uri hsl = await GetHitChannelHSL(url, tag); if (hsl != null) { // check is phone bool isHardwareButtonsAPIPresent = Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"); if (isHardwareButtonsAPIPresent) { //Windows.Phone.UI.Input.HardwareButtons.CameraPressed += // HardwareButtons_CameraPressed; ValueSet msg = new ValueSet(); msg.Add("Play", hsl.OriginalString); BackgroundMediaPlayer.SendMessageToBackground(msg); } AdaptiveMediaSourceCreationResult result = await AdaptiveMediaSource.CreateFromUriAsync(hsl); if (result.Status == AdaptiveMediaSourceCreationStatus.Success) { _source = result.MediaSource; _source.DownloadRequested += _source_DownloadRequested; _source.DownloadCompleted += _source_DownloadCompleted; _source.DownloadFailed += _source_DownloadFailed; _source.DownloadBitrateChanged += _source_DownloadBitrateChanged; _source.PlaybackBitrateChanged += _source_PlaybackBitrateChanged; mediaPlayer.SetMediaStreamSource(result.MediaSource); } } }
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; } }
/// <summary> /// Hệ thống gọi đến hàm này khi association backgroundtask được bật /// </summary> /// <param name="taskInstance"> hệ thống tự tạo và truyền vào đây</param> public async void Run(IBackgroundTaskInstance taskInstance) { //System.Diagnostics.Debug.WriteLine("background run"); taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(BackgroundTaskCanceled); taskInstance.Task.Completed += new BackgroundTaskCompletedEventHandler(BackgroundTaskCompleted); _backgroundstarted.Set();// _deferral = taskInstance.GetDeferral(); //Playlist = new BackgroundPlaylist(); _smtc = initSMTC(); this._foregroundState = this.initForegroundState(); BackgroundMediaPlayer.Current.CurrentStateChanged += BackgroundMediaPlayer_CurrentStateChanged; //Playlist = await BackgroundPlaylist.LoadBackgroundPlaylist("playlist.xml"); Playlist = new BackgroundPlaylist(); Playlist.ListPathsource = await BackgroundPlaylist.LoadCurrentPlaylist(Constant.CurrentPlaylist); if (_foregroundState != eForegroundState.Suspended) { ValueSet message = new ValueSet(); message.Add(Constant.BackgroundTaskStarted, ""); BackgroundMediaPlayer.SendMessageToForeground(message); } Playlist.TrackChanged += Playlist_TrackChanged; BackgroundMediaPlayer.MessageReceivedFromForeground += BackgroundMediaPlayer_MessageReceivedFromForeground; BackgroundMediaPlayer.Current.MediaEnded +=Current_MediaEnded; ApplicationSettingHelper.SaveSettingsValue(Constant.BackgroundTaskState, Constant.BackgroundTaskRunning); isbackgroundtaskrunning = true; _loopState = eLoopState.None; }
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; }
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 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; }); }
public void RestorePlaylist() { #if WINDOWS_PHONE_APP var msgDictionanary = new ValueSet(); msgDictionanary.Add(BackgroundAudioConstants.RestorePlaylist, ""); BackgroundMediaPlayer.SendMessageToBackground(msgDictionanary); #endif }
private async void ParseButton_Click(object sender, RoutedEventArgs e) { this.Items.Clear(); this.appServiceConnection = new AppServiceConnection { AppServiceName = "com.shenchauhan.GroceryShop", PackageFamilyName = "292c6a2f-3028-412d-b530-23fbc868d2cb_8gdmnpqbw06hm" }; var status = await this.appServiceConnection.OpenAsync(); switch (status) { case AppServiceConnectionStatus.AppNotInstalled: await LogError("The Grocery Shop application is not installed. Please install it and try again"); return; case AppServiceConnectionStatus.AppServiceUnavailable: await LogError("The Grocery Shop application does not have the available feature"); return; case AppServiceConnectionStatus.Unknown: await LogError("Uh-oh! erm....."); return; } var items = this.NotesTextBox.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 this.appServiceConnection.SendMessageAsync(message); switch (response.Status) { case AppServiceResponseStatus.ResourceLimitsExceeded: await LogError("Yikes! The resource for this device exceeded the limits so the app service was shutdown"); return; case AppServiceResponseStatus.Failure: await LogError("Oh dear, we failed to get a response"); return; case AppServiceResponseStatus.Unknown: await LogError("uh-oh... Not sure why we didn't get a response"); return; } foreach (var item in response.Message) { this.Items.Add(new ShoppingItem { Name = item.Key, Price = item.Value.ToString() }); } }
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.JsRTChakraCoreX.UI.Test"); returnData.Add("sketch-home", "X.Extension.ThirdParty.JsRTChakraCoreX.UI.Home"); break; } await args.Request.SendResponseAsync(returnData); msgDef.Complete(); }
private async void CallAppService() { await EnsureConnectionToService(); //Send data to the service var message = new ValueSet(); message.Add("Command", "CalcSum"); message.Add("Value1", Int32.Parse(Value1.Text)); message.Add("Value2", Int32.Parse(Value2.Text)); //Send a message AppServiceResponse response = await connection.SendMessageAsync(message); if (response.Status == AppServiceResponseStatus.Success) { int sum = (int)response.Message["Result"]; ResultTextBox.Text = sum.ToString(); } }
private void TimerCallBack(object state) { if (_connection!=null) { var msg = new ValueSet(); msg.Add("unsolicited", "you asked for it!"); _connection.SendMessageAsync(msg).AsTask(); } }
private static async Task parseArguments(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 parseRecycleBinAction(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.PostMessage <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 "FileOperation": await parseFileOperation(args); break; case "GetIconOverlay": var fileIconPath = (string)args.Request.Message["filePath"]; var iconOverlay = Win32API.GetFileOverlayIcon(fileIconPath); await args.Request.SendResponseAsync(new ValueSet() { { "IconOverlay", iconOverlay.icon }, { "HasCustomIcon", iconOverlay.isCustom } }); break; default: if (args.Request.Message.ContainsKey("Application")) { var application = (string)args.Request.Message["Application"]; HandleApplicationLaunch(application, args); } else if (args.Request.Message.ContainsKey("ApplicationList")) { var applicationList = JsonConvert.DeserializeObject <IEnumerable <string> >((string)args.Request.Message["ApplicationList"]); HandleApplicationsLaunch(applicationList, args); } break; } }
public async override void GetSpecialProperties() { ViewModel.IsHidden = NativeFileOperationsHelper.HasFileAttribute( Item.ItemPath, System.IO.FileAttributes.Hidden); var fileIconData = await FileThumbnailHelper.LoadIconFromPathAsync(Item.ItemPath, 80, Windows.Storage.FileProperties.ThumbnailMode.SingleItem); if (fileIconData != null) { ViewModel.IconData = fileIconData; ViewModel.LoadFolderGlyph = false; ViewModel.LoadFileIcon = true; } if (Item.IsShortcutItem) { ViewModel.ItemSizeVisibility = true; ViewModel.ItemSize = Item.FileSizeBytes.ToLongSizeString(); ViewModel.ItemCreatedTimestamp = Item.ItemDateCreated; ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed; if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((ShortcutItem)Item).TargetPath)) { // Can't show any other property return; } } string folderPath = (Item as ShortcutItem)?.TargetPath ?? Item.ItemPath; BaseStorageFolder storageFolder; try { storageFolder = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync(folderPath); } catch (Exception ex) { App.Logger.Warn(ex, ex.Message); // Could not access folder, can't show any other property return; } if (storageFolder != null) { ViewModel.ItemCreatedTimestamp = dateTimeFormatter.ToShortLabel(storageFolder.DateCreated); if (storageFolder.Properties != null) { GetOtherProperties(storageFolder.Properties); } GetFolderSize(storageFolder.Path, TokenSource.Token); } else if (Item.ItemPath.Equals(CommonPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) { // GetFolderFromPathAsync cannot access recyclebin folder var connection = await AppServiceConnectionHelper.Instance; if (connection != null) { var value = new ValueSet(); value.Add("Arguments", "RecycleBin"); value.Add("action", "Query"); // Send request to fulltrust process to get recyclebin properties var(status, response) = await connection.SendMessageForResponseAsync(value); if (status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success) { if (response.TryGetValue("BinSize", out var binSize)) { ViewModel.ItemSizeBytes = (long)binSize; ViewModel.ItemSize = ByteSize.FromBytes((long)binSize).ToString(); ViewModel.ItemSizeVisibility = true; } else { ViewModel.ItemSizeVisibility = false; } if (response.TryGetValue("NumItems", out var numItems)) { ViewModel.FilesCount = (int)(long)numItems; SetItemsCountString(); ViewModel.FilesAndFoldersCountVisibility = true; } else { ViewModel.FilesAndFoldersCountVisibility = false; } ViewModel.ItemCreatedTimestampVisibiity = false; ViewModel.ItemAccessedTimestampVisibility = false; ViewModel.ItemModifiedTimestampVisibility = false; ViewModel.LastSeparatorVisibility = false; } } } else { GetFolderSize(folderPath, TokenSource.Token); } }
public async Task ParseArgumentsAsync(PipeStream connection, Dictionary <string, object> message, string arguments) { switch (arguments) { case "LoadContextMenu": var contextMenuResponse = new ValueSet(); var loadThreadWithMessageQueue = new ThreadWithMessageQueue <Dictionary <string, object> >(HandleMenuMessage); var cMenuLoad = await loadThreadWithMessageQueue.PostMessageAsync <ContextMenu>(message); contextMenuResponse.Add("Handle", handleTable.AddValue(loadThreadWithMessageQueue)); contextMenuResponse.Add("ContextMenu", JsonConvert.SerializeObject(cMenuLoad)); await Win32API.SendMessageAsync(connection, contextMenuResponse, message.Get("RequestID", (string)null)); break; case "ExecAndCloseContextMenu": var menuKey = (string)message["Handle"]; var execThreadWithMessageQueue = handleTable.GetValue <ThreadWithMessageQueue <Dictionary <string, object> > >(menuKey); if (execThreadWithMessageQueue != null) { await execThreadWithMessageQueue.PostMessage(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)message["FilePath"]; var split = filePath.Split('|').Where(x => !string.IsNullOrWhiteSpace(x)); var verb = (string)message["Verb"]; using (var cMenu = ContextMenu.GetContextMenuForFiles(split.ToArray(), Shell32.CMF.CMF_DEFAULTONLY)) { var result = cMenu?.InvokeVerb(verb); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", result } }, message.Get("RequestID", (string)null)); } break; case "GetNewContextMenuEntries": var entries = await Extensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntries(), Program.Logger); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Entries", JsonConvert.SerializeObject(entries) } }, message.Get("RequestID", (string)null)); break; case "GetNewContextMenuEntryForType": var fileExtension = (string)message["extension"]; var entry = await Extensions.IgnoreExceptions(() => ShellNewMenuHelper.GetNewContextMenuEntryForType(fileExtension), Program.Logger); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Entry", JsonConvert.SerializeObject(entry) } }, message.Get("RequestID", (string)null)); break; } }
private async void ParseButton_Click(object sender, RoutedEventArgs e) { this.Items.Clear(); this.appServiceConnection = new AppServiceConnection { AppServiceName = "com.shenchauhan.GroceryShop", PackageFamilyName = "292c6a2f-3028-412d-b530-23fbc868d2cb_8gdmnpqbw06hm" }; var status = await this.appServiceConnection.OpenAsync(); switch (status) { case AppServiceConnectionStatus.AppNotInstalled: await LogError("The Grocery Shop application is not installed. Please install it and try again"); return; case AppServiceConnectionStatus.AppServiceUnavailable: await LogError("The Grocery Shop application does not have the available feature"); return; case AppServiceConnectionStatus.Unknown: await LogError("Uh-oh! erm....."); return; } var items = this.NotesTextBox.Text.Split(new string[] { "\r" }, StringSplitOptions.RemoveEmptyEntries); var message = new ValueSet(); for (int i = 0; i < items.Length; i++) { message.Add(i.ToString(), items[i]); } var response = await this.appServiceConnection.SendMessageAsync(message); switch (response.Status) { case AppServiceResponseStatus.ResourceLimitsExceeded: await LogError("Yikes! The resource for this device exceeded the limits so the app service was shutdown"); return; case AppServiceResponseStatus.Failure: await LogError("Oh dear, we failed to get a response"); return; case AppServiceResponseStatus.Unknown: await LogError("uh-oh... Not sure why we didn't get a response"); return; } foreach (var item in response.Message) { this.Items.Add(new ShoppingItem { Name = item.Key, Price = item.Value.ToString() }); } }
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 "DetectQuickLook": // Check QuickLook Availability var available = QuickLook.CheckQuickLookAvailability(); await args.Request.SendResponseAsync(new ValueSet() { { "IsAvailable", available } }); 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": try { var oneDriveAccountsKey = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\OneDrive\Accounts", false); if (oneDriveAccountsKey == null) { await args.Request.SendResponseAsync(new ValueSet()); 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); } } await args.Request.SendResponseAsync(oneDriveAccounts); }
private async Task WriteResponseAsync(string request, IOutputStream os) { // See if the request is for blinky.html, if yes get the new state string state = "Unspecified"; string axisState = "Unspecified"; string axisdn = "test.html?axis=down"; char[] arr; string str = ""; string axisValue = ""; bool stateChanged = false; // ListAvailablePorts(); string html = offHtmlString; // default off if (request.Contains("blinky.html?state=on")) { state = "On"; stateChanged = true; html = onHtmlString; } else if (request.Contains("blinky.html?state=off")) { state = "Off"; stateChanged = true; html = offHtmlString; } else if (request.Contains("blinky.html?state=start")) { state = "Start"; stateChanged = true; html = startHtmlString; } else if (request.Contains("blinky.html?state=test_on")) { state = "Test_ON"; stateChanged = true; html = offHtmlString; } else if (request.Contains("blinky.html?state=test_off")) { state = "Test_OFF"; stateChanged = true; html = offHtmlString; } else if (request.Contains("test.html?axis=")) { axisState = "On"; stateChanged = true; string up = "test.html?axis=up"; string sub = request.Substring(request.Length - 4, 4); if (request.Contains("down") == true) { axisValue = "-"; //string str = request.Replace("test.html?axis=down", ""); axisValue += sub; } else { axisValue = sub; } } else if (request.Contains("slice.html")) { //don't send any commands to backend just show current slice number html = "<html><head><meta http-equiv=\"refresh\" content=\"5\" /></head><body></body>Current Slice :" + SliceName + "/" + TotalSliceName + "</html>"; stateChanged = false; } if (stateChanged) { var updateMessage = new ValueSet(); updateMessage.Add("State", state); updateMessage.Add("AxisState", axisState); updateMessage.Add("AxisValue", axisValue); //avar responseStatus = await appServiceConnection.SendMessageAsync(updateMessage); appServiceConnection.SendMessageAsync(updateMessage); } //string html = state == "On" ? onHtmlString : offHtmlString; // Show the html using (Stream resp = os.AsStreamForWrite()) { // Look in the Data subdirectory of the app package byte[] bodyArray = Encoding.UTF8.GetBytes(html); MemoryStream stream = new MemoryStream(bodyArray); string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Length: {0}\r\n" + "Connection: close\r\n\r\n", stream.Length); byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await stream.CopyToAsync(resp); await resp.FlushAsync(); } }
async private void callAppService_Click(object sender, RoutedEventArgs e) { long number = 0; if (long.TryParse(input.Text, out number)) { try { callAppService.IsEnabled = false; if (appServiceConnection == null) { appServiceConnection = new AppServiceConnection(); appServiceConnection.PackageFamilyName = APPSERVICE_PACKAGE_FAMILY_NAME; appServiceConnection.AppServiceName = "SomeArbitraryName"; AppServiceConnectionStatus result = await appServiceConnection.OpenAsync(); if (result != AppServiceConnectionStatus.Success) { appServiceConnection.Dispose(); appServiceConnection = null; status.Log(LocalizableStrings.APPSERVICE_CREATE_FAIL); closeAppService.IsEnabled = false; return; } else { status.Log(LocalizableStrings.APPSERVICE_CREATE_SUCCESS); closeAppService.IsEnabled = true; } } ValueSet message = new ValueSet(); string requestText = input.Text; message.Add("SQR", requestText); AppServiceResponse response = await appServiceConnection.SendMessageAsync(message); if (response.Status != AppServiceResponseStatus.Success) { status.Log(LocalizableStrings.APPSERVICE_SEND_FAIL); } else { string responseText = response.Message["Response"] as string; status.Log(string.Format( CultureInfo.CurrentCulture, LocalizableStrings.APPSERVICE_SEND_RESULT, requestText, responseText)); result.Text = responseText; } } catch (Exception ex) { status.Log(ex.Message); } finally { callAppService.IsEnabled = true; } } else { status.Log(LocalizableStrings.APPSERVICE_INVALID_INPUT); } }
public async void CheckPathInput(ItemViewModel instance, string CurrentInput) { if (CurrentInput != instance.WorkingDirectory || App.CurrentInstance.ContentFrame.CurrentSourcePageType == typeof(YourHome)) { //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.HomeItems.isEnabled = false; //(App.CurrentInstance.OperationsControl as RibbonArea).RibbonViewModel.ShareItems.isEnabled = false; if (CurrentInput.Equals("Home", StringComparison.OrdinalIgnoreCase) || CurrentInput.Equals("New tab", StringComparison.OrdinalIgnoreCase)) { App.CurrentInstance.ViewModel.WorkingDirectory = "New tab"; App.CurrentInstance.ContentFrame.Navigate(typeof(YourHome), "New tab", new SuppressNavigationTransitionInfo()); } else { switch (CurrentInput.ToLower()) { case "%temp%": CurrentInput = App.AppSettings.TempPath; break; case "%appdata": CurrentInput = App.AppSettings.AppDataPath; break; case "%homepath%": CurrentInput = App.AppSettings.HomePath; break; case "%windir%": CurrentInput = App.AppSettings.WinDirPath; break; } try { await StorageFolder.GetFolderFromPathAsync(CurrentInput); App.CurrentInstance.ContentFrame.Navigate(App.AppSettings.GetLayoutType(), CurrentInput); // navigate to folder } catch (Exception) // Not a folder or inaccessible { try { await StorageFile.GetFileFromPathAsync(CurrentInput); await Interaction.InvokeWin32Component(CurrentInput); } catch (Exception ex) // Not a file or not accessible { // Launch terminal application if possible var localSettings = ApplicationData.Current.LocalSettings; foreach (var item in App.AppSettings.Terminals) { if (item.Path.Equals(CurrentInput, StringComparison.OrdinalIgnoreCase) || item.Path.Equals(CurrentInput + ".exe", StringComparison.OrdinalIgnoreCase)) { if (App.Connection != null) { var value = new ValueSet(); value.Add("Application", item.Path); value.Add("Arguments", String.Format(item.arguments, App.CurrentInstance.ViewModel.WorkingDirectory)); await App.Connection.SendMessageAsync(value); } return; } } var dialog = new ContentDialog() { Title = "Invalid item", Content = "The item referenced is either invalid or inaccessible.\nMessage:\n\n" + ex.Message, CloseButtonText = "OK" }; await dialog.ShowAsync(); } } } App.CurrentInstance.NavigationToolbar.PathControlDisplayText = App.CurrentInstance.ViewModel.WorkingDirectory; } }
private async void GenerateRandomNumber_Click(object sender, RoutedEventArgs e) { //Parse user input int minValueInput = 0; bool valueParsed = int.TryParse(MinValue.Text, out minValueInput); if (!valueParsed) { rootPage.NotifyUser("The Minimum Value should be a valid integer", NotifyType.ErrorMessage); return; } int maxValueInput = 0; valueParsed = int.TryParse(MaxValue.Text, out maxValueInput); if (!valueParsed) { rootPage.NotifyUser("The Maximum Value should be a valid integer", NotifyType.ErrorMessage); return; } if (maxValueInput <= minValueInput) { rootPage.NotifyUser("Maximum Value must be larger than Minimum Value", NotifyType.ErrorMessage); return; } using (var connection = new AppServiceConnection()) { //Set up a new app service connection connection.AppServiceName = "com.microsoft.randomnumbergenerator"; connection.PackageFamilyName = "Microsoft.SDKSamples.AppServicesProvider.CS_8wekyb3d8bbwe"; AppServiceConnectionStatus status = await connection.OpenAsync(); switch (status) { case AppServiceConnectionStatus.Success: // The new connection opened successfully rootPage.NotifyUser("Connection established", NotifyType.StatusMessage); break; case AppServiceConnectionStatus.AppNotInstalled: rootPage.NotifyUser("The app AppServicesProvider is not installed. Deploy AppServicesProvider to this device and try again.", NotifyType.ErrorMessage); return; case AppServiceConnectionStatus.AppUnavailable: rootPage.NotifyUser("The app AppServicesProvider is not available. This could be because it is currently being updated or was installed to a removable device that is no longer available.", NotifyType.ErrorMessage); return; case AppServiceConnectionStatus.AppServiceUnavailable: rootPage.NotifyUser($"The app AppServicesProvider is installed but it does not provide the app service {connection.AppServiceName}", NotifyType.ErrorMessage); return; default: case AppServiceConnectionStatus.Unknown: rootPage.NotifyUser("An unknown error occurred while we were trying to open an AppServiceConnection.", NotifyType.ErrorMessage); return; } //Set up the inputs and send a message to the service var inputs = new ValueSet(); inputs.Add("minvalue", minValueInput); inputs.Add("maxvalue", maxValueInput); AppServiceResponse response = await connection.SendMessageAsync(inputs); //If the service responded with success display the result and walk away if (response.Status == AppServiceResponseStatus.Success && response.Message.ContainsKey("result")) { var resultText = response.Message["result"].ToString(); if (!string.IsNullOrEmpty(resultText)) { Result.Text = resultText; rootPage.NotifyUser("App service responded with a result", NotifyType.StatusMessage); } else { rootPage.NotifyUser("App service did not respond with a result", NotifyType.ErrorMessage); } return; } //Something went wrong while sending a message. Let display //a meaningful error message switch (response.Status) { case AppServiceResponseStatus.Failure: rootPage.NotifyUser("The service failed to acknowledge the message we sent it. It may have been terminated or it's RequestReceived handler might not be handling incoming messages correctly.", NotifyType.ErrorMessage); return; case AppServiceResponseStatus.ResourceLimitsExceeded: rootPage.NotifyUser("The service exceeded the resources allocated to it and had to be terminated.", NotifyType.ErrorMessage); return; default: case AppServiceResponseStatus.Unknown: rootPage.NotifyUser("An unknown error occurred while we were trying to send a message to the service.", NotifyType.ErrorMessage); return; } } }
/// <summary> /// Populates the page with content passed during navigation. Any saved state is also /// provided when recreating a page from a prior session. /// </summary> /// <param name="sender"> /// The source of the event; typically <see cref="NavigationHelper"/> /// </param> /// <param name="e">Event data that provides both the navigation parameter passed to /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and /// a dictionary of state preserved by this page during an earlier /// session. The state will be null the first time a page is visited.</param> private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e) { bool failed = false; var errorMessage = string.Empty; try { prYuanwen.IsActive = true; prYuanwen.Visibility = Visibility.Visible; lvYuanwen.Visibility = Visibility.Collapsed; var setting = new AppSettingsViewModel(); if (setting != null) { switch (setting.AudioSetting) { case "美音": AudioType = Mp3Type.American; break; case "英音": AudioType = Mp3Type.English; break; default: AudioType = Mp3Type.American; break; } } bookTextKey = (string)e.NavigationParameter; var message = new ValueSet(); message.Add("bookTextKey", bookTextKey); BackgroundMediaPlayer.SendMessageToBackground(message); var bookTextInfo = await GetBookTextDataSource.GetBookTextAsync(null, bookTextKey); this.DefaultViewModel["BookText"] = bookTextInfo; bookTitle = bookTextInfo.Value.Name; var sampleDataGroup = await GetYuanWenListDataSource.GetYuanWenAsync(bookTextKey : bookTextKey); this.DefaultViewModel[FirstGroupName] = sampleDataGroup; var mp3file = await DownloadAudioFile(); string[] fileInfo = new[] { bookTitle, mp3file, bookTextKey, "!autoplay" }; message = new ValueSet { { "SetSource", fileInfo } }; BackgroundMediaPlayer.SendMessageToBackground(message); } catch (Exception ex) { errorMessage = Helper.HandlerExceptionMessage(ex); failed = true; } finally { prYuanwen.IsActive = false; prYuanwen.Visibility = Visibility.Collapsed; lvYuanwen.Visibility = Visibility.Visible; } if (failed) { MessageDialog md2 = new MessageDialog(errorMessage, Constants.NETWORK_CONNECTION); await md2.ShowAsync(); } }
private async Task HandleShellRecentItemsMessage(Dictionary <string, object> message) { var action = (string)message["action"]; var response = new ValueSet(); switch (action) { // enumerate `\Windows\Recent` for recent folders // note: files are enumerated using (Win32MessageHandler: "ShellFolder") in RecentItemsManager case "EnumerateFolders": var enumerateFoldersResponse = await Win32API.StartSTATask(() => { try { var shellLinkItems = new List <ShellLinkItem>(); var excludeMask = FileAttributes.Hidden; var linkFilePaths = Directory.EnumerateFiles(RecentItemsPath).Where(f => (new FileInfo(f).Attributes & excludeMask) == 0); foreach (var linkFilePath in linkFilePaths) { using var link = new ShellLink(linkFilePath, LinkResolution.NoUIWithMsgPump, null, TimeSpan.FromMilliseconds(100)); try { if (!string.IsNullOrEmpty(link.TargetPath) && link.Target.IsFolder) { var shellLinkItem = ShellFolderExtensions.GetShellLinkItem(link); shellLinkItems.Add(shellLinkItem); } } catch (FileNotFoundException) { // occurs when shortcut or shortcut target is deleted and accessed (link.Target) // consequently, we shouldn't include the item as a recent item } } response.Add("EnumerateFolders", JsonConvert.SerializeObject(shellLinkItems)); } catch (Exception e) { Program.Logger.Warn(e); } return(response); }); await Win32API.SendMessageAsync(connection, enumerateFoldersResponse, message.Get("RequestID", (string)null)); break; case "Add": var addResponse = await Win32API.StartSTATask(() => { try { var path = (string)message["Path"]; Shell32.SHAddToRecentDocs(Shell32.SHARD.SHARD_PATHW, path); } catch (Exception e) { Program.Logger.Warn(e); } return(response); }); await Win32API.SendMessageAsync(connection, addResponse, message.Get("RequestID", (string)null)); break; case "Clear": var clearResponse = await Win32API.StartSTATask(() => { try { Shell32.SHAddToRecentDocs(Shell32.SHARD.SHARD_PIDL, (string)null); } catch (Exception e) { Program.Logger.Warn(e); } return(response); }); await Win32API.SendMessageAsync(connection, clearResponse, message.Get("RequestID", (string)null)); break; // invoke 'remove' verb on the file to remove it from Quick Access // note: for folders, we need to use the verb 'unpinfromhome' or 'removefromhome' case "UnpinFile": var unpinFileResponse = await Win32API.StartSTATask(() => { try { var path = (string)message["Path"]; var command = $"-command \"((New-Object -ComObject Shell.Application).Namespace('shell:{QuickAccessGuid}\').Items() " + $"| Where-Object {{ $_.Path -eq '{path}' }}).InvokeVerb('remove')\""; bool success = Win32API.RunPowershellCommand(command, false); response.Add("UnpinFile", path); response.Add("Success", success); } catch (Exception e) { Program.Logger.Warn(e); } return(response); }); await Win32API.SendMessageAsync(connection, unpinFileResponse, message.Get("RequestID", (string)null)); break; } }
private static void GetReturnData(ValueSet message, ref ValueSet returnData) { string command = message["Command"] as string; switch (command.ToUpper()) { case "INIT": { Hashtable result = CommonInit(); string status = "OK"; if (!(bool)result[TypeZigBee]) { status = "\nFail to init ZigBee"; } returnData.Add("Status", status); } break; case "GETPHRASELIST": { List <string> result = null; try { using (var db = new IOTOI.Model.Db.Context()) { result = (from ep in db.ZigBeeEndPoint where ep.CustomName != null select ep.CustomName) .ToList(); } } catch (Exception e) { loggingServices.Write(Log, e.Message, LogLevel.Error, e); } returnData.Add("Result", JsonConvert.SerializeObject(result)); returnData.Add("Status", "OK"); } break; case "GETDEVICE": { returnData.Add("Result", JsonConvert.SerializeObject(ZigBeeService.GetEndPoint(message["Target"] as string))); returnData.Add("Status", "OK"); } break; case "GETSTATUS": { returnData.Add("Result", ZigBeeService.GetEndPointStatus(message["Target"] as string)); returnData.Add("Status", "OK"); } break; case "SETNESTTOKEN": { strNestToken = message["NESTTOKEN"].ToString(); Nest.NestCommandHandler.ThermostatAPI.ApplyAccessToken(strNestToken); returnData.Add("Status", "OK"); } break; case "GETNESTSTATUS": { //TODO : NEST GET STATUS //Result CASE 1(temperature : 60) //Result CASE 2(fan : true or false) #region if (message["Target"].ToString() == "temperature") { string r = Nest.NestCommandHandler.CurrentTemperature(); if (r.Contains("Fail:")) { returnData.Add("Status", r); } else { returnData.Add("Result", r); returnData.Add("Status", "OK"); } } else if (message["Target"].ToString() == "fan") { string r = Nest.NestCommandHandler.CurrentFanStatus(); if (r.Contains("Fail:")) { returnData.Add("Status", r); } else { returnData.Add("Result", r); // FanRunning , FanStopped returnData.Add("Status", "OK"); } } #endregion } break; default: { returnData.Add("Status", "Fail: unknown command"); break; } } }
public async override void GetSpecialProperties() { ViewModel.IsHidden = NativeFileOperationsHelper.HasFileAttribute( Item.ItemPath, System.IO.FileAttributes.Hidden); var fileIconInfo = await AppInstance.FilesystemViewModel.LoadIconOverlayAsync(Item.ItemPath, 80); if (fileIconInfo.Icon != null && fileIconInfo.IsCustom) { ViewModel.FileIconSource = fileIconInfo.Icon; } if (Item.IsShortcutItem) { ViewModel.ItemSizeVisibility = Visibility.Visible; ViewModel.ItemSize = ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation() + " (" + ByteSize.FromBytes(Item.FileSizeBytes).Bytes.ToString("#,##0") + " " + "ItemSizeBytes".GetLocalized() + ")"; ViewModel.ItemCreatedTimestamp = Item.ItemDateCreated; ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed; if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((ShortcutItem)Item).TargetPath)) { // Can't show any other property return; } } StorageFolder storageFolder; try { storageFolder = await AppInstance.FilesystemViewModel.GetFolderFromPathAsync((Item as ShortcutItem)?.TargetPath ?? Item.ItemPath); } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message); // Could not access folder, can't show any other property return; } if (storageFolder != null) { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; string returnformat = Enum.Parse <TimeStyle>(localSettings.Values[Constants.LocalSettings.DateTimeFormat].ToString()) == TimeStyle.Application ? "D" : "g"; ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDateFromFormat(storageFolder.DateCreated, returnformat); GetOtherProperties(storageFolder.Properties); GetFolderSize(storageFolder, TokenSource.Token); } else if (Item.ItemPath.Equals(App.AppSettings.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) { // GetFolderFromPathAsync cannot access recyclebin folder if (AppInstance.FilesystemViewModel.Connection != null) { var value = new ValueSet(); value.Add("Arguments", "RecycleBin"); value.Add("action", "Query"); // Send request to fulltrust process to get recyclebin properties var response = await AppInstance.FilesystemViewModel.Connection.SendMessageAsync(value); if (response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success) { if (response.Message.TryGetValue("BinSize", out var binSize)) { ViewModel.ItemSizeBytes = (long)binSize; ViewModel.ItemSize = ByteSize.FromBytes((long)binSize).ToString(); ViewModel.ItemSizeVisibility = Visibility.Visible; } else { ViewModel.ItemSizeVisibility = Visibility.Collapsed; } if (response.Message.TryGetValue("NumItems", out var numItems)) { ViewModel.FilesCount = (int)(long)numItems; SetItemsCountString(); ViewModel.FilesAndFoldersCountVisibility = Visibility.Visible; } else { ViewModel.FilesAndFoldersCountVisibility = Visibility.Collapsed; } ViewModel.ItemCreatedTimestampVisibiity = Visibility.Collapsed; ViewModel.ItemAccessedTimestampVisibility = Visibility.Collapsed; ViewModel.ItemModifiedTimestampVisibility = Visibility.Collapsed; ViewModel.ItemFileOwnerVisibility = Visibility.Collapsed; ViewModel.LastSeparatorVisibility = Visibility.Collapsed; } } } }
public static async Task <ValueSet> FindElementProperty(ValueSet arguments) { ValueSet results = new ValueSet(); if (Queue == null) { Log.Error("VisualTreeHelper - Missing UI DispatcherQueue"); return(null); } await Queue.EnqueueAsync(() => { // Dispatch? var content = Window.Current.Content as Frame; if (content == null) { Log.Error("VisualTreeHelper.FindElementProperty - Window has no content."); return; } if (arguments.TryGetValue("ElementName", out object value) && value is string name && arguments.TryGetValue("Property", out object value2) && value2 is string propertyName) { Log.Comment("VisualTreeHelper.FindElementProperty('{0}', '{1}')", name, propertyName); // 1. Find Element in Visual Tree var element = content.FindDescendant(name); try { Log.Comment("VisualTreeHelper.FindElementProperty - Found Element? {0}", element != null); var typeinfo = element.GetType().GetTypeInfo(); Log.Comment("Element Type: {0}", typeinfo.FullName); var prop = element.GetType().GetTypeInfo().GetProperty(propertyName); if (prop == null) { Log.Error("VisualTreeHelper.FindElementProperty - Couldn't find Property named {0} on type {1}", propertyName, typeinfo.FullName); return; } // 2. Get the property using reflection var propValue = prop.GetValue(element); // 3. Serialize and return the result results.Add("Result", JsonSerializer.Serialize(propValue, SerializerOptions)); } catch (Exception e) { Log.Error("Error {0}", e.Message); Log.Error("StackTrace:\n{0}", e.StackTrace); } } }); if (results.Count > 0) { return(results); } return(null); // Failure }
private async void InitAppSvc() { // Initialize the AppServiceConnection appServiceConnection = new AppServiceConnection(); appServiceConnection.PackageFamilyName = "fe84f789-e7b7-4c2e-b960-955e3aab0ea0_vayj3az00mxpp"; appServiceConnection.AppServiceName = "App2AppComService"; whAppServiceConnection = new AppServiceConnection(); whAppServiceConnection.PackageFamilyName = "WHTaskConnectApp_vayj3az00mxpp"; whAppServiceConnection.AppServiceName = "org.laz.tcwebhook"; // Send a initialize request var res = await appServiceConnection.OpenAsync(); if (res == AppServiceConnectionStatus.Success) { var message = new ValueSet(); message.Add("Command", "DashboardReady"); var response = await appServiceConnection.SendMessageAsync(message); if (response.Status != AppServiceResponseStatus.Success) { telemetry.TrackEvent("Laz.Org.AppService.Msg.Fail.App2AppComService"); throw new Exception("Failed to send message"); } Debug.WriteLine("AppServiceConnection initialized"); telemetry.TrackEvent("Laz.Org.AppService.Conn.Success.App2AppComService"); appServiceConnection.RequestReceived += OnMessageReceived; } else { Debug.WriteLine("Failed to initialize AppServiceConnection"); telemetry.TrackEvent("Laz.Org.AppService.Conn.Fail.App2AppComService"); } //--- var whRes = await whAppServiceConnection.OpenAsync(); if (whRes == AppServiceConnectionStatus.Success) { var whMessage = new ValueSet(); whMessage.Add("Command", "DashboardReady"); var whResponse = await whAppServiceConnection.SendMessageAsync(whMessage); if (whResponse.Status != AppServiceResponseStatus.Success) { telemetry.TrackEvent("Laz.Org.AppService.Msg.Fail.tcwebhook"); throw new Exception("Failed to send message to WH service"); } whAppServiceConnection.RequestReceived += WhAppServiceConnection_RequestReceived; telemetry.TrackEvent("Laz.Org.AppService.Conn.Success.tcwebhook"); } else { Debug.WriteLine("Failed to connect to WH app service connection"); telemetry.TrackEvent("Laz.Org.AppServiceInitialize.Conn.Fail.tcwebhook"); } }
public void Serialize(ValueSet value) { value.Add(nameof(Songs), Songs); }
// Method for activating Radio private void Button_Click_2(object sender, RoutedEventArgs e) { var loader = new Windows.ApplicationModel.Resources.ResourceLoader(); networkStatus.Text = loader.GetString("CS_Text2"); networkStatus.Foreground = new SolidColorBrush(Colors.Yellow); InternetTest.Navigate(new Uri("http://curiosity.shoutca.st:8019/stream")); if (InternetAvailable == true) { if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true) { streamStatus.Text = loader.GetString("CS_Text20"); streamStatus.Foreground = new SolidColorBrush(Colors.Gray); networkStatus.Text = "..."; networkStatus.Foreground = new SolidColorBrush(Colors.Green); try { streamStatus.Text = loader.GetString("CS_Text21"); if (MediaPlayerState.Playing != BackgroundMediaPlayer.Current.CurrentState) { BackgroundAudioTask.MyBackgroundAudioTask backgroundAccess = new BackgroundAudioTask.MyBackgroundAudioTask(); streamStatus.Text = loader.GetString("CS_Text22"); var message = new ValueSet(); streamStatus.Text = loader.GetString("CS_Text23"); ApplicationSettingsHelper.SaveSettingsValue(Constants.CurrentTrack, "192"); streamStatus.Text = loader.GetString("CS_Text24"); message.Add(Constants.StartPlayback, "0"); streamStatus.Text = loader.GetString("CS_Text25"); BackgroundMediaPlayer.SendMessageToBackground(message); } streamStatus.Text = "..."; } catch (Exception) { networkStatus.Text = loader.GetString("CS_Text26"); networkStatus.Foreground = new SolidColorBrush(Colors.Red); if (MediaPlayerState.Playing == BackgroundMediaPlayer.Current.CurrentState) { streamStatus.Text = loader.GetString("CS_Text27"); } else { try { BackgroundMediaPlayer.Current.Play(); } catch (Exception) { } } } } else { networkStatus.Text = loader.GetString("CS_Text28"); networkStatus.Foreground = new SolidColorBrush(Colors.Yellow); streamStatus.Text = loader.GetString("CS_Text29"); streamStatus.Foreground = new SolidColorBrush(Colors.Red); } } else // If Internet Is Not Available { networkStatus.Text = loader.GetString("CS_Text30"); networkStatus.Foreground = new SolidColorBrush(Colors.Red); streamStatus.Text = loader.GetString("CS_Text31"); streamStatus.Foreground = new SolidColorBrush(Colors.Red); } }
private void mediaElement_CurrentStateChanged(object sender, RoutedEventArgs e) { switch (mediaElement.CurrentState) { case MediaElementState.Closed: btn_Play.Visibility = Visibility.Visible; btn_Pause.Visibility = Visibility.Collapsed; LoadDanmu = false; break; case MediaElementState.Opening: btn_Play.Visibility = Visibility.Visible; btn_Pause.Visibility = Visibility.Collapsed; progress.Visibility = Visibility.Visible; LoadDanmu = false; break; case MediaElementState.Buffering: btn_Play.Visibility = Visibility.Collapsed; btn_Pause.Visibility = Visibility.Visible; progress.Visibility = Visibility.Visible; LoadDanmu = false; try{ ValueSet vs = new ValueSet(); vs.Add("Play", "Playing"); BackgroundMediaPlayer.SendMessageToBackground(vs); } catch { } break; case MediaElementState.Playing: btn_Play.Visibility = Visibility.Collapsed; btn_Pause.Visibility = Visibility.Visible; progress.Visibility = Visibility.Collapsed; LoadDanmu = true; try{ ValueSet vs = new ValueSet(); vs.Add("Play", "Playing"); BackgroundMediaPlayer.SendMessageToBackground(vs); } catch { } break; case MediaElementState.Paused: btn_Play.Visibility = Visibility.Visible; btn_Pause.Visibility = Visibility.Collapsed; progress.Visibility = Visibility.Collapsed; LoadDanmu = false; try{ ValueSet vs = new ValueSet(); vs.Add("Play", "Paused"); BackgroundMediaPlayer.SendMessageToBackground(vs); } catch { } break; case MediaElementState.Stopped: btn_Play.Visibility = Visibility.Visible; btn_Pause.Visibility = Visibility.Collapsed; progress.Visibility = Visibility.Collapsed; LoadDanmu = false; try{ ValueSet vs = new ValueSet(); vs.Add("Play", "Paused"); BackgroundMediaPlayer.SendMessageToBackground(vs); } catch { } break; default: break; } }
public async override void GetSpecialProperties() { if (Item.IsShortcutItem) { ViewModel.ItemSizeVisibility = Visibility.Visible; ViewModel.ItemSize = ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation() + " (" + ByteSize.FromBytes(Item.FileSizeBytes).Bytes.ToString("#,##0") + " " + "ItemSizeBytes".GetLocalized() + ")"; ViewModel.ItemCreatedTimestamp = Item.ItemDateCreated; ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed; if (Item.IsLinkItem || string.IsNullOrWhiteSpace(((ShortcutItem)Item).TargetPath)) { // Can't show any other property return; } } var parentDirectory = App.CurrentInstance.FilesystemViewModel.CurrentFolder; StorageFolder storageFolder = null; try { var isItemSelected = await CoreApplication.MainView.ExecuteOnUIThreadAsync(() => App.CurrentInstance?.ContentPage?.IsItemSelected ?? true); if (isItemSelected) { storageFolder = await ItemViewModel.GetFolderFromPathAsync((Item as ShortcutItem)?.TargetPath ?? Item.ItemPath); } else if (!parentDirectory.ItemPath.StartsWith(App.AppSettings.RecycleBinPath)) { storageFolder = await ItemViewModel.GetFolderFromPathAsync(parentDirectory.ItemPath); } } catch (Exception ex) { NLog.LogManager.GetCurrentClassLogger().Error(ex, ex.Message); // Could not access folder, can't show any other property return; } if (storageFolder != null) { ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; string returnformat = Enum.Parse <TimeStyle>(localSettings.Values[LocalSettings.DateTimeFormat].ToString()) == TimeStyle.Application ? "D" : "g"; ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDateFromFormat(storageFolder.DateCreated, returnformat); LoadFolderIcon(storageFolder); GetOtherProperties(storageFolder.Properties); GetFolderSize(storageFolder, TokenSource.Token); } else if (parentDirectory.ItemPath.StartsWith(App.AppSettings.RecycleBinPath)) { // GetFolderFromPathAsync cannot access recyclebin folder if (App.Connection != null) { var value = new ValueSet(); value.Add("Arguments", "RecycleBin"); value.Add("action", "Query"); // Send request to fulltrust process to get recyclebin properties var response = await App.Connection.SendMessageAsync(value); if (response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success) { if (response.Message.TryGetValue("BinSize", out var binSize)) { ViewModel.ItemSizeBytes = (long)binSize; ViewModel.ItemSize = ByteSize.FromBytes((long)binSize).ToString(); ViewModel.ItemSizeVisibility = Visibility.Visible; } else { ViewModel.ItemSizeVisibility = Visibility.Collapsed; } if (response.Message.TryGetValue("NumItems", out var numItems)) { ViewModel.FilesCount = (int)(long)numItems; SetItemsCountString(); ViewModel.FilesAndFoldersCountVisibility = Visibility.Visible; } else { ViewModel.FilesAndFoldersCountVisibility = Visibility.Collapsed; } ViewModel.ItemCreatedTimestampVisibiity = Visibility.Collapsed; ViewModel.ItemAccessedTimestampVisibility = Visibility.Collapsed; ViewModel.ItemModifiedTimestampVisibility = Visibility.Collapsed; ViewModel.ItemFileOwnerVisibility = Visibility.Collapsed; ViewModel.LastSeparatorVisibility = Visibility.Collapsed; } } } }
public void Serialize(ValueSet value) { value.Add(nameof(Timestamp), Timestamp); }
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(); var result = new ValueSet(); string response = AppServiceTaskConstant.RESULT_FIELD_ERROR_VALUE; try { if ((args.Request != null) && (args.Request.Message != null)) { var inputs = args.Request.Message; if (inputs.ContainsKey(AppServiceTaskConstant.COMMAND_FIELD)) { string s = (string)inputs[AppServiceTaskConstant.COMMAND_FIELD]; if (string.Equals(s, AppServiceTaskConstant.COMMAND_FIELD_DATA_VALUE)) { if ((inputs.ContainsKey(AppServiceTaskConstant.DATA_FIELD)) && (inputs.ContainsKey(AppServiceTaskConstant.SOURCE_FIELD))) { string data = (string)inputs[AppServiceTaskConstant.DATA_FIELD]; string source = (string)inputs[AppServiceTaskConstant.SOURCE_FIELD]; if ((string.Equals(source, AppServiceTaskConstant.SOURCE_FIELD_LOCAL_VALUE)) && (remoteConnectionList != null) && (remoteConnectionList.Count > 0)) { bool res = await SendMessage(true, inputs); if (res == true) { System.Diagnostics.Debug.WriteLine("AppService Task data sent"); response = AppServiceTaskConstant.RESULT_FIELD_OK_VALUE; } else { response = AppServiceTaskConstant.RESULT_FIELD_ERROR_VALUE; } } else if ((string.Equals(source, AppServiceTaskConstant.SOURCE_FIELD_REMOTE_VALUE)) && (localConnectionList != null) && (localConnectionList.Count > 0)) { bool res = await SendMessage(false, inputs); if (res == true) { System.Diagnostics.Debug.WriteLine("AppService Task data sent"); response = AppServiceTaskConstant.RESULT_FIELD_OK_VALUE; } else { response = AppServiceTaskConstant.RESULT_FIELD_ERROR_VALUE; } } else { response = AppServiceTaskConstant.RESULT_FIELD_ERROR_VALUE; } } } else if (string.Equals(s, AppServiceTaskConstant.COMMAND_FIELD_INIT_VALUE)) { // Background task started if ((inputs.ContainsKey(AppServiceTaskConstant.SOURCE_FIELD))) { string source = (string)inputs[AppServiceTaskConstant.SOURCE_FIELD]; if ((string.Equals(source, AppServiceTaskConstant.SOURCE_FIELD_LOCAL_VALUE)) && (localConnectionList != null)) { SetConnected(false, sender, true); response = AppServiceTaskConstant.RESULT_FIELD_OK_VALUE; System.Diagnostics.Debug.WriteLine("AppService Connection established"); } else if ((string.Equals(source, AppServiceTaskConstant.SOURCE_FIELD_REMOTE_VALUE)) && (remoteConnectionList != null)) { SetConnected(true, sender, true); response = AppServiceTaskConstant.RESULT_FIELD_OK_VALUE; System.Diagnostics.Debug.WriteLine("AppService Connection established"); } else { response = AppServiceTaskConstant.RESULT_FIELD_ERROR_VALUE; } } } } } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception while receiving message: " + e.Message); } finally { result.Add(AppServiceTaskConstant.RESULT_FIELD, response); await args.Request.SendResponseAsync(result); //Complete the message deferral so the platform knows we're done responding messageDeferral.Complete(); } }
public async Task ParseArgumentsAsync(PipeStream connection, Dictionary <string, object> message, string arguments) { switch (arguments) { case "Bitlocker": var bitlockerAction = (string)message["action"]; if (bitlockerAction == "Unlock") { var drive = (string)message["drive"]; var password = (string)message["password"]; Win32API.UnlockBitlockerDrive(drive, password); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Bitlocker", "Unlock" } }, message.Get("RequestID", (string)null)); } break; case "SetVolumeLabel": var driveName = (string)message["drivename"]; var newLabel = (string)message["newlabel"]; Win32API.SetVolumeLabel(driveName, newLabel); await Win32API.SendMessageAsync(connection, new ValueSet() { { "SetVolumeLabel", driveName } }, message.Get("RequestID", (string)null)); break; case "GetIconOverlay": var fileIconPath = (string)message["filePath"]; var thumbnailSize = (int)(long)message["thumbnailSize"]; var isOverlayOnly = (bool)message["isOverlayOnly"]; var iconOverlay = await Win32API.StartSTATask(() => Win32API.GetFileIconAndOverlay(fileIconPath, thumbnailSize, true, isOverlayOnly)); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Icon", iconOverlay.icon }, { "Overlay", iconOverlay.overlay } }, message.Get("RequestID", (string)null)); break; case "GetIconWithoutOverlay": var fileIconPath2 = (string)message["filePath"]; var thumbnailSize2 = (int)(long)message["thumbnailSize"]; var icon2 = await Win32API.StartSTATask(() => Win32API.GetFileIconAndOverlay(fileIconPath2, thumbnailSize2, false)); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Icon", icon2.icon }, }, message.Get("RequestID", (string)null)); break; case "ShellFolder": // Enumerate shell folder contents and send response to UWP var folderPath = (string)message["folder"]; var responseEnum = new ValueSet(); var folderContentsList = await Win32API.StartSTATask(() => { var flc = new List <ShellFileItem>(); try { using (var shellFolder = new ShellFolder(folderPath)) { foreach (var folderItem in shellFolder) { try { var shellFileItem = ShellFolderExtensions.GetShellFileItem(folderItem); flc.Add(shellFileItem); } catch (FileNotFoundException) { // Happens if files are being deleted } finally { folderItem.Dispose(); } } } } catch { } return(flc); }); responseEnum.Add("Enumerate", JsonConvert.SerializeObject(folderContentsList)); await Win32API.SendMessageAsync(connection, responseEnum, message.Get("RequestID", (string)null)); break; case "GetFolderIconsFromDLL": var iconInfos = Win32API.ExtractIconsFromDLL((string)message["iconFile"]); await Win32API.SendMessageAsync(connection, new ValueSet() { { "IconInfos", JsonConvert.SerializeObject(iconInfos) }, }, message.Get("RequestID", (string)null)); break; case "SetCustomFolderIcon": await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", Win32API.SetCustomDirectoryIcon((string)message["folder"], (string)message["iconFile"], (int)message.Get("iconIndex", 0L)) }, }, message.Get("RequestID", (string)null)); break; case "GetSelectedIconsFromDLL": var selectedIconInfos = Win32API.ExtractSelectedIconsFromDLL((string)message["iconFile"], JsonConvert.DeserializeObject <List <int> >((string)message["iconIndexes"]), Convert.ToInt32(message["requestedIconSize"])); await Win32API.SendMessageAsync(connection, new ValueSet() { { "IconInfos", JsonConvert.SerializeObject(selectedIconInfos) }, }, message.Get("RequestID", (string)null)); break; case "SetAsDefaultExplorer": { var enable = (bool)message["Value"]; var destFolder = Path.Combine(ApplicationData.Current.LocalFolder.Path, "FilesOpenDialog"); Directory.CreateDirectory(destFolder); foreach (var file in Directory.GetFiles(Path.Combine(Package.Current.InstalledLocation.Path, "Files.Launcher", "Assets", "FilesOpenDialog"))) { if (!Extensions.IgnoreExceptions(() => File.Copy(file, Path.Combine(destFolder, Path.GetFileName(file)), true), Program.Logger)) { // Error copying files DetectIsSetAsDefaultFileManager(); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null)); return; } } try { using var regProcess = Process.Start("regedit.exe", @$ "/s " "{Path.Combine(destFolder, enable ? " SetFilesAsDefault.reg " : " UnsetFilesAsDefault.reg ")}" ""); regProcess.WaitForExit(); DetectIsSetAsDefaultFileManager(); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", true } }, message.Get("RequestID", (string)null)); } catch { // Canceled UAC DetectIsSetAsDefaultFileManager(); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null)); } } break; case "SetAsOpenFileDialog": { var enable = (bool)message["Value"]; var destFolder = Path.Combine(ApplicationData.Current.LocalFolder.Path, "FilesOpenDialog"); Directory.CreateDirectory(destFolder); foreach (var file in Directory.GetFiles(Path.Combine(Package.Current.InstalledLocation.Path, "Files.Launcher", "Assets", "FilesOpenDialog"))) { if (!Extensions.IgnoreExceptions(() => File.Copy(file, Path.Combine(destFolder, Path.GetFileName(file)), true), Program.Logger)) { // Error copying files DetectIsSetAsOpenFileDialog(); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null)); return; } } try { using var regProc32 = Process.Start("regsvr32.exe", @$ "/s /n {(!enable ? " / u " : " ")} /i:user " "{Path.Combine(destFolder, " CustomOpenDialog32.dll ")}" ""); regProc32.WaitForExit(); using var regProc64 = Process.Start("regsvr32.exe", @$ "/s /n {(!enable ? " / u " : " ")} /i:user " "{Path.Combine(destFolder, " CustomOpenDialog64.dll ")}" ""); regProc64.WaitForExit(); DetectIsSetAsOpenFileDialog(); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", true } }, message.Get("RequestID", (string)null)); } catch { DetectIsSetAsOpenFileDialog(); await Win32API.SendMessageAsync(connection, new ValueSet() { { "Success", false } }, message.Get("RequestID", (string)null)); } } break; case "GetFileAssociation": { var filePath = (string)message["filepath"]; await Win32API.SendMessageAsync(connection, new ValueSet() { { "FileAssociation", await Win32API.GetFileAssociationAsync(filePath, true) } }, message.Get("RequestID", (string)null)); } break; } }
public async override void GetSpecialProperties() { if (Item.IsShortcutItem) { ViewModel.ItemSizeVisibility = Visibility.Visible; ViewModel.ItemSize = ByteSize.FromBytes(Item.FileSizeBytes).ToBinaryString().ConvertSizeAbbreviation() + " (" + ByteSize.FromBytes(Item.FileSizeBytes).Bytes.ToString("#,##0") + " " + ResourceController.GetTranslation("ItemSizeBytes") + ")"; ViewModel.ItemCreatedTimestamp = Item.ItemDateCreated; ViewModel.ItemAccessedTimestamp = Item.ItemDateAccessed; // Can't show any other property return; } StorageFolder storageFolder; var isItemSelected = await CoreApplication.MainView.ExecuteOnUIThreadAsync(() => App.CurrentInstance.ContentPage.IsItemSelected); if (isItemSelected) { storageFolder = await ItemViewModel.GetFolderFromPathAsync(Item.ItemPath); ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDate(storageFolder.DateCreated); GetOtherProperties(storageFolder.Properties); GetFolderSize(storageFolder, TokenSource.Token); } else { var parentDirectory = App.CurrentInstance.FilesystemViewModel.CurrentFolder; if (parentDirectory.ItemPath.StartsWith(App.AppSettings.RecycleBinPath)) { // GetFolderFromPathAsync cannot access recyclebin folder if (App.Connection != null) { var value = new ValueSet(); value.Add("Arguments", "RecycleBin"); value.Add("action", "Query"); // Send request to fulltrust process to get recyclebin properties var response = await App.Connection.SendMessageAsync(value); if (response.Status == Windows.ApplicationModel.AppService.AppServiceResponseStatus.Success) { if (response.Message.TryGetValue("BinSize", out var binSize)) { ViewModel.ItemSizeBytes = (long)binSize; ViewModel.ItemSize = ByteSize.FromBytes((long)binSize).ToString(); ViewModel.ItemSizeVisibility = Visibility.Visible; } else { ViewModel.ItemSizeVisibility = Visibility.Collapsed; } if (response.Message.TryGetValue("NumItems", out var numItems)) { ViewModel.FilesCount = (int)(long)numItems; SetItemsCountString(); ViewModel.FilesAndFoldersCountVisibility = Visibility.Visible; } else { ViewModel.FilesAndFoldersCountVisibility = Visibility.Collapsed; } ViewModel.ItemCreatedTimestampVisibiity = Visibility.Collapsed; ViewModel.ItemAccessedTimestampVisibility = Visibility.Collapsed; ViewModel.ItemModifiedTimestampVisibility = Visibility.Collapsed; ViewModel.ItemFileOwnerVisibility = Visibility.Collapsed; ViewModel.LastSeparatorVisibility = Visibility.Collapsed; } } } else { storageFolder = await ItemViewModel.GetFolderFromPathAsync(parentDirectory.ItemPath); ViewModel.ItemCreatedTimestamp = ListedItem.GetFriendlyDate(storageFolder.DateCreated); GetOtherProperties(storageFolder.Properties); GetFolderSize(storageFolder, TokenSource.Token); } } }
private async void DataServiceRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { Debug.WriteLine($"DataServiceRequestReceived"); AppServiceResponse result; AppServiceResponseStatus resultStatus; var messageDeferral = args.GetDeferral(); var request = args.Request; var m = request.Message; object command; try { m.TryGetValue("Command", out command); switch (command as string) { case "Connect": object role; m.TryGetValue("Role", out role); if (role as string == "DataStreamerConnect") // Client { _dataConnection = sender; } var response = new ValueSet(); response.Add("Response", "OK"); await request.SendResponseAsync(response); SendStatusAsync(); break; case "Write": object data; if (m.TryGetValue("Data", out data)) { Debug.WriteLine($"Write data:{data}"); if (_excelConnection != null) { result = await _excelConnection.SendMessageAsync(m); if (result.Status != AppServiceResponseStatus.Success) { Debug.WriteLine($"Failed to send data: {result.Status.ToString()}"); } else { Debug.WriteLine($"Sent: {data as string}"); } } else { Debug.WriteLine($"Failed to send data: no Excel Connection exists"); } } break; case "Read": var msg = new ValueSet(); AppServiceResponse res = null; msg["Command"] = "Read"; if (_excelConnection != null) { res = _excelConnection.SendMessageAsync(msg).AsTask().Result; ; if (res.Status == AppServiceResponseStatus.Success) { Debug.WriteLine($"Data recieved from Excel: {res.Message.Count}"); if (_dataConnection != null) { //var clientRes = _dataConnection.SendMessageAsync(res.Message).AsTask().Result; var clientRes = await request.SendResponseAsync(res.Message); if (clientRes != AppServiceResponseStatus.Success) { Debug.WriteLine($"Failed to send read data to client: {clientRes.ToString()}"); } else { Debug.WriteLine($"Data sent to client: {res.Message.Count}"); } } } else { Debug.WriteLine($"Failed to send data: {res.Status.ToString()}"); } } break; case "Status": var message = new ValueSet(); message.Add("Command", "Status"); message.Add("Data", String.Format("Client:{0},Excel:{1}", _dataConnection != null, _excelConnection != null)); resultStatus = request.SendResponseAsync(message).AsTask().Result; if (resultStatus != AppServiceResponseStatus.Success) { Debug.WriteLine($"Failed to send data: {resultStatus}"); } break; } } catch (Exception e) { Debug.WriteLine($"Exception while sending the response : {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(); } }
private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var messageDeferral = args.GetDeferral(); ValueSet message = args.Request.Message; ValueSet returnData = new ValueSet(); try { string command = message["Command"] as string; string todoTitle = message["Title"] as string; if (command == "Add Todo" && todoTitle.Length > 0) { ObservableCollection <TodoItem> todos = new ObservableCollection <TodoItem>(); bool settingsCreated = false; int lastID = 0; if (ApplicationData.Current.LocalSettings.Values.TryGetValue(Local_Settings_Todo, out object json)) { JsonSerializerSettings settings = new JsonSerializerSettings(); settings.TypeNameHandling = TypeNameHandling.Objects; todos = JsonConvert.DeserializeObject <ObservableCollection <TodoItem> >(json.ToString(), settings); settingsCreated = true; if (ApplicationData.Current.LocalSettings.Values.TryGetValue(Last_Todo_ID, out object last)) { lastID = (int)last; } } lastID++; TodoItem newTodo = new TodoItem(lastID, todoTitle, "..."); todos.Add(newTodo); if (settingsCreated) { ApplicationData.Current.LocalSettings.Values[Local_Settings_Todo] = JsonConvert.SerializeObject(todos); ApplicationData.Current.LocalSettings.Values[Last_Todo_ID] = lastID; } else { ApplicationData.Current.LocalSettings.Values.Add(Local_Settings_Todo, JsonConvert.SerializeObject(todos)); ApplicationData.Current.LocalSettings.Values.Add(Last_Todo_ID, lastID); } //Nuget Packacke UWP.ToastNotification var content = new ToastContent() { // More about the Launch property at https://docs.microsoft.com/dotnet/api/microsoft.toolkit.uwp.notifications.toastcontent Launch = "ToastContentActivationParams", Visual = new ToastVisual() { BindingGeneric = new ToastBindingGeneric() { Children = { new AdaptiveText() { Text = "TODO wurde erstellt!" }, new AdaptiveText() { Text = $"{newTodo.Title}: {newTodo.Description}" } } } }, Actions = new ToastActionsCustom() { Buttons = { // More about Toast Buttons at https://docs.microsoft.com/dotnet/api/microsoft.toolkit.uwp.notifications.toastbutton new ToastButton("Anzeigen", newTodo.ID.ToString()) { ActivationType = ToastActivationType.Foreground }, new ToastButtonDismiss("Abbrechen") } } }; var toast = new ToastNotification(content.GetXml()); ToastNotificationManager.CreateToastNotifier().Show(toast); returnData.Add("Status", "OK"); await args.Request.SendResponseAsync(returnData); } } catch (Exception e) { returnData.Add("Status", e.Message); await args.Request.SendResponseAsync(returnData); return; } finally { messageDeferral?.Complete(); } }
private async void GenerateRandomNumber_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e) { //Is there an open connection? if (connection == null) { rootPage.NotifyUser("You need to open a connection before trying to generate a random number.", NotifyType.ErrorMessage); return; } //Parse user input int minValueInput = 0; bool valueParsed = int.TryParse(MinValue.Text, out minValueInput); if (!valueParsed) { rootPage.NotifyUser("The Minimum Value should be a valid integer", NotifyType.ErrorMessage); return; } int maxValueInput = 0; valueParsed = int.TryParse(MaxValue.Text, out maxValueInput); if (!valueParsed) { rootPage.NotifyUser("The Maximum Value should be a valid integer", NotifyType.ErrorMessage); return; } if (maxValueInput <= minValueInput) { rootPage.NotifyUser("Maximum Value must be larger than Minimum Value", NotifyType.ErrorMessage); return; } //Send a message to the app service var inputs = new ValueSet(); inputs.Add("minvalue", minValueInput); inputs.Add("maxvalue", maxValueInput); AppServiceResponse response = await connection.SendMessageAsync(inputs); //If the service responded display the message. We're done! if (response.Status == AppServiceResponseStatus.Success) { if (!response.Message.ContainsKey("result")) { rootPage.NotifyUser("The app service response message does not contain a key called \"result\"", NotifyType.StatusMessage); return; } var resultText = response.Message["result"].ToString(); if (!string.IsNullOrEmpty(resultText)) { Result.Text = resultText; rootPage.NotifyUser("App service responded with a result", NotifyType.StatusMessage); } else { rootPage.NotifyUser("App service did not respond with a result", NotifyType.ErrorMessage); } } else { //Something went wrong. Show the user a meaningful //message depending upon the status switch (response.Status) { case AppServiceResponseStatus.Failure: rootPage.NotifyUser("The service failed to acknowledge the message we sent it. It may have been terminated because the client was suspended.", NotifyType.ErrorMessage); break; case AppServiceResponseStatus.ResourceLimitsExceeded: rootPage.NotifyUser("The service exceeded the resources allocated to it and had to be terminated.", NotifyType.ErrorMessage); break; case AppServiceResponseStatus.Unknown: default: rootPage.NotifyUser("An unkown error occurred while we were trying to send a message to the service.", NotifyType.ErrorMessage); break; } } }
private static 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(); if (args.Request.Message == null) { messageDeferral.Complete(); return; } try { if (args.Request.Message.ContainsKey("Arguments")) { // This replaces launching the fulltrust process with arguments // Instead a single instance of the process is running // Requests from UWP app are sent via AppService connection var arguments = (string)args.Request.Message["Arguments"]; var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; if (arguments == "Terminate") { // Exit fulltrust process (UWP is closed or suspended) appServiceExit.Set(); messageDeferral.Complete(); } else if (arguments == "RecycleBin") { var action = (string)args.Request.Message["action"]; if (action == "Empty") { // Shell function to empty recyclebin Vanara.PInvoke.Shell32.SHEmptyRecycleBin(IntPtr.Zero, null, Vanara.PInvoke.Shell32.SHERB.SHERB_NOCONFIRMATION | Vanara.PInvoke.Shell32.SHERB.SHERB_NOPROGRESSUI); } else if (action == "Query") { var responseQuery = new ValueSet(); Win32API.SHQUERYRBINFO queryBinInfo = new Win32API.SHQUERYRBINFO(); queryBinInfo.cbSize = (uint)Marshal.SizeOf(typeof(Win32API.SHQUERYRBINFO)); var res = Win32API.SHQueryRecycleBin("", ref queryBinInfo); // TODO: use this when updated library is released //Vanara.PInvoke.Shell32.SHQUERYRBINFO queryBinInfo = new Vanara.PInvoke.Shell32.SHQUERYRBINFO(); //Vanara.PInvoke.Shell32.SHQueryRecycleBin(null, ref queryBinInfo); if (res == Vanara.PInvoke.HRESULT.S_OK) { var numItems = queryBinInfo.i64NumItems; var binSize = queryBinInfo.i64Size; responseQuery.Add("NumItems", numItems); responseQuery.Add("BinSize", binSize); await args.Request.SendResponseAsync(responseQuery); } } else if (action == "Enumerate") { // Enumerate recyclebin contents and send response to UWP var responseEnum = new ValueSet(); var folderContentsList = new List <ShellFileItem>(); foreach (var folderItem in recycler) { try { folderItem.Properties.ReadOnly = true; folderItem.Properties.NoInheritedProperties = false; string recyclePath = folderItem.FileSystemPath; // True path on disk string fileName = Path.GetFileName(folderItem.Name); // Original file name string filePath = folderItem.Name; // Original file path + name var dt = (System.Runtime.InteropServices.ComTypes.FILETIME)folderItem.Properties[Vanara.PInvoke.Ole32.PROPERTYKEY.System.DateCreated]; var recycleDate = dt.ToDateTime().ToLocalTime(); // This is LocalTime string fileSize = folderItem.Properties.GetPropertyString(Vanara.PInvoke.Ole32.PROPERTYKEY.System.Size); ulong fileSizeBytes = (ulong)folderItem.Properties[Vanara.PInvoke.Ole32.PROPERTYKEY.System.Size]; string fileType = (string)folderItem.Properties[Vanara.PInvoke.Ole32.PROPERTYKEY.System.ItemTypeText]; bool isFolder = folderItem.IsFolder && Path.GetExtension(folderItem.Name) != ".zip"; folderContentsList.Add(new ShellFileItem(isFolder, recyclePath, fileName, filePath, recycleDate, fileSize, fileSizeBytes, fileType)); } catch (System.IO.FileNotFoundException) { // Happens if files are being deleted } finally { folderItem.Dispose(); } } responseEnum.Add("Enumerate", Newtonsoft.Json.JsonConvert.SerializeObject(folderContentsList)); await args.Request.SendResponseAsync(responseEnum); } } else if (arguments == "StartupTasks") { // Check QuickLook Availability QuickLook.CheckQuickLookAvailability(localSettings); } else if (arguments == "ToggleQuickLook") { var path = (string)args.Request.Message["path"]; QuickLook.ToggleQuickLook(path); } else if (arguments == "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(); } else if (args.Request.Message.ContainsKey("Application")) { HandleApplicationLaunch(args); } } else if (args.Request.Message.ContainsKey("Application")) { HandleApplicationLaunch(args); } } 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(); } }
private async Task HandleShellLibraryMessage(Dictionary <string, object> message) { switch ((string)message["action"]) { case "Enumerate": // Read library information and send response to UWP var enumerateResponse = await Win32API.StartSTATask(() => { var response = new ValueSet(); try { var libraryItems = new List <ShellLibraryItem>(); // https://docs.microsoft.com/en-us/windows/win32/search/-search-win7-development-scenarios#library-descriptions var libFiles = Directory.EnumerateFiles(ShellLibraryItem.LibrariesPath, "*" + ShellLibraryItem.EXTENSION); foreach (var libFile in libFiles) { using var shellItem = ShellItem.Open(libFile); if (shellItem is ShellLibrary library) { libraryItems.Add(ShellFolderExtensions.GetShellLibraryItem(library, libFile)); } } response.Add("Enumerate", JsonConvert.SerializeObject(libraryItems)); } catch (Exception e) { Program.Logger.Error(e); } return(response); }); await Win32API.SendMessageAsync(connection, enumerateResponse, message.Get("RequestID", (string)null)); break; case "Create": // Try create new library with the specified name and send response to UWP var createResponse = await Win32API.StartSTATask(() => { var response = new ValueSet(); try { using var library = new ShellLibrary((string)message["library"], Shell32.KNOWNFOLDERID.FOLDERID_Libraries, false); response.Add("Create", JsonConvert.SerializeObject(ShellFolderExtensions.GetShellLibraryItem(library, library.GetDisplayName(ShellItemDisplayString.DesktopAbsoluteParsing)))); } catch (Exception e) { Program.Logger.Error(e); } return(response); }); await Win32API.SendMessageAsync(connection, createResponse, message.Get("RequestID", (string)null)); break; case "Update": // Update details of the specified library and send response to UWP var updateResponse = await Win32API.StartSTATask(() => { var response = new ValueSet(); try { var folders = message.ContainsKey("folders") ? JsonConvert.DeserializeObject <string[]>((string)message["folders"]) : null; var defaultSaveFolder = message.Get("defaultSaveFolder", (string)null); var isPinned = message.Get("isPinned", (bool?)null); bool updated = false; var libPath = (string)message["library"]; using var library = ShellItem.Open(libPath) as ShellLibrary; if (folders != null) { if (folders.Length > 0) { var foldersToRemove = library.Folders.Where(f => !folders.Any(folderPath => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase))); foreach (var toRemove in foldersToRemove) { library.Folders.Remove(toRemove); updated = true; } var foldersToAdd = folders.Distinct(StringComparer.OrdinalIgnoreCase) .Where(folderPath => !library.Folders.Any(f => string.Equals(folderPath, f.FileSystemPath, StringComparison.OrdinalIgnoreCase))) .Select(ShellItem.Open); foreach (var toAdd in foldersToAdd) { library.Folders.Add(toAdd); updated = true; } foreach (var toAdd in foldersToAdd) { toAdd.Dispose(); } } } if (defaultSaveFolder != null) { library.DefaultSaveFolder = ShellItem.Open(defaultSaveFolder); updated = true; } if (isPinned != null) { library.PinnedToNavigationPane = isPinned == true; updated = true; } if (updated) { library.Commit(); response.Add("Update", JsonConvert.SerializeObject(ShellFolderExtensions.GetShellLibraryItem(library, libPath))); } } catch (Exception e) { Program.Logger.Error(e); } return(response); }); await Win32API.SendMessageAsync(connection, updateResponse, message.Get("RequestID", (string)null)); break; } }
private async void OnRequestReceived(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(); ValueSet message = args.Request.Message; ValueSet returnData = new ValueSet(); string command = message["q"] as string; switch (command) { case "lyric": var title = message["title"] as string; message.TryGetValue("artist", out object art); var artists = art as string; message.TryGetValue("album", out object alb); var lyalbum = alb as string; var localLrc = await LyricSearcher.SearchLrcLocalAsync(title, artists, lyalbum); if (!localLrc.IsNullorEmpty()) { returnData.Add("result", localLrc); returnData.Add("status", 1); break; } if (message.ContainsKey("ID") && message.ContainsKey("service") && message["service"] as string == "Aurora.Music.Services") { var result = await LyricSearcher.GetSongLrcByID(message["ID"] as string); if (!result.IsNullorEmpty()) { await LyricSearcher.SaveLrcLocalAsync(title, artists, lyalbum, result); returnData.Add("result", result); returnData.Add("status", 1); break; } } var substitutes = await LyricSearcher.GetSongLrcListAsync(title, artists); if (!substitutes.IsNullorEmpty()) { var result = await ApiRequestHelper.HttpGet(substitutes.First().Value); if (!result.IsNullorEmpty()) { result = HttpUtility.HtmlDecode(result); await LyricSearcher.SaveLrcLocalAsync(title, artists, lyalbum, result); returnData.Add("result", result); returnData.Add("status", 1); } else { returnData.Add("result", null); returnData.Add("status", 0); } } else { returnData.Add("result", null); returnData.Add("status", 0); } break; case "online_music": var action = message["action"] as string; switch (action) { case "search": var result = await OnlineMusicSearcher.SearchAsync(message["keyword"] as string); var resultList = new List <PropertySet>(); if (result == null && result.Data != null) { returnData.Add("status", 0); break; } foreach (var item in result.Data.Song.ListItems) { var set = new PropertySet { ["title"] = item.Title, ["description"] = item.SingerItems[0]?.Title, ["addtional"] = item.Album.Title, ["picture_path"] = OnlineMusicSearcher.GeneratePicturePathByID(item.Album.Mid), ["type"] = "song", ["id"] = new string[] { item.Mid }, ["album_id"] = item.Album.Mid }; resultList.Add(set); } if (!resultList.IsNullorEmpty()) { returnData.Add("search_result", JsonConvert.SerializeObject(resultList.ToArray())); returnData.Add("status", 1); } break; case "song": var song = await OnlineMusicSearcher.GetSongAsync(message["id"] as string); if (song != null && !song.DataItems.IsNullorEmpty()) { DateTime.TryParseExact(song.DataItems[0].Album.Time_Public, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime t); // TODO: property var songRes = new PropertySet { ["title"] = song.DataItems[0].Title, ["id"] = song.DataItems[0].Mid, ["album"] = song.DataItems[0].Album.Name, ["album_id"] = song.DataItems[0].Album.Mid, ["performers"] = song.DataItems[0].SingerItems.Select(x => x.Name).ToArray(), ["year"] = t.Year, ["bit_rate"] = Settings.Current.GetPreferredBitRate() * 1000, ["track"] = song.DataItems[0].Index_Album, ["track_count"] = 0, ["duration"] = TimeSpan.Zero.ToString() }; songRes["album_artists"] = songRes["performers"]; var picture = OnlineMusicSearcher.GeneratePicturePathByID(song.DataItems[0].Album.Mid); songRes["picture_path"] = picture; songRes["file_url"] = await OnlineMusicSearcher.GenerateFileUriByID(message["id"] as string, Settings.Current.GetPreferredBitRate()); songRes["file_type"] = OnlineMusicSearcher.GenerateFileTypeByID(message["id"] as string, Settings.Current.GetPreferredBitRate()); returnData.Add("song_result", JsonConvert.SerializeObject(songRes)); returnData.Add("status", 1); } break; case "album": var album = await OnlineMusicSearcher.GetAlbumAsync(message["id"] as string); if (album != null && album.Data != null) { DateTime.TryParseExact(album.Data.GetAlbumInfo.Fpublic_Time, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime t); var albumRes = new PropertySet { ["name"] = album.Data.GetAlbumInfo.Falbum_Name, ["desription"] = album.Data.GetAlbumDesc.Falbum_Desc.Replace("\n", "\r\n\r\n"), ["year"] = t.Year, ["track_count"] = album.Data.GetSongInfoItems.Count, ["disc_count"] = album.Data.GetSongInfoItems.Max(x => x.Index_Cd) + 1, ["picture_path"] = OnlineMusicSearcher.GeneratePicturePathByID(message["id"] as string), ["genres"] = new string[] { album.Data.Genre } }; returnData.Add("album_result", JsonConvert.SerializeObject(albumRes)); returnData.Add("songs", JsonConvert.SerializeObject(album.Data.GetSongInfoItems.Select(x => { var p = new PropertySet() { ["id"] = x.Mid, ["title"] = x.Name, ["album"] = x.Album.Name, ["album_id"] = x.Album.Mid, ["performers"] = x.SingerItems.Select(y => y.Name).ToArray(), ["year"] = t.Year, ["bit_rate"] = Settings.Current.GetPreferredBitRate() * 1000, ["picture_path"] = OnlineMusicSearcher.GeneratePicturePathByID(x.Album.Mid), ["track"] = x.Index_Album, ["duration"] = TimeSpan.Zero.ToString(), ["file_url"] = AsyncHelper.RunSync(async() => await OnlineMusicSearcher.GenerateFileUriByID(x.Mid, Settings.Current.GetPreferredBitRate())), ["file_type"] = OnlineMusicSearcher.GenerateFileTypeByID(x.Mid, Settings.Current.GetPreferredBitRate()) }; p["album_artists"] = p["performers"]; return(p); }))); returnData.Add("album_artists", JsonConvert.SerializeObject(album.Data.SingerInfoItems.Select(x => { return(new PropertySet() { ["name"] = x.Fsinger_Name, ["id"] = x.Fsinger_Mid, }); }))); returnData.Add("status", 1); } break; case "artist": var artist = await OnlineMusicSearcher.GetArtistAsync(message["id"] as string); break; default: break; } break; case "online_meta": var meta_action = message["action"] as string; switch (meta_action) { case "album": var meta_album = await LastfmSearcher.GetAlbumInfo(message["album"] as string, message["artist"] as string); if (meta_album != null) { returnData.Add("status", 1); returnData.Add("album_result", JsonConvert.SerializeObject(new PropertySet() { ["name"] = meta_album.Name, ["artwork"] = meta_album.AltArtwork?.OriginalString, ["desc"] = meta_album.Description, ["artist"] = meta_album.Artist, ["year"] = meta_album.Year })); } break; case "artist": var meta_artist = await LastfmSearcher.GetArtistInfo(message["artist"] as string); if (meta_artist != null) { returnData.Add("status", 1); returnData.Add("artist_result", JsonConvert.SerializeObject(new PropertySet() { ["name"] = meta_artist.Name, ["avatar"] = meta_artist.AvatarUri?.OriginalString, ["desc"] = meta_artist.Description, })); } break; } break; default: returnData.Add("status", 0); break; } await args.Request.SendResponseAsync(returnData); // Return the data to the caller. // 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(); }
private async void ChoosePicture_Click(object sender, RoutedEventArgs e) { // 创建和自定义 FileOpenPicker var picker = new Windows.Storage.Pickers.FileOpenPicker(); picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail; //可通过使用图片缩略图创建丰富的视觉显示,以显示文件选取器中的文件 picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary; picker.FileTypeFilter.Add(".jpg"); picker.FileTypeFilter.Add(".jpeg"); picker.FileTypeFilter.Add(".png"); picker.FileTypeFilter.Add(".gif"); //选取单个文件 Windows.Storage.StorageFile file = await picker.PickSingleFileAsync(); //文件处理 if (file != null) { var inputFile = SharedStorageAccessManager.AddFile(file); var destination = await ApplicationData.Current.LocalFolder.CreateFileAsync("Cropped.jpg", CreationCollisionOption.ReplaceExisting);//在应用文件夹中建立文件用来存储裁剪后的图像 var destinationFile = SharedStorageAccessManager.AddFile(destination); var options = new LauncherOptions(); options.TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe"; //待会要传入的参数 var parameters = new ValueSet(); parameters.Add("InputToken", inputFile); //输入文件 parameters.Add("DestinationToken", destinationFile); //输出文件 parameters.Add("ShowCamera", false); //它允许我们显示一个按钮,以允许用户采取当场图象 parameters.Add("EllipticalCrop", true); //截图区域显示为圆(最后截出来还是方形) parameters.Add("CropWidthPixals", 300); parameters.Add("CropHeightPixals", 300); //调用系统自带截图并返回结果 var result = await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), options, parameters); //按理说下面这个判断应该没问题呀,但是如果裁剪界面点了取消的话后面会出现异常,所以后面我加了try catch if (result.Status == LaunchUriStatus.Success && result.Result != null) { //对裁剪后图像的下一步处理 try { // 载入已保存的裁剪后图片 var stream = await destination.OpenReadAsync(); var bitmap = new BitmapImage(); await bitmap.SetSourceAsync(stream); // 显示 img.ImageSource = bitmap; } catch (Exception ex) { Debug.WriteLine(ex.Message + ex.StackTrace); } } } }