Пример #1
0
        /// <summary>
        /// Prepare for transcoding
        /// </summary>
        /// <param name="message">the transcode parameters</param>
        /// <param name="jsonValue">a JsonValue containing the token</param>
        /// <returns>an async task with a JsonValue</returns>
        private async Task PrepareTranscodeAsync(ValueSet message, JsonObject fileTokens)
        {
            var sourceToken      = fileTokens["SourceToken"].GetString();
            var destinationToken = fileTokens["DestinationToken"].GetString();

            var sourceFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(sourceToken);

            if (_canceled)
            {
                throw new TaskCanceledException();
            }

            var destinationFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(destinationToken);

            this._action = TranscodeAsync(sourceFile, destinationFile, message);

            await this._action;

            if (_canceled)
            {
                throw new TaskCanceledException();
            }

            this._action = null;
        }
        async private void LoadToken(object sender, RoutedEventArgs e)
        {
            var token = txt_token.Text;
            var file  = await SharedStorageAccessManager.RedeemTokenForFileAsync(token);

            if (file != null)
            {
                //initialize customer
                _customer = new BMXCustomerInfo
                {
                    CustomerID = Guid.NewGuid(),
                };

                //load xml
                var xml_text = await file.ReadTextAsync();

                var xml = XElement.Parse(xml_text);

                //red xml into local values
                var customer_name  = xml.Element("name").Value;
                var customer_email = xml.Element("email").Value;
                var customer_dob   = xml.Element("dob").Value;
                var dob            = DateTime.Parse(customer_dob);

                //set values of controls
                txt_name.Text    = customer_name;
                txt_email.Text   = customer_email;
                control_dob.Date = dob;

                //hide overlay
                grid_overlay.Visibility = Visibility.Collapsed;
            }
        }
Пример #3
0
 private async void parseData(string fileToken)
 {
     try
     {
         StorageFolder localFolder = ApplicationData.Current.LocalFolder;
         if (!FileUtil.dirExists("wechat_sdk"))
         {
             FileUtil.createDir("wechat_sdk");
         }
         await(await SharedStorageAccessManager.RedeemTokenForFileAsync(fileToken)).CopyAsync(localFolder, "wechat_sdk\\wp.wechat", NameCollisionOption.ReplaceExisting);
         //await SharedStorageAccessManager.CopySharedFileAsync(localFolder, "wechat_sdk\\wp.wechat", 1, fileToken);
         if (FileUtil.fileExists("wechat_sdk\\wp.wechat"))
         {
             TransactData transactData = TransactData.ReadFromFile("wechat_sdk\\wp.wechat");
             if (!transactData.ValidateData(true))
             {
                 await new Windows.UI.Popups.MessageDialog("数据验证失败").ShowAsync();
             }
             else if (!transactData.CheckSupported())
             {
                 await new Windows.UI.Popups.MessageDialog("当前版本不支持该请求").ShowAsync();
             }
             else if (transactData.Req != null)
             {
                 if (transactData.Req.Type() == 3)
                 {
                     this.On_GetMessageFromWX_Request(transactData.Req as GetMessageFromWX.Req);
                 }
                 else if (transactData.Req.Type() == 4)
                 {
                     this.On_ShowMessageFromWX_Request(transactData.Req as ShowMessageFromWX.Req);
                 }
             }
             else if (transactData.Resp != null)
             {
                 if (transactData.Resp.Type() == 2)
                 {
                     this.On_SendMessageToWX_Response(transactData.Resp as SendMessageToWX.Resp);
                 }
                 else if (transactData.Resp.Type() == 1)
                 {
                     this.On_SendAuth_Response(transactData.Resp as SendAuth.Resp);
                 }
                 else if (transactData.Resp.Type() == 5)
                 {
                     this.On_SendPay_Response(transactData.Resp as SendPay.Resp);
                 }
             }
         }
     }
     catch
     {
         await new Windows.UI.Popups.MessageDialog("未知错误").ShowAsync();
     }
 }
        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();
            }
        }
        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));
        }
Пример #6
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();
            }
        }
Пример #7
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.Parameter != null)
            {
                var         args  = e.Parameter as ProtocolActivatedEventArgs;
                string      token = args.Data["token"].ToString();
                StorageFile file  = await SharedStorageAccessManager.RedeemTokenForFileAsync(token);

                string text = await FileIO.ReadTextAsync(file);

                FileText.Text = text;
            }
        }
Пример #8
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);
                    }
                }
            }
        }
