コード例 #1
0
        private async void Buy(string productName, string price, string filename)
        {
            var woodgroveUri = new Uri("woodgrove-pay:");

            var options = new LauncherOptions();

            options.TargetApplicationPackageFamilyName = "111055f1-4e28-4634-b304-e76934e91e53_876gvmnfevegr";

            var inputData = new ValueSet();

            inputData["ProductName"] = productName;
            inputData["Amount"]      = price;


            StorageFolder assetsFolder = await Package.Current.InstalledLocation.GetFolderAsync("Assets\\ProductImages");

            StorageFile imgFile = await assetsFolder.GetFileAsync(filename);

            inputData["ImageFileToken"] = SharedStorageAccessManager.AddFile(imgFile);


            LaunchUriResult result = await Launcher.LaunchUriForResultsAsync(woodgroveUri, options, inputData);

            if (result.Status == LaunchUriStatus.Success &&
                result.Result["Status"] != null &&
                (result.Result["Status"] as string) == "Success")
            {
                this.Frame.Navigate(typeof(OrderPlacedPage), result.Result);
            }
        }
コード例 #2
0
        public async static Task <BitmapImage> LoadPicture()
        {
            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(".jpg");
            picker.FileTypeFilter.Add(".png");
            picker.FileTypeFilter.Add(".gif");
            Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();

            var inputFile = SharedStorageAccessManager.AddFile(file);

            CroppedImage = await ApplicationData.Current.LocalFolder.CreateFileAsync("Cropped.jpg", CreationCollisionOption.ReplaceExisting);

            var destinationFile = SharedStorageAccessManager.AddFile(CroppedImage);
            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);

            return(await ImageHelper.LoadBitmapImage(CroppedImage));
        }
コード例 #3
0
        async void OnAppServiceRequestReceived(AppServiceConnection sender,
                                               AppServiceRequestReceivedEventArgs args)
        {
            var      localDeferral = args.GetDeferral();
            var      parameters    = args.Request.Message;
            ValueSet vs            = new ValueSet();

            if (parameters.ContainsKey("query"))
            {
                var result = await FlickrSearcher.SearchAsync((string)parameters["query"]);

                if ((result != null) && (result.Count > 0))
                {
                    var        first  = result[0];
                    HttpClient client = new HttpClient();
                    using (var response = await client.GetAsync(new Uri(first.ImageUrl)))
                    {
                        var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(first.Id.ToString(),
                                                                                                 CreationCollisionOption.ReplaceExisting);

                        using (var fileStream = await file.OpenStreamForWriteAsync())
                        {
                            await response.Content.CopyToAsync(fileStream);
                        }
                        var token = SharedStorageAccessManager.AddFile(file);
                        vs["pictureToken"] = token;
                    }
                }
            }
            await args.Request.SendResponseAsync(vs);

            localDeferral.Complete();
        }
コード例 #4
0
        private async void SaveImage_Click(object sender, RoutedEventArgs e)
        {
            if (protocolForResultsArgs == null)
            {
                SaveButton.IsEnabled = false;

                var savePicker = new FileSavePicker()
                {
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                    SuggestedFileName      = string.Format("QuickstartImage_{0}", DateTime.Now.ToString("yyyyMMddHHmmss"))
                };

                savePicker.FileTypeChoices.Add("JPG File", new List <string> {
                    ".jpg"
                });

                SaveImage(savePicker);
            }
            else
            {
                // save file to a local file, and send token back to caller
                var destFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("EditedOutput.jpg", CreationCollisionOption.GenerateUniqueName);
                await SaveImageAsync(destFile);

                var operation = protocolForResultsArgs.ProtocolForResultsOperation;

                var result = new ValueSet();
                result["Success"] = true;
                result["Reason"]  = "Completed";
                result["Token"]   = SharedStorageAccessManager.AddFile(destFile);

                operation.ReportCompleted(result);
            }
        }