Пример #9
0
        // 根据 token 获取文件
        // 为了演示方便,本例就在同一个 app 中演示了,实际上在其他 app 中也是可以根据此 token 获取文件的
        private async void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StorageFile file = await SharedStorageAccessManager.RedeemTokenForFileAsync(_sharedToken);

                string textContent = await FileIO.ReadTextAsync(file);

                lblMsg.Text += $"token 值为 {_sharedToken} 的文件的内容为: {textContent}";
                lblMsg.Text += Environment.NewLine;
            }
            catch (Exception ex)
            {
                lblMsg.Text += ex.ToString();
                lblMsg.Text += Environment.NewLine;
            }
        }
Пример #10
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();
                    }
                }
            }
        }
Пример #11
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var protocolArgs = e.Parameter as ProtocolActivatedEventArgs;

            if (protocolArgs.Uri.Query != "")
            {
                var    queryStrings = new WwwFormUrlDecoder(protocolArgs.Uri.Query);
                string gpxFileToken = queryStrings.GetFirstValueByName("GpxFile");
                if (!string.IsNullOrEmpty(gpxFileToken))
                {
                    StorageFile fileget = await SharedStorageAccessManager.RedeemTokenForFileAsync(gpxFileToken);

                    BitmapImage bitmapimage = new BitmapImage();
                    bitmapimage.SetSource(await fileget.OpenReadAsync());
                    imgAppdeliver.Source = bitmapimage;
                }
            }
        }
Пример #12
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            protocolForResultsArgs = e.Parameter as ProtocolForResultsActivatedEventArgs;

            if (protocolForResultsArgs != null)
            {
                PickImageButton.Visibility = Visibility.Collapsed;

                // In the data there should be a file token
                if (protocolForResultsArgs.Data.Keys.Count == 1 &&
                    protocolForResultsArgs.Data.ContainsKey("Token"))
                {
                    string fileToken = protocolForResultsArgs.Data["Token"] as string;


                    // Get the file for the token
                    protocolForResultsImageFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(fileToken);

                    if (protocolForResultsImageFile.ContentType.Contains("image"))
                    {
                        while (m_renderer == null)
                        {
                            await Task.Delay(200);
                        }


                        await ApplyEffectAsync(protocolForResultsImageFile);

                        SaveButton.IsEnabled = true;
                        return;
                    }
                }

                // When we can't handle the  Protocol For Results operation, just end the operation
                var operation = protocolForResultsArgs.ProtocolForResultsOperation;

                var result = new ValueSet();
                result["Success"] = false;
                result["Reason"]  = "Invalid payload";

                operation.ReportCompleted(result);
            }
        }
        public async Task LoadForProtocolActivationAsync(ProtocolForResultsActivatedEventArgs protocolForResultsArgs)
        {
            _protocolOperation = protocolForResultsArgs.ProtocolForResultsOperation;

            // In the data there should be a file token
            if (protocolForResultsArgs.Data.ContainsKey("Photo"))
            {
                string dataFromCaller  = protocolForResultsArgs.Data["Photo"] as string;
                string tokenFromCaller = protocolForResultsArgs.Data["DestinationToken"] as string;

                if (!string.IsNullOrEmpty(tokenFromCaller))

                {
                    // Get the file for the token
                    StorageFile imageFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(tokenFromCaller);

                    if (imageFile.ContentType.Contains("image"))
                    {
                        // Try copying to local storage
                        // var copy = await imageFile.CopyAsync(ApplicationData.Current.LocalFolder, imageFile.Name, NameCollisionOption.ReplaceExisting);

                        // Wait until renderer has loaded
                        while (m_renderer == null)
                        {
                            await Task.Delay(200);
                        }

                        await LoadPhotoAsync(imageFile);

                        return;
                    }
                }
            }

            // When we can't handle the  Protocol For Results operation, just end the operation
            var result = new ValueSet();

            result["Success"] = false;
            result["Reason"]  = "Invalid payload";

            _protocolOperation.ReportCompleted(result);
        }
        private void HandleBMXServiceRequests(AppServiceTriggerDetails details)
        {
            var retval = new ValueSet();

            details.AppServiceConnection.RequestReceived += async(sender, args) =>
            {
                var message = args.Request.Message;
                var command = message["command"] as string;
                if (command == "customer-file-share")
                {
                    var token = message["token"] as string;
                    var file  = await SharedStorageAccessManager.RedeemTokenForFileAsync(token);

                    if (file != null)
                    {
                        var xml_text = await file.ReadTextAsync();

                        var xml = XElement.Parse(xml_text);

                        var customer = new BMXCustomerInfo
                        {
                            CustomerID   = Guid.NewGuid(),
                            CustomerName = xml.Element("name").Value,
                            Email        = xml.Element("email").Value,
                            DOB          = DateTime.Parse(xml.Element("dob").Value)
                        };

                        State.Customers.Add(customer);
                        await State.SaveAsync();

                        retval.Add("result", "File was copied");
                    }
                    else
                    {
                        retval.Add("result", "Could not retrieve file");
                    }
                    await args.Request.SendResponseAsync(retval);
                }
                _deferral.Complete();
            };
        }