コード例 #5
0
        private async Task<LaunchUriResult> CropImageAsync(IStorageFile input, IStorageFile destination, int width, int height) {
            // Get access tokens to pass input and output files between apps
            var inputToken = SharedStorageAccessManager.AddFile(input);
            var destinationToken = SharedStorageAccessManager.AddFile(destination);

            // Specify an app to launch by using LaunchUriForResultsAsync
            var options = new LauncherOptions();
            options.TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe";

            // Specify protocol launch options
            var parameters = new ValueSet();
            parameters.Add("InputToken", inputToken);
            parameters.Add("DestinationToken", destinationToken);
            parameters.Add("CropWidthPixels", width);
            parameters.Add("CropHeightPixels", height);
            parameters.Add("EllipticalCrop", false);
            parameters.Add("ShowCamera", false);

            // Perform LaunchUriForResultsAsync
            return await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), options, parameters);

            // See also: 
            // https://frayxrulez.wordpress.com/tag/microsoft-windows-photos-crop/ 
            // https://gist.github.com/c2f1bbfa996ad5751b87 
            // https://myignite.microsoft.com/videos/2571
        }
コード例 #6
0
        private async Task SendResultAsync(JsonObject result)
        {
            ValueSet val = new ValueSet();

            try
            {
                if (result.ContainsKey("imagePath"))
                {
                    var imagePath = result["imagePath"].GetString();
                    var imageFile = await StorageFile.GetFileFromPathAsync(imagePath);

                    result.Add("imagePathToken", JsonValue.CreateStringValue(SharedStorageAccessManager.AddFile(imageFile)));
                }

                if (result.ContainsKey("fullImagePath"))
                {
                    var imagePath = result["fullImagePath"].GetString();
                    var imageFile = await StorageFile.GetFileFromPathAsync(imagePath);

                    result.Add("fullImagePathToken", JsonValue.CreateStringValue(SharedStorageAccessManager.AddFile(imageFile)));
                }
                val["result"] = result.ToString();
            }
            catch (Exception e)
            {
                val["exception"] = e.Message;
            }
            finally
            {
                _operation.ReportCompleted(val);
            }
        }
コード例 #7
0
        private async void LaunchApp()
        {
            var testAppUri = new Uri("weipo:"); // The protocol handled by the launched app
            var options    = new LauncherOptions {
                TargetApplicationPackageFamilyName = Package.Current.Id.FamilyName
            };

            var inputData = new ValueSet();
            var data      = _shareArguments.ShareOperation.Data;

            if (data.Contains(StandardDataFormats.Text))
            {
                var text = await data.GetTextAsync();

                inputData["text"] = text;
            }

            if (data.Contains(StandardDataFormats.Bitmap))
            {
                var bitmap = await data.GetBitmapAsync();

                var file = await bitmap.SaveCacheFile();

                inputData["image"] = SharedStorageAccessManager.AddFile(file);
            }

            await Launcher.LaunchUriAsync(testAppUri, options, inputData);

            _shareArguments.ShareOperation.ReportCompleted();
        }
コード例 #8
0
ファイル: ImageHelper.cs プロジェクト: AsteroidOS/WinSteroid
        public async static Task <StorageFile> CropImageFileAsync(StorageFile inputFile, int cropWidthPixels, int cropHeightPixels)
        {
            var outputFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("Cropped_" + inputFile.Name, CreationCollisionOption.ReplaceExisting);

            var inputToken       = SharedStorageAccessManager.AddFile(inputFile);
            var destinationToken = SharedStorageAccessManager.AddFile(outputFile);

            var inputData = new ValueSet
            {
                { "InputToken", inputToken },
                { "DestinationToken", destinationToken },
                { "CropWidthPixels", cropWidthPixels },
                { "CropHeightPixels", cropHeightPixels },
                { "EllipticalCrop", false }
            };

            var launcherOptions = new LauncherOptions
            {
                TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe"
            };

            var launcherResult = await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), launcherOptions, inputData);

            if (launcherResult.Status != LaunchUriStatus.Success)
            {
                return(null);
            }

            return(outputFile);
        }
コード例 #9
0
ファイル: ImageService.cs プロジェクト: Szing/UWP
        /// <summary>
        /// 获取经过截取后的图片流
        /// </summary>
        /// <returns>图片流</returns>
        public async Task <IRandomAccessStream> GetImageStream()
        {
            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();

                        return(stream);
                    }

                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message + ex.StackTrace);
                    }
                }
            }
            return(null);
        }
コード例 #10
0
        public async void OnPhotoToFile(StorageFile file)
        {
            JsonObject result = new JsonObject();

            result.Add("imagePathToken", JsonValue.CreateStringValue(SharedStorageAccessManager.AddFile(file)));

            await SendResultAsync(result);
        }
コード例 #11
0
 /// <summary>
 /// Gets the Transcoder extension description
 /// </summary>
 /// <param name="response"></param>
 private void GetDescription(ValueSet response)
 {
     response["DisplayName"]   = DisplayName;
     response["PublisherName"] = PublisherName;
     response["Version"]       = Version;
     response["Price"]         = Price;
     response["LogoFileToken"] = SharedStorageAccessManager.AddFile(this.LogoFile);
     response["SourceType"]    = this.SourceType;
 }
コード例 #12
0
        private async void AppServiceConnection_RequestReceived(
            AppServiceConnection sender,
            AppServiceRequestReceivedEventArgs args)
        {
            var deferral = args.GetDeferral();

            try
            {
                var request = args.Request;

                var token = request.Message["FileToken"] as string;

                var data = request.Message["Data"] as string;

                var jsonData = JsonObject.Parse(data);

                var framesPerSecond = jsonData["FramesPerSecond"].GetNumber();

                var secondsPerFrame = 1.0 / framesPerSecond;

                var delayTime = System.Convert.ToUInt16(secondsPerFrame * 1000);

                var file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token);

                var temporaryFolder = Windows.Storage.ApplicationData.Current.TemporaryFolder;
                var gifFile         = await temporaryFolder.CreateFileAsync(file.DisplayName + ".gif", Windows.Storage.CreationCollisionOption.ReplaceExisting);

                using (var stream = await file.OpenStreamForReadAsync())
                {
                    using (var archive = new ZipArchive(stream, ZipArchiveMode.Read))
                    {
                        var journalXmlEntry = archive.GetEntry("journal.xml");

                        using (var journalStream = journalXmlEntry.Open())
                        {
                            await EncodeImagesAsync(delayTime, gifFile, archive, journalStream);
                        }
                    }
                }

                var gifToken = SharedStorageAccessManager.AddFile(gifFile);

                var responseMessage = new ValueSet
                {
                    ["FileToken"] = gifToken
                };

                await request.SendResponseAsync(responseMessage);
            }
            finally
            {
                deferral.Complete();
            }
        }