Пример #15
0
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            var protocolForResultsArgs = e.Parameter as ProtocolForResultsActivatedEventArgs;

            this.operation   = protocolForResultsArgs.ProtocolForResultsOperation;
            productName      = protocolForResultsArgs.Data["ProductName"] as string;
            this.Item.Text   = productName;
            this.Amount.Text = "$" + protocolForResultsArgs.Data["Amount"] as string;

            if (protocolForResultsArgs.Data.ContainsKey("ImageFileToken"))
            {
                string imageFileToken = protocolForResultsArgs.Data["ImageFileToken"] as string;

                StorageFile imageFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(imageFileToken);

                BitmapImage bitmap = new BitmapImage();
                bitmap.SetSource(await imageFile.OpenReadAsync());
                ProductImage.Source = bitmap;
                ProductImage.Height = 200;
            }
        }
Пример #16
0
        protected override void OnCreate(object parameter)
        {
            base.OnCreate(parameter);
            Singleton <BroadcastCenter> .Instance.SubscribeWithPendingMessage("share_target_receive", async (sender, args) =>
            {
                if (args is ProtocolActivatedEventArgs protocolActivatedEventArgs)
                {
                    if (protocolActivatedEventArgs.Data.ContainsKey("image"))
                    {
                        var file = await SharedStorageAccessManager.RedeemTokenForFileAsync(
                            protocolActivatedEventArgs.Data["image"].ToString());
                        Singleton <BroadcastCenter> .Instance.Send(this, "share_add_image", file);
                    }

                    if (protocolActivatedEventArgs.Data.ContainsKey("text"))
                    {
                        var text = protocolActivatedEventArgs.Data["text"].ToString();
                        Singleton <BroadcastCenter> .Instance.Send(this, "share_add_text", text);
                    }
                }
            });
        }
Пример #17
0
        async void OnClick(object sender, RoutedEventArgs e)
        {
            AppServiceConnection connection = new AppServiceConnection();

            connection.PackageFamilyName = this.txtPackageName.Text;
            connection.AppServiceName    = this.txtServiceName.Text;

            var status = await connection.OpenAsync();

            if (status == AppServiceConnectionStatus.Success)
            {
                ValueSet parameters = new ValueSet();
                parameters["query"] = this.txtQuery.Text;

                var response = await connection.SendMessageAsync(parameters);

                if (response.Status == AppServiceResponseStatus.Success)
                {
                    var token = response.Message["pictureToken"] as string;

                    if (!string.IsNullOrEmpty(token))
                    {
                        var file = await SharedStorageAccessManager.RedeemTokenForFileAsync((string)token);

                        BitmapImage bitmap = new BitmapImage();

                        using (var fileStream = await file.OpenReadAsync())
                        {
                            await bitmap.SetSourceAsync(fileStream);
                        }
                        this.image.Source = bitmap;
                    }
                }
                connection.Dispose();
            }
        }