コード例 #13
0
        // 将沙盒内的指定文件设置为可共享,并生成 token
        private async void btnSave_Click(object sender, RoutedEventArgs e)
        {
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(@"webabcdTest\sharedStorage.txt", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteTextAsync(file, "I am webabcd: " + DateTime.Now.ToString());

            _sharedToken = SharedStorageAccessManager.AddFile(file);

            lblMsg.Text += $"文件 {file.Path} 已经被设置为可共享,其 token 值为 {_sharedToken}";
            lblMsg.Text += Environment.NewLine;
        }
        public async Task LaunchExtensionAsync(AppExtension appExtension)
        {
            // Il y a 2 types de packages, le bon et le mauvais
            // le bon, il est bon alors que le mauvais il est mauvais.
            if (false == appExtension.Package.Status.VerifyIsOK())
            {
                return;
            }

            // création d'une connexion
            var connection = new AppServiceConnection
            {
                AppServiceName = "com.infinitesquare.UWPWhatsNewExtension",

                // ciblage de l'extension
                PackageFamilyName = appExtension.Package.Id.FamilyName
            };

            var cameraCaptureUI = new CameraCaptureUI {
                PhotoSettings = { CroppedAspectRatio = new Size(1, 1), Format = CameraCaptureUIPhotoFormat.Jpeg }
            };
            var file = await cameraCaptureUI.CaptureFileAsync(CameraCaptureUIMode.Photo);

            if (file == null)
            {
                return;
            }

            var token = SharedStorageAccessManager.AddFile(file);

            // ouverture de la connexion
            var result = await connection.OpenAsync();

            if (result != AppServiceConnectionStatus.Success)
            {
                return;
            }

            var inputs = new ValueSet {
                { "targetFileToken", token }
            };

            // send input and receive output in a variable
            var response = await connection.SendMessageAsync(inputs);

            var outputFileToken = response.Message["outputFileToken"].ToString();

            var outputFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(outputFileToken);

            var copied = await outputFile.CopyAsync(ApplicationData.Current.TemporaryFolder, outputFile.Name);

            OutputImage = new BitmapImage(new Uri(copied.Path));
        }
コード例 #15
0
        private static async Task CreateImageEffectAsync(AppServiceRequestReceivedEventArgs message, BackgroundTaskDeferral wholeTaskDeferral)
        {
            try
            {
                var messageDef = message.GetDeferral();
                try
                {
                    var targetFileToken = message.Request.Message["targetFileToken"].ToString();
                    var targetFile      = await SharedStorageAccessManager.RedeemTokenForFileAsync(targetFileToken);

                    var outputFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(Guid.NewGuid().ToString("N") + ".jpg");

                    var foregroundImage = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Paillete.png"));

                    //use the blureffect
                    using (var inputStream = await targetFile.OpenReadAsync())
                        using (var foregroundImageStream = await foregroundImage.OpenReadAsync())
                        {
                            var effect = new BlendEffect(new RandomAccessStreamImageSource(inputStream), new RandomAccessStreamImageSource(foregroundImageStream));
                            inputStream.Seek(0);
                            foregroundImageStream.Seek(0);
                            //effect.Source = new RandomAccessStreamImageSource(inputStream);
                            //effect.BlendFunction = BlendFunction.Add;
                            //effect.ForegroundSource = new RandomAccessStreamImageSource(foregroundImageStream);

                            using (var jpegRenderer = new JpegRenderer(effect))
                                using (var stream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
                                {
                                    // Jpeg renderer gives the raw buffer that contains the filtered image.
                                    IBuffer jpegBuffer = await jpegRenderer.RenderAsync();

                                    await stream.WriteAsync(jpegBuffer);

                                    await stream.FlushAsync();
                                }
                        }

                    var outputFileToken = SharedStorageAccessManager.AddFile(outputFile);
                    await message.Request.SendResponseAsync(new ValueSet { { "outputFileToken", outputFileToken } });
                }
                finally
                {
                    // fermeture du message
                    messageDef.Complete();
                }
            }
            finally
            {
                // On ne fera pas d'autres communications
                wholeTaskDeferral.Complete();
            }
        }
コード例 #16
0
        private async void OnLaunchForResults(object sender, RoutedEventArgs e)
        {
            // Insert the M3_LaunchForResults snippet here
            StorageFile imagefile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ViewModel.SelectedSightFile.Uri));

            // Copy to temp local storage - SharedStorageAccessmanager cannot get tokens for files that are in the app package folder
            StorageFile file = await imagefile.CopyAsync(ApplicationData.Current.TemporaryFolder, imagefile.Name, NameCollisionOption.GenerateUniqueName);

            if (file != null)
            {
                //Send data to the service
                var token = SharedStorageAccessManager.AddFile(file);

                var message = new ValueSet();

                //For QuickStart
                message.Add("Token", token);

                var targetAppUri = new Uri("lumiaphotoeditingquick:");

                // We want a specific app to perform our photo editing operation, not just any that implements the protocol we're using for launch
                var options = new LauncherOptions();
                options.TargetApplicationPackageFamilyName = "3ac26f24-3747-47ef-bfc5-b877b482f0f3_gd40dm16kn5w8";

                var response = await Launcher.LaunchUriForResultsAsync(targetAppUri, options, message);

                if (response.Status == LaunchUriStatus.Success)
                {
                    if (response.Result != null)
                    {
                        string alteredFileToken = response.Result["Token"].ToString();
                        var    alteredFile      = await SharedStorageAccessManager.RedeemTokenForFileAsync(alteredFileToken);

                        // get the destination where this file needs to go
                        var sightFile = await ViewModel.CreateSightFileAndAssociatedStorageFileAsync();

                        // Get the destination StorageFile
                        var destFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(sightFile.Uri));

                        // save the edited image file at the required destination
                        await alteredFile.CopyAndReplaceAsync(destFile);

                        sightFile.FileType = SightFileType.ImageGallery;

                        await ViewModel.SaveSightFileAsync(sightFile);
                    }
                }
            }
        }
コード例 #17
0
        async private void OnAppServiceShareFile(object sender, RoutedEventArgs e)
        {
            _name_count++;
            //create or replace the file
            var folder = ApplicationData.Current.LocalFolder;
            var file   = await folder.CreateFileAsync("customer.xml", CreationCollisionOption.ReplaceExisting);

            //write the message
            var xml = $"<customer><name>john_{_name_count}</name>"
                      + @"<dob>10/19/1990</dob>
                <email>[email protected]</email>
            </customer>";
            await file.AppendTextAsync(xml);

            //share the file
            var token = SharedStorageAccessManager.AddFile(file);

            AppServiceConnection connection = new AppServiceConnection();

            connection.AppServiceName    = "bmx-service";
            connection.PackageFamilyName = "748f8ea9-5de1-48be-a132-323bdc3c5fcc_hxmhn7vrhn3vp";

            AppServiceConnectionStatus status = await connection.OpenAsync();

            if (status == AppServiceConnectionStatus.Success)
            {
                //Send data to the service 
                var message = new ValueSet();
                message.Add("command", "customer-file-share");
                message.Add("token", token);

                //Send message and wait for response 
                AppServiceResponse response = await connection.SendMessageAsync(message);

                if (response.Status == AppServiceResponseStatus.Success)
                {
                    await new MessageDialog("Sent").ShowAsync();
                }
                else
                {
                    await new MessageDialog("Failed when sending message to app").ShowAsync();
                }
            }
            else
            {
                await new MessageDialog(status.ToString()).ShowAsync();
            }
            connection.Dispose();
        }
コード例 #18
0
        private async void OnOpenAnotherAppWithFileClicked(object sender, RoutedEventArgs e)
        {
            StorageFile textfile = await Package.Current.InstalledLocation.GetFileAsync("textfile.txt");

            string token = SharedStorageAccessManager.AddFile(textfile);

            ValueSet data = new ValueSet();

            data.Add("token", token);

            LauncherOptions options = new LauncherOptions();

            options.TargetApplicationPackageFamilyName = "a29b22b7-2ea6-424d-8c3b-4f6112d9caef_e8f4dqfvn1be6";

            await Launcher.LaunchUriAsync(new Uri("textfile:"), options, data);
        }
コード例 #19
0
        private async void button_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");

            StorageFile file = await openPicker.PickSingleFileAsync();

            if (file != null)
            {
                //Send data to the service
                var token = SharedStorageAccessManager.AddFile(file);

                var message = new ValueSet();
                message.Add("Token", token);

                //var targetAppUri = new Uri("lumiaphotoediting:");
                var targetAppUri = new Uri("lumiaphotoeditingquick:");

                // We want a specific app to perform our photo editing operation, not just any that implements the protocol we're using for launch
                var options = new LauncherOptions();
                //options.TargetApplicationPackageFamilyName = "704d7940-cd63-48d5-a0dd-45b6171c41c8_tkv88av2beah0";
                options.TargetApplicationPackageFamilyName = "3ac26f24-3747-47ef-bfc5-b877b482f0f3_gd40dm16kn5w8";

                var response = await Launcher.LaunchUriForResultsAsync(targetAppUri, options, message);

                if (response.Status == LaunchUriStatus.Success)
                {
                    if (response.Result != null)
                    {
                        string alteredFileToken = response.Result["Token"].ToString();
                        var    alteredFile      = await SharedStorageAccessManager.RedeemTokenForFileAsync(alteredFileToken);

                        await new MessageDialog("Altered file: " + alteredFile.Path).ShowAsync();
                    }
                    else
                    {
                        await new MessageDialog("Launch success, but no data returned ").ShowAsync();
                    }
                }
            }
        }