Пример #18
0
        private async void BtnScan_Click(object sender, RoutedEventArgs e)
        {
            JsonObject inputJson = null;
            JsonObject result    = null;

            // send in the corresponding JSON config
            if ((bool)RBMeterScan.IsChecked)
            {
                inputJson = await GetJsonObjectFromConfigFileName("Config/meterConfig.json");
            }
            else if ((bool)RBSerialNumberScan.IsChecked)
            {
                inputJson = await GetJsonObjectFromConfigFileName("Config/serialNumberConfig.json");
            }
            else if ((bool)RBBarcode.IsChecked)
            {
                inputJson = await GetJsonObjectFromConfigFileName("Config/barcodeConfig.json");
            }
            else if ((bool)RBPhoto.IsChecked)
            {
                inputJson = await GetJsonObjectFromConfigFileName("Config/photoConfig.json");
            }
            else if ((bool)RBPhotoFar.IsChecked)
            {
                inputJson = await GetJsonObjectFromConfigFileName("Config/photoConfigFar.json");
            }
            else if ((bool)RBPhoto1024.IsChecked)
            {
                inputJson = await GetJsonObjectFromConfigFileName("Config/photoConfig1024.json");
            }
            else
            {
                throw new InvalidOperationException("Usecase not supported.");
            }

            result = await LaunchAppForResults(inputJson);


            // retrieve the result as JSON in string format & fill ListView with result
            if (result != null)
            {
                var item = new ListViewItem
                {
                    HorizontalAlignment = HorizontalAlignment.Stretch
                };

                var grid = new Grid
                {
                    Margin = new Thickness(5)
                };
                grid.ColumnDefinitions.Add(new ColumnDefinition());
                grid.ColumnDefinitions.Add(new ColumnDefinition());
                grid.ColumnDefinitions.Add(new ColumnDefinition());
                grid.ColumnDefinitions.Add(new ColumnDefinition());

                if (result.ContainsKey("result"))
                {
                    var resultTextBlock = new TextBlock
                    {
                        Text   = result.GetNamedString("result"),
                        Margin = new Thickness(10)
                    };
                    grid.Children.Add(resultTextBlock);
                    Grid.SetColumn(resultTextBlock, 0);
                }
                if (result.ContainsKey("imagePathToken"))
                {
                    BitmapImage bitmapImage = new BitmapImage();

                    // sharing file across 2 apps
                    var tokenFile = await SharedStorageAccessManager.RedeemTokenForFileAsync(result["imagePathToken"].GetString());

                    using (var stream = (await tokenFile.OpenStreamForReadAsync()).AsRandomAccessStream())
                    {
                        bitmapImage.SetSource(stream);
                    }
                    var resultImage = new Image
                    {
                        Source = bitmapImage,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment   = VerticalAlignment.Center,
                        MaxHeight           = 150
                    };
                    grid.Children.Add(resultImage);
                    Grid.SetColumn(resultImage, 1);
                }

                var infoBlock = new TextBlock
                {
                    Margin = new Thickness(10)
                };
                infoBlock.Text = "";
                if (result.ContainsKey("scanMode"))
                {
                    infoBlock.Text = result.GetNamedString("scanMode");
                }
                if (result.ContainsKey("barcodeFormat"))
                {
                    infoBlock.Text = result.GetNamedString("barcodeFormat");
                }

                grid.Children.Add(infoBlock);
                Grid.SetColumn(infoBlock, 2);

                var removeButton = new Button
                {
                    Content           = "X",
                    Margin            = new Thickness(15),
                    VerticalAlignment = VerticalAlignment.Top
                };
                removeButton.Click += (s, args) => {
                    ResultListView.Items.Remove(item);
                };
                grid.Children.Add(removeButton);
                Grid.SetColumn(removeButton, 3);

                item.Content = grid;

                ResultListView.Items.Add(item);
            }
        }
Пример #19
0
        private static async Task <ProtocolActivatedArguments> ParseActivationArgumentsWithoutDescription(ProtocolActivatedEventArgs args)
        {
            if (args.Uri.AbsolutePath == "/path")
            {
                if (!(args.Data.TryGetValue("Path", out var o) && o is string path))
                {
                    return(new ProtocolErrorActivatedArguments(ProtocolActivatedErrorReason.InvalidArguments, "Required argument 'Path' not found."));
                }

                try {
                    var folder = await StorageFolder.GetFolderFromPathAsync(path);

                    return(new ProtocolFoldersActivatedArguments(new[] { folder }));
                } catch (UnauthorizedAccessException) {
                    return(new ProtocolErrorActivatedArguments(
                               ProtocolActivatedErrorReason.AccessDenied,
                               "Please ensure file system access for this app is turned on in Settings."));
                } catch (FileNotFoundException) {
                    return(new ProtocolErrorActivatedArguments(ProtocolActivatedErrorReason.FilesNotFound, $"The directory doesn't exist: {path}"));
                }
            }

            if (args.Uri.AbsolutePath == "/file")
            {
                throw new NotImplementedException();
            }

            if (args.Uri.AbsolutePath == "/filenames")
            {
                if (!(args.Data.TryGetValue("Filenames", out var o2) && o2 is string[] filenames))
                {
                    return(new ProtocolErrorActivatedArguments(ProtocolActivatedErrorReason.InvalidArguments, "Required argument 'Filenames' not found."));
                }

                return(new ProtocolFilenamesActivatedArguments(filenames));
            }

            if (args.Uri.AbsolutePath == "/shared_filelist")
            {
                if (!(args.Data.TryGetValue("FileToken", out var o) && o is string token))
                {
                    return(new ProtocolErrorActivatedArguments(ProtocolActivatedErrorReason.InvalidArguments, "Required argument 'FileToken' not found."));
                }

                StorageFile file;

                try {
                    file = await SharedStorageAccessManager.RedeemTokenForFileAsync(token);
                } catch {
                    return(new ProtocolErrorActivatedArguments(
                               ProtocolActivatedErrorReason.InvalidArguments,
                               $"Could not retrieve file corresponding to file token '{token}'."));
                }

                var lines = await FileIO.ReadLinesAsync(file);

                // the temp file is no longer needed
                await file.DeleteAsync();

                return(new ProtocolFilenamesActivatedArguments(lines));
            }

            return(new ProtocolErrorActivatedArguments(ProtocolActivatedErrorReason.InvalidUri, args.Uri.AbsolutePath));
        }