コード例 #20
0
        async void Doit()
        {
            string uriString = "demoking102040:key=value123";
            var    opt       = new LauncherOptions();

            // PFN
            opt.TargetApplicationPackageFamilyName = "5082b433-03c4-4db0-abf6-d2d63493f851_e7qah2kqbxs60";


            //token
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///images/bild.jpg"));

            string tok = SharedStorageAccessManager.AddFile(file);

            uriString = uriString += "&file=" + tok;

            await Launcher.LaunchUriAsync(new Uri(uriString), opt);
        }
コード例 #21
0
        private async void OnReturnImageToCaller()
        {
            // check whether or not this was a for results call
            if (_protocolOperation != null)
            {
                ValueSet result = new ValueSet();

                // TODO 2: save file to a local file, and send token back to caller
                var destFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("EditedOutput.jpg", CreationCollisionOption.GenerateUniqueName);
                await SaveImageAsync(destFile);

                result["Success"] = true;
                result["Reason"]  = "Completed";
                result["Token"]   = SharedStorageAccessManager.AddFile(destFile);

                _protocolOperation.ReportCompleted(result);
            }
        }
コード例 #22
0
ファイル: Page1.xaml.cs プロジェクト: tyuchn/PhotoShop-UWP
        /*private void Button_Click_Draw(object sender, RoutedEventArgs e)
         * {
         *  Frame.Navigate(typeof(draw));
         * }
         */
        private async void CutPicture(StorageFile file)
        {
            #region 裁剪图片
            var inputFile   = SharedStorageAccessManager.AddFile(file);                                                                          //  获取一个文件共享Token,使应用程序能够与另一个应用程序共享指定的文件。
            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"; //应用于启动文件或URI的目标包的包名称
                                                                                                   //待会要传入的参数
            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);
            var result = await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), options, parameters);

            if (result.Status == LaunchUriStatus.Success && result.Result != null)
            {
                //对裁剪后图像的下一步处理
                try
                {
                    //载入已保存的裁剪后图片
                    var stream = await destination.OpenReadAsync();

                    var bitmap = new BitmapImage();
                    await bitmap.SetSourceAsync(stream);

                    // 显示裁剪过后的图片
                    Img.Source = bitmap;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message + ex.StackTrace);
                }
            }


            #endregion
        }
コード例 #23
0
        async private void OnShareFile(object sender, RoutedEventArgs e)
        {
            //create or replace the file
            var folder = ApplicationData.Current.LocalFolder;
            var file   = await folder.CreateFileAsync("customer.xml", CreationCollisionOption.ReplaceExisting);

            //write the message
            var xml = @"<customer>
                    <name>john</name>
                        <dob>10/19/1990</dob>
                        <email>[email protected]</email>
                    </customer>";
            await file.AppendTextAsync(xml);

            //share the file
            var token = SharedStorageAccessManager.AddFile(file);

            txt_token.Text = token;
        }
コード例 #24
0
        private async void OnLaunchUriSharedStorageToken(object sender, RoutedEventArgs e)
        {
            try
            {
                string          targetUri         = @"for-results2:";
                string          launcherTargetPfn = @"LaunchUriTargetMultiApp_8wekyb3d8bbwe";
                Uri             uri     = new Uri(targetUri, UriKind.Absolute);
                LauncherOptions options = new LauncherOptions();
                options.TargetApplicationPackageFamilyName = launcherTargetPfn;
                ValueSet data = new ValueSet();
                // Get UTC filetime and reduce resolution from 100ns to 10ms, expecting target to receive data within 10ms
                long timeSuffix = DateTime.Now.ToFileTimeUtc();
                timeSuffix = (timeSuffix / 10000000000L);
                data.Add("Data", "Hello Target App_" + timeSuffix);

                string      imageFile   = @"\Assets\Launchers\technicaldebts.jpg";
                string      installPath = Package.Current.InstalledLocation.Path;
                StorageFile file        = await StorageFile.GetFileFromPathAsync(installPath + imageFile);

                string filetoken = SharedStorageAccessManager.AddFile(file);
                data.Add("SSAM Token", filetoken);

                bool success = await Launcher.LaunchUriAsync(uri, options, data);

                if (success)
                {
                    status.Log(string.Format(CultureInfo.CurrentCulture,
                                             LocalizableStrings.LAUNCHERS_APP_LAUNCH_SUCCESS, file.Name));
                }
                else
                {
                    status.Log(string.Format(CultureInfo.CurrentCulture,
                                             LocalizableStrings.LAUNCHERS_APP_LAUNCH_FAIL, file.Name));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("LaunchersPage.OnLaunchUriSharedStorageToken: " + ex.ToString());
                status.Log(ex.Message);
            }
        }
コード例 #25
0
        private async Task <LaunchUriResult> CropImageAsync(IStorageFile input, IStorageFile destination, int width, int height)
        {
            // Get access tokens to pass input and output files between apps
            var inputToken       = SharedStorageAccessManager.AddFile(input);
            var destinationToken = SharedStorageAccessManager.AddFile(destination);

            // Specify an app to launch by using LaunchUriForResultsAsync
            var options = new LauncherOptions();

            options.TargetApplicationPackageFamilyName = "Microsoft.Windows.Photos_8wekyb3d8bbwe";

            // Specify protocol launch options
            var parameters = new ValueSet();

            parameters.Add("InputToken", inputToken);
            parameters.Add("DestinationToken", destinationToken);
            parameters.Add("CropWidthPixels", 500);
            parameters.Add("CropHeightPixels", 500);
            parameters.Add("EllipticalCrop", false);

            // Perform LaunchUriForResultsAsync
            return(await Launcher.LaunchUriForResultsAsync(new Uri("microsoft.windows.photos.crop:"), options, parameters));
        }
コード例 #26
0
ファイル: Startup.cs プロジェクト: tc21/ComicsViewer
        public static async Task OpenComicSubitemAsync(ComicSubitem subitem, UserProfile profile)
        {
            switch (profile.StartupApplicationType)
            {
            case StartupApplicationType.OpenFirstFile:
                // The if statement checks that the return value is not null
                var file = await StorageFile.GetFileFromPathAsync(subitem.Files.First());

                _ = await Launcher.LaunchFileAsync(file);

                return;

            case StartupApplicationType.OpenContainingFolder:
                _ = await Launcher.LaunchFolderPathAsync(subitem.RootPath);

                return;

            case StartupApplicationType.BuiltinViewer:
                var files    = subitem.Files.ToList();
                var testFile = files[0];

                if (FileTypes.IsImage(testFile))
                {
                    // apparently if we transfer too much information in memory we cause an error. (The size of ValueSet is capped at ~100kb).
                    if (files.Count > 250)
                    {
                        var tempFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("comics_file_list.txt", CreationCollisionOption.ReplaceExisting);

                        await FileIO.WriteLinesAsync(tempFile, files);

                        var fileToken = SharedStorageAccessManager.AddFile(tempFile);

                        await LaunchBuiltInViewerWithFileTokenAsync("d4f1d4fc-69b2-4240-9627-b2ff603e62e8_jh3a8zm8ky434", "comics-imageviewer:///shared_filelist", fileToken);
                    }
                    else
                    {
                        await LaunchBuiltinViewerWithFilenamesAsync("d4f1d4fc-69b2-4240-9627-b2ff603e62e8_jh3a8zm8ky434", "comics-imageviewer:///filenames", files);
                    }

                    return;
                }

                if (FileTypes.IsMusic(testFile))
                {
                    var description = "";
                    var comicFolder = await StorageFolder.GetFolderFromPathAsync(subitem.Comic.Path);

                    foreach (var descriptionSpecification in profile.ExternalDescriptions)
                    {
                        if (await descriptionSpecification.FetchFromFolderAsync(comicFolder) is not {
                        } desc)
                        {
                            continue;
                        }

                        description += desc.Content;
                        description += "\n";
                    }

                    await LaunchBuiltinViewerWithFilenamesAsync("e0dd0f61-b687-4419-81a3-3369df63b72f_jh3a8zm8ky434", "comics-musicplayer:///filenames", files, description);

                    return;
                }

                await ComicExpectedExceptions.IntendedBehaviorAsync(
                    title : "Cannot open item",
                    message : "The application could not open this item in a built-in viewer, " +
                    $"because it doesn't recognize its extension: '{Path.GetExtension(testFile)}'.",
                    cancelled : false
                    );

                return;

            default:
                throw new ProgrammerError($"{nameof(OpenComicSubitemAsync)}: unhandled switch case");
            }
コード例 #27
0
ファイル: newpage.xaml.cs プロジェクト: CHENwz/Todos
        private async void Select(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);

                //储存选择的图片以便重载的时候加载出来
                StorageFile File = await picker.PickSingleFileAsync();

                if (file != null)
                {
                    ApplicationData.Current.LocalSettings.Values["TempImage"] = StorageApplicationPermissions.FutureAccessList.Add(file);
                    using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
                    {
                        var srcImage = new BitmapImage();
                        await srcImage.SetSourceAsync(stream);

                        image.Source = srcImage;
                    }
                }
                //按理说下面这个判断应该没问题呀,但是如果裁剪界面点了取消的话后面会出现异常,所以后面我加了try catch
                if (result.Status == LaunchUriStatus.Success && result.Result != null)
                {
                    //对裁剪后图像的下一步处理
                    try
                    {
                        // 载入已保存的裁剪后图片
                        var stream = await destination.OpenReadAsync();

                        var bitmap = new BitmapImage();
                        await bitmap.SetSourceAsync(stream);

                        // 显示
                        image.Source = bitmap;
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message + ex.StackTrace);
                    }
                }
            }
        }
コード例 #28
0
        //private void element_PointerExited(object sender, PointerRoutedEventArgs e)
        //{
        //    // Scale back down to 1.0
        //    CreateOrUpdateSpringAnimation(1.0f);

        //    (sender as UIElement).StartAnimation(_springAnimation);
        //}


        private async void MyPersonPicture_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var            srcImage   = new BitmapImage();
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.Thumbnail;
            openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            openPicker.FileTypeFilter.Add(".jpg");
            openPicker.FileTypeFilter.Add(".jpeg");
            openPicker.FileTypeFilter.Add(".png");
            StorageFile file = await openPicker.PickSingleFileAsync();

            Picture_file = file;
            if (file != null)
            {
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    await srcImage.SetSourceAsync(stream);

                    await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
                }
            }
            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);

                if (result.Status.Equals(LaunchUriStatus.Success) && result.Result != null)
                {
                    try
                    {
                        var stream = await destination.OpenReadAsync();

                        var bitmap = new BitmapImage();
                        using (var dataRender = new DataReader(stream))
                        {
                            if (stream.Size == 0)
                            {
                                return;
                            }
                            var imgBytes = new byte[stream.Size];
                            await dataRender.LoadAsync((uint)stream.Size);

                            dataRender.ReadBytes(imgBytes);
                            List <PersonPictures> datalist = conn.Query <PersonPictures>("select * from PersonPictures where pictureName = ?", "picture");
                            if (datalist != null)
                            {
                                conn.Execute("delete from PersonPictures where pictureName = ?", "picture");
                            }
                            conn.Insert(new PersonPictures()
                            {
                                pictureName = "picture", picture = imgBytes
                            });
                            SetPersonPicture();
                        }
                        await localFolder.CreateFileAsync("PersonPicture", CreationCollisionOption.ReplaceExisting);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message + ex.StackTrace);
                    }
                }
            }
        }