コード例 #1
0
ファイル: SaveFileAction.cs プロジェクト: WaffleSquirrel/More
        private void SaveFile( SaveFileInteraction saveFile )
        {
            Contract.Requires( saveFile != null );

            var dialog = new FileSavePicker();

            dialog.ContinuationData.AddRange( saveFile.ContinuationData );
            dialog.DefaultFileExtension = saveFile.DefaultFileExtension;
            dialog.FileTypeChoices.AddRange( saveFile.FileTypeChoices.ToDictionary() );
            dialog.SuggestedStartLocation = SuggestedStartLocation;

            if ( !string.IsNullOrEmpty( saveFile.FileName ) )
                dialog.SuggestedFileName = saveFile.FileName;

            if ( !string.IsNullOrEmpty( SettingsIdentifier ) )
                dialog.SettingsIdentifier = SettingsIdentifier;

            dialog.PickSaveFileAndContinue();
        }
コード例 #2
0
ファイル: SaveFileAction.cs プロジェクト: WaffleSquirrel/More
        private IAsyncOperation<StorageFile> SaveFileAsync( SaveFileInteraction saveFile )
        {
            Contract.Requires( saveFile != null );
            Contract.Ensures( Contract.Result<IAsyncOperation<StorageFile>>() != null );

            var dialog = new FileSavePicker();

            dialog.DefaultFileExtension = saveFile.DefaultFileExtension;
            dialog.FileTypeChoices.AddRange( saveFile.FileTypeChoices.ToDictionary() );
            dialog.SuggestedStartLocation = SuggestedStartLocation;

            if ( !string.IsNullOrEmpty( saveFile.FileName ) )
                dialog.SuggestedFileName = saveFile.FileName;

            if ( !string.IsNullOrEmpty( SettingsIdentifier ) )
                dialog.SettingsIdentifier = SettingsIdentifier;

            return dialog.PickSaveFileAsync();
        }
コード例 #3
0
        private void Load()
        {
            SampleController.Current.RegisterNewCommand("Export & Save", async(sender, args) =>
            {
                if (_infiniteCanvas != null)
                {
                    var savePicker = new FileSavePicker
                    {
                        SuggestedStartLocation = PickerLocationId.DocumentsLibrary
                    };
                    savePicker.FileTypeChoices.Add("application/json", new List <string> {
                        ".json"
                    });
                    savePicker.SuggestedFileName = "Infinite Canvas Export";

                    var file = await savePicker.PickSaveFileAsync();
                    if (file != null)
                    {
                        var json = _infiniteCanvas.ExportAsJson();
                        CachedFileManager.DeferUpdates(file);
                        await FileIO.WriteTextAsync(file, json);
                    }
                }
            });

            SampleController.Current.RegisterNewCommand("Import and Load", async(sender, args) =>
            {
                if (_infiniteCanvas != null)
                {
                    var picker = new FileOpenPicker
                    {
                        ViewMode = PickerViewMode.Thumbnail,
                        SuggestedStartLocation = PickerLocationId.DocumentsLibrary
                    };
                    picker.FileTypeFilter.Add(".json");
                    var file = await picker.PickSingleFileAsync();

                    if (file != null)
                    {
                        try
                        {
                            var json = await FileIO.ReadTextAsync(file);
                            _infiniteCanvas.ImportFromJson(json);
                        }
                        catch
                        {
                            var dialog = new MessageDialog("Invalid File");
                            await dialog.ShowAsync();
                        }
                    }
                }
            });

            SampleController.Current.RegisterNewCommand("Export max view as image", async(sender, args) =>
            {
                if (_infiniteCanvas != null)
                {
                    var savePicker = new FileSavePicker
                    {
                        SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                        SuggestedFileName      = "Infinite Canvas Max View",
                        FileTypeChoices        =
                        {
                            { "PNG Picture",  new List <string> {
                                  ".png"
                              } },
                            { "JPEG Picture", new List <string> {
                                  ".jpg"
                              } }
                        }
                    };
                    var imageFile = await savePicker.PickSaveFileAsync();
                    if (imageFile != null)
                    {
                        BitmapFileFormat bitmapFileFormat;
                        switch (imageFile.FileType.ToLower())
                        {
                        case ".png":
                            bitmapFileFormat = BitmapFileFormat.Png;
                            break;

                        case ".jpg":
                            bitmapFileFormat = BitmapFileFormat.Jpeg;
                            break;

                        default:
                            bitmapFileFormat = BitmapFileFormat.Png;
                            break;
                        }

                        using (var fileStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite, StorageOpenOptions.None))
                        {
                            await _infiniteCanvas.SaveBitmapAsync(fileStream, bitmapFileFormat);
                        }
                    }
                }
            });
        }
コード例 #4
0
        private async void btnReplace_Click(object sender, RoutedEventArgs e)
        {
            StorageFile storageFile;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "FindAndReplace";
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("FindAndReplace.xlsx", CreationCollisionOption.ReplaceExisting);
            }

            if (storageFile == null)
            {
                return;
            }


            #region Initializing Workbook
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2013;

            Assembly  assembly     = typeof(FindAndReplace).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.ReplaceOptions.xlsx";
            Stream    fileStream   = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook     = await application.Workbooks.OpenAsync(fileStream);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];
            #endregion

            ExcelFindOptions options = ExcelFindOptions.None;
            if (check1.IsChecked == true)
            {
                options |= ExcelFindOptions.MatchCase;
            }
            if (check2.IsChecked == true)
            {
                options |= ExcelFindOptions.MatchEntireCellContent;
            }

            sheet.Replace(comboBox1.SelectedItem.ToString(), textBox2.Text, options);

            #region Saving the workbook
            await workbook.SaveAsAsync(storageFile);

            workbook.Close();
            excelEngine.Dispose();
            #endregion

            #region Launching the saved workbook
            MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

            UICommand yesCmd = new UICommand("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new UICommand("No");
            msgDialog.Commands.Add(noCmd);
            IUICommand cmd = await msgDialog.ShowAsync();

            if (cmd == yesCmd)
            {
                // Launch the saved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
            }
            #endregion
        }
コード例 #5
0
        /// <summary>
        /// 文件另存为
        /// 过程和打开文件相同,先检查本地
        /// </summary>
        public async void SaveAs()
        {
            if (State != FileItemState.None || string.IsNullOrEmpty(ID))
            {
                return;
            }

            string fileName = Path.Combine(Kit.CachePath, GetFileName());

            if (!File.Exists(fileName))
            {
                // 先下载
                bool suc = await Download();

                if (!suc)
                {
                    return;
                }
            }

#if UWP
            FileSavePicker picker = new FileSavePicker();
            picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            picker.FileTypeChoices.Add(GetSaveDesc(), new List <string>()
            {
                GetExtName()
            });
            picker.SuggestedFileName = _itemInfo.FileName;
            StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                var folder = await StorageFolder.GetFolderFromPathAsync(Kit.CachePath);

                var temp = await folder.TryGetItemAsync(GetFileName()) as StorageFile;

                if (temp != null)
                {
                    await temp.CopyAndReplaceAsync(file);

                    Kit.Msg("文件另存成功!");
                    return;
                }
            }
#elif ANDROID
            //string savePath;
            //string msg;
            //if (FileType == FileItemType.Image)
            //{
            //    savePath = IOUtil.GetPicturesPath();
            //    msg = "照片";
            //}
            //else if (FileType == FileItemType.Video)
            //{
            //    savePath = IOUtil.GetMoviesPath();
            //    msg = "电影";
            //}
            //else if (FileType == FileItemType.Sound)
            //{
            //    savePath = IOUtil.GetMusicPath();
            //    msg = "音乐";
            //}
            //else
            //{
            //    savePath = IOUtil.GetDownloadsPath();
            //    msg = "下载";
            //}
            try
            {
                // 复制本地文件
                // android 11.0 因放在其他公共目录时被过滤显示,统一放在下载
                File.Copy(fileName, Path.Combine(IOUtil.GetDownloadsPath(), GetFileName()), true);
                Kit.Msg("已保存到下载目录!");
            }
            catch
            {
                Kit.Warn("文件保存失败!");
            }
#elif IOS
            if (FileType == FileItemType.Image || FileType == FileItemType.Video)
            {
                var status = await Permissions.CheckStatusAsync <Permissions.Photos>();

                if (status != PermissionStatus.Granted)
                {
                    status = await Permissions.RequestAsync <Permissions.Photos>();
                }

                if (status == PermissionStatus.Granted)
                {
                    if (FileType == FileItemType.Image)
                    {
                        var imageData = System.IO.File.ReadAllBytes(fileName);
                        var myImage   = new UIKit.UIImage(Foundation.NSData.FromArray(imageData));
                        myImage.SaveToPhotosAlbum((image, error) =>
                        {
                            if (error == null)
                            {
                                Kit.Msg("已保存到照片!");
                            }
                        });
                    }
                    else
                    {
                        UIKit.UIVideo.SaveToPhotosAlbum(fileName, (image, error) =>
                        {
                            if (error == null)
                            {
                                Kit.Msg("已保存到照片!");
                            }
                        });
                    }
                }
            }
            else
            {
                // 普通文件以共享方式保存
                await ShareFile();
            }
#endif
        }
コード例 #6
0
        public override async void OnNavigatedTo(NavigatedToEventArgs e, Dictionary <string, object> viewModelState)
        {
            base.OnNavigatedTo(e, viewModelState);

            var client = await ClientService.GetClient();

            if (client == null)
            {
                return;
            }

            _cts = new CancellationTokenSource();

            var parameters   = SingleFileDownloadPageParameters.Deserialize(e.Parameter);
            var resourceInfo = parameters?.ResourceInfo;

            if (resourceInfo == null)
            {
                return;
            }

            if (resourceInfo.ContentType == "dav/directory")
            {
                ResourceInfo = new ResourceInfo
                {
                    Name        = resourceInfo.Name + ".zip",
                    ContentType = "application/zip"
                };
            }
            else
            {
                ResourceInfo = resourceInfo;
            }

            var savePicker = new FileSavePicker();

            savePicker.FileTypeChoices.Add(ResourceInfo.ContentType, new List <string> {
                Path.GetExtension(ResourceInfo.Name)
            });
            savePicker.SuggestedFileName = ResourceInfo.Name;

            var localFile = await savePicker.PickSaveFileAsync();

            if (localFile == null)
            {
                return;
            }

            _currentFile = localFile;

            // Prevent updates to the remote version of the file until
            // we finish making changes and call CompleteUpdatesAsync.
            CachedFileManager.DeferUpdates(localFile);

            try
            {
                IProgress <HttpProgress>        progress = new Progress <HttpProgress>(ProgressHandler);
                Windows.Storage.Streams.IBuffer buffer;
                switch (resourceInfo.ContentType)
                {
                case "dav/directory":
                    buffer = await client.DownloadDirectoryAsZip(ResourceInfo.Path, _cts, progress);

                    break;

                default:
                    buffer = await client.Download(ResourceInfo.Path + "/" + ResourceInfo.Name, _cts, progress);

                    break;
                }
                await FileIO.WriteBufferAsync(localFile, buffer);
            }
            catch (ResponseError e2)
            {
                ResponseErrorHandlerService.HandleException(e2);
            }

            // Let Windows know that we're finished changing the file so
            // the other app can update the remote version of the file.
            // Completing updates may require Windows to ask for user input.
            var status = await CachedFileManager.CompleteUpdatesAsync(localFile);

            if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
            {
                //this.textBlock.Text = "Path " + file.Name + " was saved.";
            }
            else
            {
                //this.textBlock.Text = "Path " + file.Name + " couldn't be saved.";
            }

            _navigationService.GoBack();
        }
コード例 #7
0
        async private void OnSaveAsAppBarButtonClick(object sender, RoutedEventArgs args)
        {
            FileSavePicker picker = new FileSavePicker();

            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;

            // Get the encoder information
            Dictionary <string, Guid> imageTypes = new Dictionary <string, Guid>();
            IReadOnlyList <BitmapCodecInformation> codecInfos =
                BitmapEncoder.GetEncoderInformationEnumerator();

            foreach (BitmapCodecInformation codecInfo in codecInfos)
            {
                List <string> extensions = new List <string>();

                foreach (string extension in codecInfo.FileExtensions)
                {
                    extensions.Add(extension);
                }

                string filetype = codecInfo.FriendlyName.Split(' ')[0];
                picker.FileTypeChoices.Add(filetype, extensions);

                foreach (string mimeType in codecInfo.MimeTypes)
                {
                    imageTypes.Add(mimeType, codecInfo.CodecId);
                }
            }

            // Get a selected StorageFile
            StorageFile storageFile = await picker.PickSaveFileAsync();

            if (storageFile == null)
            {
                return;
            }

            // Open the StorageFile
            using (IRandomAccessStream fileStream =
                       await storageFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                // Create an encoder
                Guid          codecId = imageTypes[storageFile.ContentType];
                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(codecId, fileStream);

                // Get the pixels from the existing WriteableBitmap
                WriteableBitmap bitmap = image.Source as WriteableBitmap;
                byte[]          pixels = new byte[4 * bitmap.PixelWidth * bitmap.PixelHeight];

                using (Stream pixelStream = bitmap.PixelBuffer.AsStream())
                {
                    await pixelStream.ReadAsync(pixels, 0, pixels.Length);
                }

                // Write those pixels to the first frame
                encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
                                     (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight,
                                     dpiX, dpiY, pixels);

                await encoder.FlushAsync();
            }
        }
コード例 #8
0
        /// <summary>
        /// this is used when the user selects save to file
        /// </summary>
        /// <remarks>
        /// to implement this, we will need to create and instance of the save file picker
        /// then write the output stream into a file
        /// </remarks>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnSaveToFile_Click(object sender, RoutedEventArgs e)
        {
            string text = this.tbData.Text;


            // select the file to save this data to
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.DefaultFileExtension = ".wav";
            // this is the only type available
            savePicker.FileTypeChoices.Add("Audio file", new List <string>()
            {
                ".wav"
            });

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                this.btnSaveToFile.IsEnabled = false;

                // create the data stream
                SpeechSynthesisStream synthesisStream;
                try
                {
                    synthesisStream = await this.synthesizer.SynthesizeSsmlToStreamAsync(text);
                }
                catch (Exception)
                {
                    synthesisStream = null;
                    this.btnSaveToFile.IsEnabled = true;
                }

                if (synthesisStream == null)
                {
                    MessageDialog dialog = new MessageDialog("unable to synthesize text");
                    await dialog.ShowAsync();

                    return;
                }

                // open the output stream
                Windows.Storage.Streams.Buffer buffer      = new Windows.Storage.Streams.Buffer(4096);
                IRandomAccessStream            writeStream = (IRandomAccessStream)await file.OpenAsync(FileAccessMode.ReadWrite);

                IOutputStream outputStream = writeStream.GetOutputStreamAt(0);
                DataWriter    dataWriter   = new DataWriter(outputStream);

                // copy the stream data into the file
                while (synthesisStream.Position < synthesisStream.Size)
                {
                    await synthesisStream.ReadAsync(buffer, 4096, InputStreamOptions.None);

                    dataWriter.WriteBuffer(buffer);
                }

                // close the data file streams
                dataWriter.StoreAsync().AsTask().Wait();
                outputStream.FlushAsync().AsTask().Wait();

                this.btnSaveToFile.IsEnabled = true;
            }
        }
コード例 #9
0
ファイル: PageAdd.xaml.cs プロジェクト: Raizohaza/DoAn1
        private async void Import_Detail_Images_Click(object sender, RoutedEventArgs e)
        {
            ExcelEngine excelEngine = new ExcelEngine();

            IApplication application = excelEngine.Excel;

            //Instantiates the File Picker.
            try
            {
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
                openPicker.FileTypeFilter.Add(".xlsx");
                openPicker.FileTypeFilter.Add(".xls");
                StorageFile openFile = await openPicker.PickSingleFileAsync();

                //Opens the workbook.
                IWorkbook workbook = await application.Workbooks.OpenAsync(openFile);

                //Access first worksheet from the workbook.
                var tabs = workbook.Worksheets;

                //Sets workbook version.
                workbook.Version = ExcelVersion.Excel2016;

                //Initializes FileSavePicker.
                FileSavePicker        savePicker = new FileSavePicker();
                List <Product_Images> list       = new List <Product_Images>();
                foreach (var tab in tabs)
                {
                    Debug.WriteLine(tab.Name);
                    var row     = 3;
                    var product = new Product()
                    {
                        Name = tab.Name
                    };

                    tab.UsedRangeIncludesFormatting = false;
                    var cell = tab.Range[$"C3"];

                    while (cell.Value != null && !cell.IsBlank)
                    {
                        var image = tab.Range[$"B{row}"].Text;
                        var name  = tab.Range[$"C{row}"].Text;

                        var ImageId = (int)QueryForSQLServer.GetProductsByImage(image).Rows[0].ItemArray[0];

                        var product_image = new Product_Images()
                        {
                            ProductId = ImageId,
                            Name      = name
                        };


                        Debug.WriteLine($"{image}{name}");
                        list.Add(product_image);
                        // Đi qua dòng kế
                        row++;
                        cell = tab.Range[$"C{row}"];
                    }
                }
                workbook.Close();
                excelEngine.Dispose();

                var messageDialog = new MessageDialog("Import", "Confirm");

                messageDialog.Commands.Add(new UICommand("Yes")
                {
                    Id = 0
                });
                messageDialog.Commands.Add(new UICommand("No")
                {
                    Id = 1
                });
                messageDialog.DefaultCommandIndex = 0;
                messageDialog.CancelCommandIndex  = 1;

                var result = await messageDialog.ShowAsync();

                if ((int)result.Id == 0)
                {
                    var i          = QueryForSQLServer.GetProducts_ImageMaxId(list[0].ProductId) + 1;
                    var preProduct = list[0].ProductId;
                    foreach (var img in list)
                    {
                        if (img.ProductId != preProduct)
                        {
                            i = QueryForSQLServer.GetProducts_ImageMaxId(img.ProductId) + 1;
                        }
                        img.id     = i;
                        preProduct = img.ProductId;
                        QueryForSQLServer.InsertProduct_Image(img);
                        Debug.WriteLine(img.id + img.Name + img.ProductId);
                        i++;
                    }
                    var messageDialog2 = await new  MessageDialog("Success", "Confirm").ShowAsync();
                }

                else
                {
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
            }
        }
コード例 #10
0
        async Task ExportGrayscale()
        {
            var picker = new FileSavePicker();

            picker.FileTypeChoices.Add("Jpeg files", new List <string> {
                ".jpg"
            });
            picker.DefaultFileExtension = ".jpg";

            // the user should pick the output file
            StorageFile file = await picker.PickSaveFileAsync();

            if (file != null)
            {
                // the render target object
                var rt = _d2dContext;

                // create the target Direct2D bitmap for the given DXGI.Surface
                var bpTarget = new D2D.BitmapProperties1(
                    new D2D.PixelFormat(DXGI.Format.B8G8R8A8_UNorm, D2D.AlphaMode.Premultiplied),
                    (float)_bitmap.DpiX, (float)_bitmap.DpiY, D2D.BitmapOptions.Target | D2D.BitmapOptions.CannotDraw);
                Size2L bmpSize   = new Size2L(_bitmap.PixelWidth, _bitmap.PixelHeight);
                var    targetBmp = D2D.Bitmap1.Create(rt, bmpSize, bpTarget);

                // associate the target bitmap with render target
                rt.SetTarget(targetBmp);

                // start drawing
                rt.BeginDraw();

                // clear the target bitmap
                rt.Clear(null);

                // convert C1Bitmap image to Direct2D image
                var d2dBitmap = _bitmap.ToD2DBitmap1(rt, D2D.BitmapOptions.None);

                // create the Grayscale effect
                _colorMatrix.SetInput(0, d2dBitmap);
                _colorMatrix.Matrix = new Matrix5x4(
                    0.299f, 0.299f, 0.299f, 0,
                    0.587f, 0.587f, 0.587f, 0,
                    0.114f, 0.114f, 0.114f, 0,
                    0, 0, 0, 1,
                    0, 0, 0, 0
                    );

                // and draw the result
                rt.DrawImage(_colorMatrix, Point2F.Empty);
                d2dBitmap.Dispose();

                // now let's draw the additional text label with shadow
                rt.Transform = Matrix3x2.Rotation(-90f) * Matrix3x2.Translation(6f, 344f);
                _brush.SetColor(ColorF.White);
                rt.DrawTextLayout(new Point2F(-1f, -1f), _textLayout, _brush);
                _brush.SetColor(ColorF.DimGray);
                rt.DrawTextLayout(Point2F.Empty, _textLayout, _brush);
                rt.Transform = Matrix3x2.Identity;

                // finish drawing (all drawing commands are executed now)
                if (!rt.EndDraw(true))
                {
                    // clean up and return if the GPU device was removed and we can't draw
                    targetBmp.Dispose();
                    return;
                }

                // detach the target bitmap
                rt.SetTarget(null);

                // create a temporary C1Bitmap object
                var exportBitmap = new C1Bitmap(_bitmap.ImagingFactory);

                // import the image from Direct2D target bitmap to C1Bitmap
                var srcRect = new RectL(_bitmap.PixelWidth, _bitmap.PixelHeight);
                exportBitmap.Import(targetBmp, rt, srcRect);
                targetBmp.Dispose();

                // save the image to file
                await exportBitmap.SaveAsJpegAsync(file, null);

                exportBitmap.Dispose();
            }
        }
コード例 #11
0
        private async void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            #region Setting output location
            StorageFile storageFile;
            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "PivotTableCreateSample";
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("PivotTableCreateSample.xlsx", CreationCollisionOption.ReplaceExisting);
            }

            if (storageFile == null)
            {
                return;
            }
            #endregion

            #region Initializing Workbook
            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2013;

            Assembly  assembly     = typeof(PivotTable).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.PivotCodeData.xlsx";
            Stream    fileStream   = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook     = await application.Workbooks.OpenAsync(fileStream);

            IWorksheet dataSheet  = workbook.Worksheets[0];
            IWorksheet pivotSheet = workbook.Worksheets[1];
            #endregion

            #region Creating Pivot Table
            IPivotCache cache = workbook.PivotCaches.Add(dataSheet["A1:H50"]);

            //Insert the pivot table.
            IPivotTable pivotTable = pivotSheet.PivotTables.Add("PivotTable1", pivotSheet["A1"], cache);
            pivotTable.Fields[2].Axis = PivotAxisTypes.Row;
            pivotTable.Fields[4].Axis = PivotAxisTypes.Row;
            pivotTable.Fields[3].Axis = PivotAxisTypes.Column;

            IPivotField field1 = pivotSheet.PivotTables[0].Fields[5];
            pivotTable.DataFields.Add(field1, "Sum of Units", PivotSubtotalTypes.Sum);

            pivotTable.ShowDrillIndicators  = true;
            pivotTable.RowGrand             = true;
            pivotTable.DisplayFieldCaptions = true;
            pivotTable.BuiltInStyle         = PivotBuiltInStyles.PivotStyleMedium2;
            pivotSheet.Activate();

            #region Dynamic source change

            #region Adding rows
            string accountingFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* \"-\"??_);_(@_)";
            string dateFormat       = "[$-409]d-mmm-yy;@";

            dataSheet["A51"].NumberFormat = dateFormat;
            dataSheet["A51"].DateTime     = DateTime.Parse("5/12/2012", CultureInfo.InvariantCulture);
            dataSheet["B51"].Formula      = "=TEXT(A51,\"dddd\")";
            dataSheet["C51"].Value        = "Central";
            dataSheet["D51"].Value        = "Allan";
            dataSheet["E51"].Value        = "Binder";
            dataSheet["F51"].Number       = 87;
            dataSheet["G51"].Number       = 3.21;
            dataSheet["G51"].NumberFormat = accountingFormat;
            dataSheet["H51"].Formula      = "G51*F51";
            dataSheet["H51"].NumberFormat = accountingFormat;

            dataSheet["A52"].NumberFormat = dateFormat;
            dataSheet["A52"].DateTime     = DateTime.Parse("5/15/2012", CultureInfo.InvariantCulture);
            dataSheet["B52"].Formula      = "=TEXT(A52,\"dddd\")";
            dataSheet["C52"].Value        = "Central";
            dataSheet["D52"].Value        = "Andrew";
            dataSheet["E52"].Value        = "Binder";
            dataSheet["F52"].Number       = 95;
            dataSheet["G52"].Number       = 2.48;
            dataSheet["G52"].NumberFormat = accountingFormat;
            dataSheet["H52"].Formula      = "G52*F52";
            dataSheet["H52"].NumberFormat = accountingFormat;

            dataSheet["A53"].NumberFormat = dateFormat;
            dataSheet["A53"].DateTime     = DateTime.Parse("5/18/2012", CultureInfo.InvariantCulture);
            dataSheet["B53"].Formula      = "=TEXT(A53,\"dddd\")";
            dataSheet["C53"].Value        = "West";
            dataSheet["D53"].Value        = "Kevin";
            dataSheet["E53"].Value        = "Binder";
            dataSheet["F53"].Number       = 68;
            dataSheet["G53"].Number       = 1.75;
            dataSheet["G53"].NumberFormat = accountingFormat;
            dataSheet["H53"].Formula      = "G53*F53";
            dataSheet["H53"].NumberFormat = accountingFormat;

            dataSheet["A54"].NumberFormat = dateFormat;
            dataSheet["A54"].DateTime     = DateTime.Parse("5/21/2012", CultureInfo.InvariantCulture);
            dataSheet["B54"].Formula      = "=TEXT(A54,\"dddd\")";
            dataSheet["C54"].Value        = "West";
            dataSheet["D54"].Value        = "Jack";
            dataSheet["E54"].Value        = "Binder";
            dataSheet["F54"].Number       = 19;
            dataSheet["G54"].Number       = 1.01;
            dataSheet["G54"].NumberFormat = accountingFormat;
            dataSheet["H54"].Formula      = "G54*F54";
            dataSheet["H54"].NumberFormat = accountingFormat;

            dataSheet["A55"].NumberFormat = dateFormat;
            dataSheet["A55"].DateTime     = DateTime.Parse("5/24/2012", CultureInfo.InvariantCulture);
            dataSheet["B55"].Formula      = "=TEXT(A55,\"dddd\")";
            dataSheet["C55"].Value        = "East";
            dataSheet["D55"].Value        = "Allan";
            dataSheet["E55"].Value        = "File Folder";
            dataSheet["F55"].Number       = 20;
            dataSheet["G55"].Number       = 0.28;
            dataSheet["G55"].NumberFormat = accountingFormat;
            dataSheet["H55"].Formula      = "G55*F55";
            dataSheet["H55"].NumberFormat = accountingFormat;

            dataSheet["A56"].NumberFormat = dateFormat;
            dataSheet["A56"].DateTime     = DateTime.Parse("5/27/2012", CultureInfo.InvariantCulture);
            dataSheet["B56"].Formula      = "=TEXT(A56,\"dddd\")";
            dataSheet["C56"].Value        = "East";
            dataSheet["D56"].Value        = "Jack";
            dataSheet["E56"].Value        = "File Folder";
            dataSheet["F56"].Number       = 32;
            dataSheet["G56"].Number       = 0.45;
            dataSheet["G56"].NumberFormat = accountingFormat;
            dataSheet["H56"].Formula      = "G56*F56";
            dataSheet["H56"].NumberFormat = accountingFormat;

            dataSheet["A57"].NumberFormat = dateFormat;
            dataSheet["A57"].DateTime     = DateTime.Parse("5/30/2012", CultureInfo.InvariantCulture);
            dataSheet["B57"].Formula      = "=TEXT(A57,\"dddd\")";
            dataSheet["C57"].Value        = "West";
            dataSheet["D57"].Value        = "Kevin";
            dataSheet["E57"].Value        = "Binder";
            dataSheet["F57"].Number       = 23;
            dataSheet["G57"].Number       = 1.19;
            dataSheet["G57"].NumberFormat = accountingFormat;
            dataSheet["H57"].Formula      = "G57*F57";
            dataSheet["H57"].NumberFormat = accountingFormat;

            dataSheet["A58"].NumberFormat = dateFormat;
            dataSheet["A58"].DateTime     = DateTime.Parse("6/2/2012", CultureInfo.InvariantCulture);
            dataSheet["B58"].Formula      = "=TEXT(A58,\"dddd\")";
            dataSheet["C58"].Value        = "West";
            dataSheet["D58"].Value        = "Andrew";
            dataSheet["E58"].Value        = "Binder";
            dataSheet["F58"].Number       = 43;
            dataSheet["G58"].Number       = 1.92;
            dataSheet["G58"].NumberFormat = accountingFormat;
            dataSheet["H58"].Formula      = "G58*F58";
            dataSheet["H58"].NumberFormat = accountingFormat;
            #endregion

            //Adding new named range to the workbook
            IName name = workbook.Names.Add("DynamicRange", dataSheet.UsedRange);

            //Setting pivot table source range from named range
            workbook.PivotCaches[0].SourceRange = name.RefersToRange;
            pivotSheet.SetColumnWidth(1, 15.29);
            pivotSheet.SetColumnWidth(2, 15.29);
            pivotSheet.SetColumnWidth(14, 10.43);
            #endregion

            #endregion

            #region Saving workbook and disposing objects

            await workbook.SaveAsAsync(storageFile);

            workbook.Close();
            excelEngine.Dispose();

            #endregion

            #region Save accknowledgement and Launching of output file
            MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

            UICommand yesCmd = new UICommand("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new UICommand("No");
            msgDialog.Commands.Add(noCmd);
            IUICommand cmd = await msgDialog.ShowAsync();

            if (cmd == yesCmd)
            {
                // Launch the saved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
            }
            #endregion
        }
コード例 #12
0
        public async Task PickSaveFile()
        {
            if (simplePhotoEditor.canvasRenderTarget == null)
            {
                StartWritingOutput("No Effects Applied");
                return;
            }


            FileSavePicker picker = new FileSavePicker();

            picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            picker.SuggestedFileName      = "SavedImage";
            picker.DefaultFileExtension   = ".png";
            picker.FileTypeChoices.Add("Image Files (*.png, *.jpg, *.tiff, *.gif) ", new List <string> {
                ".png", ".jpg", ".tiff", ".gif"
            });

            StorageFile outfile = await picker.PickSaveFileAsync();

            if (outfile != null)
            {
                CanvasBitmapFileFormat canvasBitmapFileFormat = CanvasBitmapFileFormat.Png;


                string filepath = outfile.Path;
                filepath = filepath.ToLower();
                int index = filepath.IndexOf(".jpg");
                if (index > 0)
                {
                    canvasBitmapFileFormat = CanvasBitmapFileFormat.Jpeg;
                }
                else
                {
                    index = filepath.IndexOf(".png");
                    if (index > 0)
                    {
                        canvasBitmapFileFormat = CanvasBitmapFileFormat.Png;
                    }
                    else
                    {
                        index = filepath.IndexOf(".tif");
                        if (index > 0)
                        {
                            canvasBitmapFileFormat = CanvasBitmapFileFormat.Tiff;
                        }
                        else
                        {
                            index = filepath.IndexOf(".gif");
                            if (index > 0)
                            {
                                canvasBitmapFileFormat = CanvasBitmapFileFormat.Gif;
                            }
                        }
                    }
                }

                ApplyFilterEffects(true);


                await simplePhotoEditor.SaveCanvasBitmap(outfile, canvasBitmapFileFormat);

                ApplyFilterEffects(false, null, false);


                canvas2d.Invalidate();
            }
        }
コード例 #13
0
        public async void Execute(object parameter)
        {
            BucketEntryViewModel bucketEntryVM = parameter as BucketEntryViewModel;

#if !__ANDROID__
            FileSavePicker picker = new FileSavePicker();
            if (bucketEntryVM.ObjectInfo.Path.Contains("mp4"))
            {
                picker.SuggestedStartLocation = PickerLocationId.VideosLibrary;
                picker.FileTypeChoices.Add("Video", new List <string>()
                {
                    ".mp4"
                });
            }
            else
            {
                picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
                picker.FileTypeChoices.Add("Image", new List <string>()
                {
                    ".jpg"
                });
            }

            picker.SuggestedFileName = bucketEntryVM.ObjectInfo.Path;


            var file = await picker.PickSaveFileAsync();

            if (file == null)
            {
                return;
            }

            Windows.Storage.CachedFileManager.DeferUpdates(file);

            try
            {
                var bucket = await _bucketService.OpenBucketAsync(bucketEntryVM._bucketContentViewModel.BucketName);

                var downloadOperation = await _objectService.DownloadObjectAsync(bucket, bucketEntryVM.ObjectInfo.Path, true);

                downloadOperation.DownloadOperationEnded += async(operation) =>
                {
                    if (!operation.Failed && !operation.Cancelled)
                    {
                        await Windows.Storage.FileIO.WriteBytesAsync(file, operation.DownloadedBytes);

                        var status = await CachedFileManager.CompleteUpdatesAsync(file);
                    }
                };
                if (BucketContentViewModel.ActiveDownloadOperations.ContainsKey(_bucketName))
                {
                    BucketContentViewModel.ActiveDownloadOperations[_bucketName].Add(downloadOperation);
                }
                else
                {
                    var list = new List <DownloadOperation>();
                    list.Add(downloadOperation);
                    BucketContentViewModel.ActiveDownloadOperations.Add(_bucketName, list);
                }
                _senderView.AddDownloadOperation(downloadOperation);
            }
            catch (Exception ex)
            {
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("Could not download object - " + ex.Message);
                await dialog.ShowAsync();

                return;
            }
#else
            var path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;

            try
            {
                var bucket = await _bucketService.GetBucketAsync(bucketEntryVM._bucketContentViewModel.BucketName);

                var downloadOperation = await _objectService.DownloadObjectAsync(bucket, bucketEntryVM.ObjectInfo.Key, new DownloadOptions(), true);

                downloadOperation.DownloadOperationEnded += async(operation) =>
                {
                    if (!operation.Failed && !operation.Cancelled)
                    {
                        string filePath = Path.Combine(path, "Download");
                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }

                        filePath = Path.Combine(filePath, "Storj");
                        if (!Directory.Exists(filePath))
                        {
                            Directory.CreateDirectory(filePath);
                        }
                        filePath = Path.Combine(filePath, bucketEntryVM.ObjectInfo.Key);
                        using (FileStream fs = new FileStream(filePath, FileMode.Create))
                        {
                            await fs.WriteAsync(operation.DownloadedBytes, 0, (int)operation.TotalBytes);
                        }
                    }
                };
                if (BucketContentViewModel.ActiveDownloadOperations.ContainsKey(_bucketName))
                {
                    BucketContentViewModel.ActiveDownloadOperations[_bucketName].Add(downloadOperation);
                }
                else
                {
                    var list = new List <DownloadOperation>();
                    list.Add(downloadOperation);
                    BucketContentViewModel.ActiveDownloadOperations.Add(_bucketName, list);
                }
                _senderView.AddDownloadOperation(downloadOperation);
            }
            catch (Exception ex)
            {
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("Could not download object - " + ex.Message);
                await dialog.ShowAsync();

                return;
            }
#endif
        }
コード例 #14
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            #region Initializing Workbook
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the Excel application object.
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2016;

            Assembly  assembly     = typeof(FunnelChart).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.GroupShapes.xlsx";
            Stream    fileStream   = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook     = await application.Workbooks.OpenAsync(fileStream);

            IWorksheet worksheet;
            #endregion

            #region Group Shape Creation

            if (this.rdBtnGroup.IsChecked != null && this.rdBtnGroup.IsChecked.Value)
            {
                // The first worksheet object in the worksheets collection is accessed.
                worksheet = workbook.Worksheets[0];
                IShapes shapes = worksheet.Shapes;

                IShape[] groupItems;
                for (int i = 0; i < shapes.Count; i++)
                {
                    if (shapes[i].Name == "Development" || shapes[i].Name == "Production" || shapes[i].Name == "Sales")
                    {
                        groupItems = new IShape[] { shapes[i], shapes[i + 1], shapes[i + 2], shapes[i + 3], shapes[i + 4], shapes[i + 5] };
                        shapes.Group(groupItems);
                        i = -1;
                    }
                }

                groupItems = new IShape[] { shapes[0], shapes[1], shapes[2], shapes[3], shapes[4], shapes[5], shapes[6] };
                shapes.Group(groupItems);
            }
            else if (this.rdBtnUngroupAll.IsChecked != null && this.rdBtnUngroupAll.IsChecked.Value)
            {
                // The second worksheet object in the worksheets collection is accessed.
                worksheet = workbook.Worksheets[1];
                IShapes shapes = worksheet.Shapes;
                shapes.Ungroup(shapes[0] as IGroupShape, true);
                worksheet.Activate();
            }
            else if (this.rdBtnUngroup.IsChecked != null && this.rdBtnUngroup.IsChecked.Value)
            {
                // The second worksheet object in the worksheets collection is accessed.
                worksheet = workbook.Worksheets[1];
                IShapes shapes = worksheet.Shapes;
                shapes.Ungroup(shapes[0] as IGroupShape);
                worksheet.Activate();
            }
            #endregion

            #region Save the Workbook
            StorageFile storageFile;
            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "GroupShapes";
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("GroupShapes.xlsx", CreationCollisionOption.ReplaceExisting);
            }

            if (storageFile != null)
            {
                //Saving the workbook
                await workbook.SaveAsAsync(storageFile);

                workbook.Close();
                excelEngine.Dispose();

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been saved successfully.");

                UICommand yesCmd = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
                }
            }
            else
            {
                workbook.Close();
                excelEngine.Dispose();
            }
            #endregion
        }
コード例 #15
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            StorageFile storageFile;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "SpreadsheetSample";
                if (rdBtn2003.IsChecked.Value)
                {
                    savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                    {
                        ".xls"
                    });
                }
                else
                {
                    savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                    {
                        ".xlsx",
                    });
                }
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                if (rdBtn2003.IsChecked.Value)
                {
                    storageFile = await local.CreateFileAsync("SpreadsheetSample.xls", CreationCollisionOption.ReplaceExisting);
                }
                else
                {
                    storageFile = await local.CreateFileAsync("SpreadsheetSample.xlsx", CreationCollisionOption.ReplaceExisting);
                }
            }

            if (storageFile == null)
            {
                return;
            }


            #region Initializing Workbook
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            if (rdBtn2003.IsChecked.Value)
            {
                application.DefaultVersion = ExcelVersion.Excel97to2003;
            }
            else
            {
                application.DefaultVersion = ExcelVersion.Excel2013;
            }

            //A new workbook is created.[Equivalent to creating a new workbook in MS Excel]
            //The new workbook will have 5 worksheets
            IWorkbook workbook = application.Workbooks.Create(1);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];
            #endregion

            #region Generate Excel
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
            {
                sheet.Range["A2"].RowHeight = 34;
            }

            sheet.Range["A2"].ColumnWidth = 30;
            sheet.Range["B2"].ColumnWidth = 30;
            sheet.Range["C2"].ColumnWidth = 30;
            sheet.Range["D2"].ColumnWidth = 30;

            sheet.Range["A2:D2"].Merge(true);



            //Inserting sample text into the first cell of the first worksheet.
            sheet.Range["A2"].Text = "EXPENSE REPORT";
            sheet.Range["A2"].CellStyle.Font.FontName = "Verdana";
            sheet.Range["A2"].CellStyle.Font.Bold     = true;
            sheet.Range["A2"].CellStyle.Font.Size     = 28;
            sheet.Range["A2"].CellStyle.Font.RGBColor = Windows.UI.Color.FromArgb(0, 0, 112, 192);
            sheet.Range["A2"].HorizontalAlignment     = ExcelHAlign.HAlignCenter;

            sheet.Range["A4"].Text = "Employee";
            sheet.Range["B4"].Text = "Roger Federer";
            sheet.Range["A4:B7"].CellStyle.Font.FontName = "Verdana";
            sheet.Range["A4:B7"].CellStyle.Font.Bold     = true;
            sheet.Range["A4:B7"].CellStyle.Font.Size     = 11;
            sheet.Range["A4:A7"].CellStyle.Font.RGBColor = Windows.UI.Color.FromArgb(0, 128, 128, 128);
            sheet.Range["A4:A7"].HorizontalAlignment     = ExcelHAlign.HAlignLeft;
            sheet.Range["B4:B7"].CellStyle.Font.RGBColor = Windows.UI.Color.FromArgb(0, 174, 170, 170);
            sheet.Range["B4:B7"].HorizontalAlignment     = ExcelHAlign.HAlignRight;

            sheet.Range["A9:D20"].CellStyle.Font.FontName = "Verdana";
            sheet.Range["A9:D20"].CellStyle.Font.Size     = 11;

            sheet.Range["A5"].Text = "Department";
            sheet.Range["B5"].Text = "Administration";

            sheet.Range["A6"].Text         = "Week Ending";
            sheet.Range["B6"].NumberFormat = "m/d/yyyy";
            sheet.Range["B6"].DateTime     = DateTime.Parse("10/10/2012", CultureInfo.InvariantCulture);

            sheet.Range["A7"].Text         = "Mileage Rate";
            sheet.Range["B7"].NumberFormat = "$#,##0.00";
            sheet.Range["B7"].Number       = 0.70;

            sheet.Range["A10"].Text = "Miles Driven";
            sheet.Range["A11"].Text = "Miles Reimbursement";
            sheet.Range["A12"].Text = "Parking and Tolls";
            sheet.Range["A13"].Text = "Auto Rental";
            sheet.Range["A14"].Text = "Lodging";
            sheet.Range["A15"].Text = "Breakfast";
            sheet.Range["A16"].Text = "Lunch";
            sheet.Range["A17"].Text = "Dinner";
            sheet.Range["A18"].Text = "Snacks";
            sheet.Range["A19"].Text = "Others";
            sheet.Range["A20"].Text = "Total";
            sheet.Range["A20:D20"].CellStyle.Color      = Windows.UI.Color.FromArgb(0, 0, 112, 192);
            sheet.Range["A20:D20"].CellStyle.Font.Color = ExcelKnownColors.White;
            sheet.Range["A20:D20"].CellStyle.Font.Bold  = true;

            IStyle style = sheet["B9:D9"].CellStyle;
            style.VerticalAlignment   = ExcelVAlign.VAlignCenter;
            style.HorizontalAlignment = ExcelHAlign.HAlignRight;
            style.Color      = Windows.UI.Color.FromArgb(0, 0, 112, 192);
            style.Font.Bold  = true;
            style.Font.Color = ExcelKnownColors.White;

            sheet.Range["A9"].Text                 = "Expenses";
            sheet.Range["A9"].CellStyle.Color      = Windows.UI.Color.FromArgb(0, 0, 112, 192);
            sheet.Range["A9"].CellStyle.Font.Color = ExcelKnownColors.White;
            sheet.Range["A9"].CellStyle.Font.Bold  = true;
            sheet.Range["B9"].Text                 = "Day 1";
            sheet.Range["B10"].Number              = 100;
            sheet.Range["B11"].NumberFormat        = "$#,##0.00";
            sheet.Range["B11"].Formula             = "=(B7*B10)";
            sheet.Range["B12"].NumberFormat        = "$#,##0.00";
            sheet.Range["B12"].Number              = 0;
            sheet.Range["B13"].NumberFormat        = "$#,##0.00";
            sheet.Range["B13"].Number              = 0;
            sheet.Range["B14"].NumberFormat        = "$#,##0.00";
            sheet.Range["B14"].Number              = 0;
            sheet.Range["B15"].NumberFormat        = "$#,##0.00";
            sheet.Range["B15"].Number              = 9;
            sheet.Range["B16"].NumberFormat        = "$#,##0.00";
            sheet.Range["B16"].Number              = 12;
            sheet.Range["B17"].NumberFormat        = "$#,##0.00";
            sheet.Range["B17"].Number              = 13;
            sheet.Range["B18"].NumberFormat        = "$#,##0.00";
            sheet.Range["B18"].Number              = 9.5;
            sheet.Range["B19"].NumberFormat        = "$#,##0.00";
            sheet.Range["B19"].Number              = 0;
            sheet.Range["B20"].NumberFormat        = "$#,##0.00";
            sheet.Range["B20"].Formula             = "=SUM(B11:B19)";

            sheet.Range["C9"].Text          = "Day 2";
            sheet.Range["C10"].Number       = 145;
            sheet.Range["C11"].NumberFormat = "$#,##0.00";
            sheet.Range["C11"].Formula      = "=(B7*C10)";
            sheet.Range["C12"].NumberFormat = "$#,##0.00";
            sheet.Range["C12"].Number       = 15;
            sheet.Range["C13"].NumberFormat = "$#,##0.00";
            sheet.Range["C13"].Number       = 0;
            sheet.Range["C14"].NumberFormat = "$#,##0.00";
            sheet.Range["C14"].Number       = 45;
            sheet.Range["C15"].NumberFormat = "$#,##0.00";
            sheet.Range["C15"].Number       = 9;
            sheet.Range["C16"].NumberFormat = "$#,##0.00";
            sheet.Range["C16"].Number       = 12;
            sheet.Range["C17"].NumberFormat = "$#,##0.00";
            sheet.Range["C17"].Number       = 15;
            sheet.Range["C18"].NumberFormat = "$#,##0.00";
            sheet.Range["C18"].Number       = 7;
            sheet.Range["C19"].NumberFormat = "$#,##0.00";
            sheet.Range["C19"].Number       = 0;
            sheet.Range["C20"].NumberFormat = "$#,##0.00";
            sheet.Range["C20"].Formula      = "=SUM(C11:C19)";

            sheet.Range["D9"].Text          = "Day 3";
            sheet.Range["D10"].Number       = 113;
            sheet.Range["D11"].NumberFormat = "$#,##0.00";
            sheet.Range["D11"].Formula      = "=(B7*D10)";
            sheet.Range["D12"].NumberFormat = "$#,##0.00";
            sheet.Range["D12"].Number       = 17;
            sheet.Range["D13"].NumberFormat = "$#,##0.00";
            sheet.Range["D13"].Number       = 8;
            sheet.Range["D14"].NumberFormat = "$#,##0.00";
            sheet.Range["D14"].Number       = 45;
            sheet.Range["D15"].NumberFormat = "$#,##0.00";
            sheet.Range["D15"].Number       = 7;
            sheet.Range["D16"].NumberFormat = "$#,##0.00";
            sheet.Range["D16"].Number       = 11;
            sheet.Range["D17"].NumberFormat = "$#,##0.00";
            sheet.Range["D17"].Number       = 16;
            sheet.Range["D18"].NumberFormat = "$#,##0.00";
            sheet.Range["D18"].Number       = 7;
            sheet.Range["D19"].NumberFormat = "$#,##0.00";
            sheet.Range["D19"].Number       = 5;
            sheet.Range["D20"].NumberFormat = "$#,##0.00";
            sheet.Range["D20"].Formula      = "=SUM(D11:D19)";
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
            {
                sheet.UsedRange.AutofitRows();
            }

            #endregion

            #region Saving the workbook
            await workbook.SaveAsAsync(storageFile);

            workbook.Close();
            excelEngine.Dispose();
            #endregion

            #region Launching the saved workbook
            MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

            UICommand yesCmd = new UICommand("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new UICommand("No");
            msgDialog.Commands.Add(noCmd);
            IUICommand cmd = await msgDialog.ShowAsync();

            if (cmd == yesCmd)
            {
                // Launch the saved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
            }
            #endregion
        }
コード例 #16
0
        private async void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            #region Setting output location


            StorageFile storageFile;
            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "AutoShapesSample";
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("AutoShapesSample.xlsx", CreationCollisionOption.ReplaceExisting);
            }

            if (storageFile == null)
            {
                return;
            }
            #endregion

            #region Initializing Workbook
            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

            //if (this.rdBtn2013.IsChecked.Value)
            application.DefaultVersion = ExcelVersion.Excel2013;
            //else if (this.rdBtn2010.IsChecked.Value)
            //    application.DefaultVersion = ExcelVersion.Excel2010;
            //else
            //   application.DefaultVersion = ExcelVersion.Excel2007;


            IWorkbook  workbook  = application.Workbooks.Create(1);
            IWorksheet worksheet = workbook.Worksheets[0];
            #endregion

            #region AddAutoShapes
            IShape shape;
            string text;

            IFont font = workbook.CreateFont();
            font.Color  = ExcelKnownColors.White;
            font.Italic = true;
            font.Size   = 12;


            IFont font2 = workbook.CreateFont();
            font2.Color  = ExcelKnownColors.Black;
            font2.Size   = 15;
            font2.Italic = true;
            font2.Bold   = true;

            text  = "Requirement";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 2, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Light_blue;
            shape.Line.Visible                = false;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;

            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 5, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Design";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 7, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Light_orange;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;


            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 10, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Execution";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 12, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Blue;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;

            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 15, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Testing";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 17, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Green;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;

            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.DownArrow, 20, 8, 40, 64);
            shape.Fill.ForeColorIndex = ExcelKnownColors.White;
            shape.Line.ForeColorIndex = ExcelKnownColors.Blue;
            shape.Line.Weight         = 1;

            text  = "Release";
            shape = worksheet.Shapes.AddAutoShapes(AutoShapeType.RoundedRectangle, 22, 7, 60, 192);
            shape.TextFrame.TextRange.Text = text;
            shape.TextFrame.TextRange.RichText.SetFont(0, text.Length - 1, font);
            shape.TextFrame.TextRange.RichText.SetFont(0, 0, font2);
            shape.Line.Visible                = false;
            shape.Fill.ForeColorIndex         = ExcelKnownColors.Lavender;
            shape.TextFrame.VerticalAlignment = ExcelVerticalAlignment.MiddleCentered;
            #endregion


            #region Saving workbook and disposing objects

            await workbook.SaveAsAsync(storageFile);

            workbook.Close();
            excelEngine.Dispose();

            #endregion

            #region Save accknowledgement and Launching of output file
            MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

            UICommand yesCmd = new UICommand("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new UICommand("No");
            msgDialog.Commands.Add(noCmd);
            IUICommand cmd = await msgDialog.ShowAsync();

            if (cmd == yesCmd)
            {
                // Launch the saved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
            }
            #endregion
        }
コード例 #17
0
        private async void SaveButton_Click(object sender, RoutedEventArgs e)
        {
            // get the title and randomization
            string title    = MyTitleText.Text;
            bool   isRandom = MyRandomizeToggle.IsOn;

            // validate title
            if (title.Equals(""))
            {
                var dialog = new MessageDialog("ERROR: You are missing the title.");
                await dialog.ShowAsync();

                return;
            }

            // get the prompts
            var promptElements = MyPromptElementsStack.Children;

            // validate the prompt size
            if (promptElements.Count == 0)
            {
                var dialog = new MessageDialog("ERROR: You have no prompts.");
                await dialog.ShowAsync();

                return;
            }

            // iterate through each prompt
            var promptElementDataList = new List <Tuple <string, string, int, string> >();

            for (int i = 0; i < promptElements.Count; ++i)
            {
                // get the current prompt
                PromptElement promptElement = (PromptElement)promptElements[i];

                // get the prompt's contents
                string imageFileName  = promptElement.ImageFileName;
                string labelName      = promptElement.LabelName;
                string iterationsText = promptElement.IterationsText;
                string displayType    = promptElement.IsDisplayTrace ? "trace" : promptElement.IsDisplayReference ? "reference" : "none";

                // validate the prompt's contents
                bool   isValid      = true;
                string errorMessage = "";
                int    iterations   = 1;
                if (imageFileName.Equals("") && !displayType.Equals("none"))
                {
                    isValid      = false;
                    errorMessage = "ERROR: One of your prompts is missing an image file name.";
                }
                else if (labelName.Equals(""))
                {
                    isValid      = false;
                    errorMessage = "ERROR: One of your prompts is missing a label name.";
                }
                else if (!int.TryParse(iterationsText, out iterations))
                {
                    isValid      = false;
                    errorMessage = "ERROR: One of your prompts uses a non-number for iterations.";
                }
                else if (iterations <= 0)
                {
                    isValid      = false;
                    errorMessage = "ERROR: One of your prompts uses a non-positive number for iterations.";
                }
                if (!isValid)
                {
                    var dialog = new MessageDialog(errorMessage);
                    await dialog.ShowAsync();

                    return;
                }

                // get the prompt element's data
                var promptElementData = new Tuple <string, string, int, string>(imageFileName, labelName, iterations, displayType);
                promptElementDataList.Add(promptElementData);
            }

            // get save file
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.FileTypeChoices.Add("eXtensible Markup Language (XML) file", new List <string>()
            {
                ".xml"
            });
            savePicker.SuggestedFileName = "New Document";
            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file == null)
            {
                return;
            }

            // write to XML file
            WriteToXml(file, title, isRandom, promptElementDataList);

            // show success message dialog
            var successDialog = new MessageDialog("File saved successfully.", "Success");
            await successDialog.ShowAsync();
        }
コード例 #18
0
        private async void iconSavePhoto_Tapped(object sender, TappedRoutedEventArgs e)
        {
            //This event is triggered when the savecontrol is tapped
            FileSavePicker saveFileP = new FileSavePicker();// A save file picker is uded to select a destination and save the files

            saveFileP.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            saveFileP.FileTypeChoices.Add("Jpeg", new List <string>()
            {
                ".jpeg"
            });
            saveFileP.FileTypeChoices.Add("Jpg", new List <string>()
            {
                ".jpg"
            });
            saveFileP.FileTypeChoices.Add("Png", new List <string>()
            {
                ".png"
            });
            saveFileP.FileTypeChoices.Add("Bmp", new List <string>()
            {
                ".bmp"
            });


            if (selectedSoftwareBmps.Count > 0)// if there are photos is in bitmap list the following code executes
            {
                int photoCounter = 0;
                try
                {
                    foreach (SoftwareBitmap bmp in selectedSoftwareBmps)//
                    {
                        saveFileP.SuggestedFileName = selectedFileNames[photoCounter].ToString();
                        var outputfile = await saveFileP.PickSaveFileAsync();

                        if (outputfile != null)
                        {
                            using (IRandomAccessStream stream = await outputfile.OpenAsync(FileAccessMode.ReadWrite))
                            {
                                // Create an encoder with the desired format
                                BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);

                                encoder.SetSoftwareBitmap(bmp);// Set the software bitmap
                                encoder.IsThumbnailGenerated = true;

                                try
                                {
                                    await encoder.FlushAsync();
                                }

                                catch (Exception err)
                                {
                                }

                                if (encoder.IsThumbnailGenerated == false)
                                {
                                    await encoder.FlushAsync();
                                }
                            }
                            var saveMessage = new MessageDialog("Photo Saved");
                            await saveMessage.ShowAsync();

                            photoCounter++;
                        }
                        else
                        {
                            var saveMessage = new MessageDialog("File Save operation cancelled");
                            await saveMessage.ShowAsync();
                        }
                    }
                }
                catch (Exception exp)
                {
                    var expmsg = new MessageDialog(exp.ToString());
                    await expmsg.ShowAsync();

                    return;
                }

                selectedSoftwareBmps.Clear();
            }
            else
            {
                var saveMessage = new MessageDialog("No Photos selected");
                await saveMessage.ShowAsync();
            }
        }
コード例 #19
0
ファイル: PageAdd.xaml.cs プロジェクト: Raizohaza/DoAn1
        private async void ImportButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ExcelEngine excelEngine = new ExcelEngine();

                IApplication application = excelEngine.Excel;

                //Instantiates the File Picker.



                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
                openPicker.FileTypeFilter.Add(".xlsx");
                openPicker.FileTypeFilter.Add(".xls");
                StorageFile openFile = await openPicker.PickSingleFileAsync();

                //Opens the workbook.
                IWorkbook workbook = await application.Workbooks.OpenAsync(openFile);

                //Access first worksheet from the workbook.
                var tabs = workbook.Worksheets;

                //Set Text in cell A3.


                //Sets workbook version.
                workbook.Version = ExcelVersion.Excel2016;

                //Initializes FileSavePicker.
                FileSavePicker savePicker = new FileSavePicker();

                List <Category> list = new List <Category>();

                foreach (var tab in tabs)
                {
                    Debug.WriteLine(tab.Name);
                    var row      = 3;
                    var category = new Category()
                    {
                        Name = tab.Name
                    };
                    category.Id = QueryForSQLServer.InsertCategory(category);

                    tab.UsedRangeIncludesFormatting = false;
                    var cell = tab.Range[$"C3"];

                    while (cell.Value != null && !cell.IsBlank)
                    {
                        var author      = tab.Range[$"J{row}"].Text;
                        var name        = tab.Range[$"C{row}"].Text;
                        var price       = Convert.ToDecimal(tab.Range[$"D{row}"].Number);
                        var quantity    = (int)(tab.Range[$"E{row}"].Number);
                        var description = tab.Range[$"F{row}"].Text;
                        var image       = tab.Range[$"I{row}"].Text;

                        var product = new Product()
                        {
                            Author      = author,
                            Name        = name,
                            CatId       = category.Id,
                            Price       = price,
                            Quantity    = quantity,
                            Description = description,
                            Image       = image
                        };

                        category.Products.Add(product);


                        Debug.WriteLine($"{author}{name}{price}{quantity}{description}");

                        // Đi qua dòng kế
                        row++;
                        cell = tab.Range[$"C{row}"];
                    }
                    list.Add(category);
                }
                var tes = list;

                workbook.Close();
                excelEngine.Dispose();

                var messageDialog = new MessageDialog("Import", "Confirm");

                messageDialog.Commands.Add(new UICommand("Yes")
                {
                    Id = 0
                });
                messageDialog.Commands.Add(new UICommand("No")
                {
                    Id = 1
                });
                messageDialog.DefaultCommandIndex = 0;
                messageDialog.CancelCommandIndex  = 1;

                var result = await messageDialog.ShowAsync();

                if ((int)result.Id == 0)
                {
                    foreach (var cat in list)
                    {
                        cat.Id = QueryForSQLServer.InsertCategory(cat);
                        foreach (var product in cat.Products)
                        {
                            var index = QueryForSQLServer.InsertProduct(product);
                        }
                    }
                    var messageDialog2 = await new MessageDialog("Success", "Confirm").ShowAsync();
                }
                else
                {
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Exception: " + ex.Message);
            }
        }
コード例 #20
0
ファイル: MainViewModel.cs プロジェクト: GooG2e/Ass-Loader
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            if (Windows.System.Profile.AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Mobile")
            {
                isMobile = true;
            }
            openPicker = new FileOpenPicker();
            openPicker.FileTypeFilter.Add(".ass");

            savePicker = new FileSavePicker()
            {
                DefaultFileExtension = ".ass"
            };
            savePicker.FileTypeChoices.Add(LocalizedStrings.Resources.AssFileName, new[] { ".ass" });

            saveDialog = new MessageDialog(LocalizedStrings.Resources.SaveDialogContent, LocalizedStrings.Resources.SaveDialogTitle);
            saveDialog.Commands.Add(new UICommand(LocalizedStrings.Resources.SaveDialogYes, null, dialogResult.Yes));
            saveDialog.Commands.Add(new UICommand(LocalizedStrings.Resources.SaveDialogNo, null, dialogResult.No));
            saveDialog.DefaultCommandIndex = 0;
            if (!isMobile)
            {
                saveDialog.Commands.Add(new UICommand(LocalizedStrings.Resources.SaveDialogCancel, null, dialogResult.Cancel));
                saveDialog.CancelCommandIndex = 2;
            }

            newFile = new RelayCommand(async() =>
            {
                if (!await CleanUpBeforeNewOrOpen())
                {
                    return;
                }
                Document.NewSubtitle();
            });
            openFile = new RelayCommand(async() =>
            {
                if (!await CleanUpBeforeNewOrOpen())
                {
                    return;
                }
                var file = await openPicker.PickSingleFileAsync();
                if (file == null)
                {
                    return;
                }
                await Document.OpenFileAsync(file);
            });
            saveFile = new RelayCommand(async() => await Save(), () => Document.IsModified);

            SplitViewButtons.Add(new SplitViewButtonData()
            {
                Icon    = "\xE160",
                Content = LocalizedStrings.Resources.SplitViewButtonNew,
                Command = newFile
            });
            SplitViewButtons.Add(new SplitViewButtonData()
            {
                Icon    = "\xE8E5",
                Content = LocalizedStrings.Resources.SplitViewButtonOpen,
                Command = openFile
            });
            SplitViewButtons.Add(new SplitViewButtonData()
            {
                Icon    = "\xE105",
                Content = LocalizedStrings.Resources.SplitViewButtonSave,
                Command = saveFile
            });

            DocumentTabs.Add(new SplitViewTabData()
            {
                Icon      = "\xE1CB",
                Content   = LocalizedStrings.Resources.SplitViewTabScriptInfo,
                PageType  = typeof(View.ScriptInfoPage),
                IsChecked = true
            });
            DocumentTabs.Add(new SplitViewTabData()
            {
                Icon     = "\xE2B1",
                Content  = LocalizedStrings.Resources.SplitViewTabStyle,
                PageType = typeof(View.StylePage)
            });
            DocumentTabs.Add(new SplitViewTabData()
            {
                Icon     = "\xE292",
                Content  = LocalizedStrings.Resources.SplitViewTabEvent,
                PageType = typeof(View.SubEventPage)
            });
            Document.PropertyChanged += documentPropertyChanged;
        }
コード例 #21
0
        /// <summary>
        /// Method is export to selected records in SfDataGrid to Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnExportSelectedExcel(object sender, RoutedEventArgs e)
        {
            ExcelEngine excelEngine = new ExcelEngine();
            var         workBook    = excelEngine.Excel.Workbooks.Create();

            workBook.Version = ExcelVersion.Excel2010;
            workBook.Worksheets.Create();
            if ((bool)this.customizeSelectedRow.IsChecked)
            {
                this.dataGrid.ExportToExcel(this.dataGrid.SelectedItems, new ExcelExportingOptions()
                {
                    CellsExportingEventHandler = CellExportingHandler,
                    ExportingEventHandler      = CustomizedexportingHandler
                }, workBook.Worksheets[0]);
            }
            else
            {
                this.dataGrid.ExportToExcel(this.dataGrid.SelectedItems, new ExcelExportingOptions()
                {
                    CellsExportingEventHandler = CellExportingHandler,
                    ExportingEventHandler      = exportingHandler
                }, workBook.Worksheets[0]);
            }

            workBook = excelEngine.Excel.Workbooks[0];
            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.Desktop,
                SuggestedFileName      = "Sample"
            };

            if (workBook.Version == ExcelVersion.Excel97to2003)
            {
                savePicker.FileTypeChoices.Add("Excel File (.xls)", new List <string>()
                {
                    ".xls"
                });
            }
            else
            {
                savePicker.FileTypeChoices.Add("Excel File (.xlsx)", new List <string>()
                {
                    ".xlsx"
                });
            }

            var storageFile = await savePicker.PickSaveFileAsync();

            if (storageFile != null)
            {
                await workBook.SaveAsAsync(storageFile);

                var msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

                var yesCmd = new UICommand("Yes");
                var noCmd  = new UICommand("No");
                msgDialog.Commands.Add(yesCmd);
                msgDialog.Commands.Add(noCmd);
                var cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
                }
            }
            excelEngine.Dispose();
        }
コード例 #22
0
        /// <summary>
        /// The event handler is invoked when clicking the button.
        /// </summary>
        /// <param name="sender">The button.</param>
        /// <param name="e">The event argument.</param>
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SfPivotGrid    pivot        = parentGrid.Children[0] as SfPivotGrid;
            Button         exportButton = e.OriginalSource as Button;
            FileSavePicker savePicker   = new FileSavePicker();

            savePicker.SuggestedFileName = "Sample";
            switch (exportButton.Content.ToString())
            {
            case "Export To CSV":

            {
                ExportPivotGridToCsv csvExport = null;
                if (pivot.OlapDataManager == null)
                {
                    csvExport = new ExportPivotGridToCsv(pivot);
                }
                else
                {
                    csvExport = new ExportPivotGridToCsv(pivot.OlapDataManager.PivotEngine);
                }
                csvExport.ExportToDocument("Sample");
            }
            break;

            case "Export To PDF":
            {
                ExportingGridStyleInfo gridStyleInfo = pivotGrid.GridStyleInfo ?? pivotGrid.GetExportingGridStyleInfo();

                ExportPivotGridToPdf pdfExport = null;
                if (pivot.OlapDataManager == null)
                {
                    pdfExport = new ExportPivotGridToPdf(pivot, gridStyleInfo);
                }
                else
                {
                    pdfExport = new ExportPivotGridToPdf(pivot.OlapDataManager.PivotEngine, gridStyleInfo);
                }
                pdfExport.ExportToDocument("Sample");
            }
            break;

            case "Export To Word":
            {
                ExportingGridStyleInfo gridStyleInfo = pivotGrid.GridStyleInfo ?? pivotGrid.GetExportingGridStyleInfo();
                ExportPivotGridToWord  wordExport    = null;
                if (pivot.OlapDataManager == null)
                {
                    wordExport = new ExportPivotGridToWord(pivot, gridStyleInfo);
                }
                else
                {
                    wordExport = new ExportPivotGridToWord(pivot.OlapDataManager.PivotEngine, pivot.Layout, gridStyleInfo);
                }
                wordExport.ExportToDocument("Sample");
            }
            break;

            case "Export To Excel":
            {
                ExportingGridStyleInfo gridStyleInfo = pivotGrid.GridStyleInfo ?? pivotGrid.GetExportingGridStyleInfo();
                ExportPivotGridToExcel excelExport   = null;
                if (pivot.OlapDataManager == null)
                {
                    excelExport = new ExportPivotGridToExcel(pivot, gridStyleInfo, "xlsx", true);
                }
                else
                {
                    excelExport = new ExportPivotGridToExcel(pivot.OlapDataManager.PivotEngine, gridStyleInfo, pivot.Layout, "xlsx", true);
                }
                excelExport.ExportToDocument("Sample");
            }
            break;
            }
        }
コード例 #23
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            StorageFile storageFile;
            string      fileName = "Funnel_Chart.xlsx";

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = fileName;
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("Funnel_Chart.xlsx", CreationCollisionOption.ReplaceExisting);
            }

            if (storageFile == null)
            {
                return;
            }


            #region Initializing Workbook
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            //Step 1 : Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();
            //Step 2 : Instantiate the Excel application object.
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2016;

            Assembly  assembly     = typeof(FunnelChart).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.FunnelChartTemplate.xlsx";
            Stream    fileStream   = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook     = await application.Workbooks.OpenAsync(fileStream);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];
            #endregion

            #region Chart Creation
            IChart chart = null;

            if (this.rdBtnSheet.IsChecked != null && this.rdBtnSheet.IsChecked.Value)
            {
                chart = workbook.Charts.Add();
            }
            else
            {
                chart = workbook.Worksheets[0].Charts.Add();
            }

            #region Funnel Chart Settings
            chart.ChartType  = ExcelChartType.Funnel;
            chart.DataRange  = sheet["A2:B8"];
            chart.ChartTitle = "Sales Pipeline";
            chart.Series[0].DataPoints.DefaultDataPoint.DataLabels.IsValue = true;
            chart.Series[0].DataPoints.DefaultDataPoint.DataLabels.Size    = 8.5;
            chart.Series[0].SerieFormat.CommonSerieOptions.GapWidth        = 100;
            #endregion

            chart.Legend.Position = ExcelLegendPosition.Right;

            if (this.rdBtnSheet.IsChecked != null && this.rdBtnSheet.IsChecked.Value)
            {
                chart.Activate();
            }
            else
            {
                workbook.Worksheets[0].Activate();
                IChartShape chartShape = chart as IChartShape;
                chartShape.TopRow      = 2;
                chartShape.BottomRow   = 19;
                chartShape.LeftColumn  = 4;
                chartShape.RightColumn = 11;
            }
            #endregion

            #region Saving the workbook
            await workbook.SaveAsAsync(storageFile);

            workbook.Close();
            excelEngine.Dispose();
            #endregion

            #region Launching the saved workbook
            MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

            UICommand yesCmd = new UICommand("Yes");
            msgDialog.Commands.Add(yesCmd);
            UICommand noCmd = new UICommand("No");
            msgDialog.Commands.Add(noCmd);
            IUICommand cmd = await msgDialog.ShowAsync();

            if (cmd == yesCmd)
            {
                // Launch the saved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
            }
            #endregion
        }
        /// <summary>
        /// Command for downloading and viewing a file.
        /// </summary>
        async void ExecuteDownloadFileCommandAsync()
        {
            StorageFile downloadedFile = null;

            if (_selectedFileObject.FileSystemItem is Folder)
            {
                LoggingViewModel.Instance.Information = "We can't download a folder";
                return;
            }

            var stream = await _fileOperations.DownloadFileAsync(_selectedFileObject);

            // Save the file.
            FileSavePicker fsp = new FileSavePicker();

            fsp.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;

            fsp.FileTypeChoices.Add("Text", new List <string>()
            {
                ".txt"
            });
            fsp.FileTypeChoices.Add("Word document", new List <string>()
            {
                ".docx"
            });
            fsp.FileTypeChoices.Add("Excel workbook", new List <string>()
            {
                ".xslx"
            });
            fsp.FileTypeChoices.Add("Powerpoint", new List <string>()
            {
                ".pptx"
            });
            fsp.FileTypeChoices.Add("XML", new List <string>()
            {
                ".xml"
            });
            fsp.FileTypeChoices.Add("JPEG", new List <string>()
            {
                ".jpg"
            });
            fsp.FileTypeChoices.Add("PNG", new List <string>()
            {
                ".png"
            });
            fsp.FileTypeChoices.Add("PDF", new List <string>()
            {
                ".pdf"
            });
            fsp.SuggestedFileName = _selectedFileObject.Name;

            StorageFile sFile = await fsp.PickSaveFileAsync();

            if (sFile != null && stream != null)
            {
                CachedFileManager.DeferUpdates(sFile);

                using (Stream s = await sFile.OpenStreamForWriteAsync())
                {
                    int count = 0;
                    do
                    {
                        var buffer = new byte[2048];
                        count = stream.Read(buffer, 0, 2048);
                        await s.WriteAsync(buffer, 0, count);
                    }while (stream.CanRead && count > 0);

                    await s.FlushAsync();
                }

                stream.Dispose();

                downloadedFile = sFile;
            }

            if (downloadedFile != null)
            {
                if (await MessageDialogHelper.ShowYesNoDialogAsync(String.Format("Your file was downloaded to {0}\nWould you like to open the file?", downloadedFile.Path), "Download Succeeded"))
                {
                    // Try to launch the default app for the file, so the user can see it
                    try
                    {
                        // Set the option to show the picker
                        var options = new Windows.System.LauncherOptions();
                        options.DisplayApplicationPicker = true;

                        await Windows.System.Launcher.LaunchFileAsync(downloadedFile, options);
                    }
                    catch (Exception)
                    {
                        // Fail silently
                    }
                }
            }
            else
            {
                LoggingViewModel.Instance.Information = "The file wasn't downloaded.";
            }
        }
コード例 #25
0
        public async Task SaveTextAsync(string filename, string contentType, MemoryStream stream)
        {
            if (Device.Idiom != TargetIdiom.Desktop)
            {
                StorageFolder local   = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFile   outFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                using (Stream outStream = await outFile.OpenStreamForWriteAsync())
                {
                    outStream.Write(stream.ToArray(), 0, (int)stream.Length);
                }
                if (contentType != "application/html")
                {
                    await Windows.System.Launcher.LaunchFileAsync(outFile);
                }
            }
            else
            {
                StorageFile    storageFile = null;
                FileSavePicker savePicker  = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = filename;
                switch (contentType)
                {
                case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                    savePicker.FileTypeChoices.Add("PowerPoint Presentation", new List <string>()
                    {
                        ".pptx",
                    });
                    break;

                case "application/msexcel":
                    savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                    {
                        ".xlsx",
                    });
                    break;

                case "application/msword":
                    savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                    {
                        ".docx"
                    });
                    break;

                case "application/pdf":
                    savePicker.FileTypeChoices.Add("Adobe PDF Document", new List <string>()
                    {
                        ".pdf"
                    });
                    break;

                case "application/html":
                    savePicker.FileTypeChoices.Add("HTML Files", new List <string>()
                    {
                        ".html"
                    });
                    break;
                }
                storageFile = await savePicker.PickSaveFileAsync();

                using (Stream outStream = await storageFile.OpenStreamForWriteAsync())
                {
                    outStream.Write(stream.ToArray(), 0, (int)stream.Length);
                }

                await Windows.System.Launcher.LaunchFileAsync(storageFile);
            }
        }
コード例 #26
0
        private async void SaveAs_Click(SplitButton sender, SplitButtonClickEventArgs args)
        {
            FileSavePicker Picker = new FileSavePicker
            {
                SuggestedFileName      = Path.GetFileNameWithoutExtension(OriginFile.Name),
                SuggestedStartLocation = PickerLocationId.Desktop
            };

            Picker.FileTypeChoices.Add($"PNG {Globalization.GetString("Transcode_Dialog_Format_Text")}", new List <string>()
            {
                ".png"
            });
            Picker.FileTypeChoices.Add($"JPEG {Globalization.GetString("Transcode_Dialog_Format_Text")}", new List <string>()
            {
                ".jpg"
            });
            Picker.FileTypeChoices.Add($"BMP {Globalization.GetString("Transcode_Dialog_Format_Text")}", new List <string>()
            {
                ".bmp"
            });
            Picker.FileTypeChoices.Add($"GIF {Globalization.GetString("Transcode_Dialog_Format_Text")}", new List <string>()
            {
                ".gif"
            });
            Picker.FileTypeChoices.Add($"TIFF {Globalization.GetString("Transcode_Dialog_Format_Text")}", new List <string>()
            {
                ".tiff"
            });

            StorageFile File = await Picker.PickSaveFileAsync();

            if (File != null)
            {
                LoadingControl.IsLoading = true;

                using (IRandomAccessStream Stream = await File.OpenAsync(FileAccessMode.ReadWrite))
                {
                    Stream.Size = 0;
                    switch (File.FileType)
                    {
                    case ".png":
                        await Cropper.SaveAsync(Stream, BitmapFileFormat.Png).ConfigureAwait(true);

                        break;

                    case ".jpg":
                    case ".jpeg":
                        await Cropper.SaveAsync(Stream, BitmapFileFormat.Jpeg).ConfigureAwait(true);

                        break;

                    case ".bmp":
                        await Cropper.SaveAsync(Stream, BitmapFileFormat.Bmp).ConfigureAwait(true);

                        break;

                    case ".gif":
                        await Cropper.SaveAsync(Stream, BitmapFileFormat.Gif).ConfigureAwait(true);

                        break;

                    case ".tiff":
                        await Cropper.SaveAsync(Stream, BitmapFileFormat.Tiff).ConfigureAwait(true);

                        break;

                    default:
                        throw new InvalidOperationException("Unsupport image format");
                    }
                }

                await Task.Delay(1000).ConfigureAwait(true);

                LoadingControl.IsLoading = false;

                Frame.GoBack();
            }
        }
コード例 #27
0
ファイル: Filters.xaml.cs プロジェクト: WangHengXu/uwp-demos
        private async void btnGenerateExcel_Click_2(object sender, RoutedEventArgs e)
        {
            #region Workbook initialization
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2013;

            Assembly assembly = typeof(Filters).GetTypeInfo().Assembly;
            string   resourcePath;
            if (comboBox1.SelectedIndex == 6)
            {
                resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.AdvancedFilterTemplate.xlsx";
            }
            else if (comboBox1.SelectedIndex == 5)
            {
                resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.IconFilterData.xlsx";
            }
            else if (comboBox1.SelectedIndex == 4)
            {
                resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.FilterData_Color.xlsx";
            }
            else
            {
                resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.FilterData.xlsx";
            }
            Stream    fileStream = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook   = await application.Workbooks.OpenAsync(fileStream);

            #endregion

            #region sorting the data
            workbook.Version = ExcelVersion.Excel2007;
            IWorksheet sheet = workbook.Worksheets[0];
            if (comboBox1.SelectedIndex != 6)
            {
                sheet.AutoFilters.FilterRange = sheet.Range[1, 1, 49, 3];
            }
            string sortOn      = comboBox1.SelectedValue as string;
            int    columnIndex = GetSelectedIndex(sortOn);
            string fileName    = "DataSortSample";
            switch (columnIndex)
            {
            case 0:
                fileName = "CustomFilter";
                IAutoFilter filter1 = sheet.AutoFilters[0];
                filter1.IsAnd = false;
                filter1.FirstCondition.ConditionOperator = ExcelFilterCondition.Equal;
                filter1.FirstCondition.DataType          = ExcelFilterDataType.String;
                filter1.FirstCondition.String            = "Owner";

                filter1.SecondCondition.ConditionOperator = ExcelFilterCondition.Equal;
                filter1.SecondCondition.DataType          = ExcelFilterDataType.String;
                filter1.SecondCondition.String            = "Sales Representative";
                break;

            case 1:
                fileName = "TextFilter";
                IAutoFilter filter2 = sheet.AutoFilters[0];
                filter2.AddTextFilter(new string[] { "Owner", "Sales Representative", "Sales Associate" });
                break;

            case 2:
                fileName = "DateTimeFilter";
                IAutoFilter filter3 = sheet.AutoFilters[1];
                filter3.AddDateFilter(new DateTime(2004, 9, 1, 1, 0, 0, 0), DateTimeGroupingType.month);
                filter3.AddDateFilter(new DateTime(2011, 1, 1, 1, 0, 0, 0), DateTimeGroupingType.year);
                break;

            case 3:
                fileName = "DynamicFilter";
                IAutoFilter filter4 = sheet.AutoFilters[1];
                filter4.AddDynamicFilter(DynamicFilterType.Quarter1);
                break;

            case 4:
                fileName = "ColorFilter";
                #region ColorFilter
                sheet.AutoFilters.FilterRange = sheet["A1:C49"];
                Windows.UI.Color color = new Windows.UI.Color();
                switch (comboBox2.SelectedIndex)
                {
                case 0:
                    color = Windows.UI.Color.FromArgb(255, 255, 0, 0);
                    break;

                case 1:
                    color = Windows.UI.Color.FromArgb(255, 0, 0, 255);
                    break;

                case 2:
                    color = Windows.UI.Color.FromArgb(255, 0, 128, 0);
                    break;

                case 3:
                    color = Windows.UI.Color.FromArgb(255, 255, 255, 0);
                    break;

                case 4:
                    //do nothing
                    break;
                }

                if (rdb3.IsChecked == true)
                {
                    IAutoFilter filter = sheet.AutoFilters[2];
                    filter.AddColorFilter(color, ExcelColorFilterType.FontColor);
                }
                else
                {
                    IAutoFilter filter = sheet.AutoFilters[0];
                    filter.AddColorFilter(color, ExcelColorFilterType.CellColor);
                }
                #endregion
                break;

            case 5:
                fileName = "IconFilter";
                #region IconFilter
                sheet.AutoFilters.FilterRange = sheet["A4:D44"];
                ExcelIconSetType iconSet = ExcelIconSetType.FiveArrows;
                int icon        = 0;
                int filterIndex = 0;
                switch (iconSetType.SelectedIndex)
                {
                case 0:
                    iconSet     = ExcelIconSetType.ThreeSymbols;
                    filterIndex = 3;
                    break;

                case 1:
                    iconSet     = ExcelIconSetType.FourRating;
                    filterIndex = 1;
                    break;

                case 2:
                    iconSet     = ExcelIconSetType.FiveArrows;
                    filterIndex = 2;
                    break;
                }
                switch (iconId.SelectedIndex)
                {
                case 0:
                    //Do nothing
                    break;

                case 1:
                    icon = 1;
                    break;

                case 2:
                    icon = 2;
                    break;

                case 3:
                    if (iconSetType.SelectedIndex == 0)
                    {
                        iconSet = (ExcelIconSetType)(-1);
                    }
                    else
                    {
                        icon = 3;
                    }
                    break;

                case 4:
                    if (iconSetType.SelectedIndex == 1)
                    {
                        iconSet = (ExcelIconSetType)(-1);
                    }
                    else
                    {
                        icon = 4;
                    }
                    break;

                case 5:
                    iconSet = (ExcelIconSetType)(-1);
                    break;
                }
                IAutoFilter filter5 = sheet.AutoFilters[filterIndex];
                filter5.AddIconFilter(iconSet, icon);

                #endregion
                break;

            case 6:
                fileName = "AdvancedFilter";
                #region AdvancedFilter

                IRange filterRange   = sheet.Range["A8:G51"];
                IRange criteriaRange = sheet.Range["A2:B5"];
                if (rdb1.IsChecked == true)
                {
                    sheet.AdvancedFilter(ExcelFilterAction.FilterInPlace, filterRange, criteriaRange, null, checkbox1.IsChecked == true);
                }
                else if (rdb2.IsChecked == true)
                {
                    IRange range = sheet.Range["I7:O7"];
                    range.Merge();
                    range.Text = "FilterCopy";
                    range.CellStyle.Font.RGBColor = Windows.UI.Color.FromArgb(0, 0, 112, 192);
                    range.HorizontalAlignment     = ExcelHAlign.HAlignCenter;
                    range.CellStyle.Font.Bold     = true;
                    IRange copyRange = sheet.Range["I8"];
                    sheet.AdvancedFilter(ExcelFilterAction.FilterCopy, filterRange, criteriaRange, copyRange, checkbox1.IsChecked == true);
                }
                break;
                #endregion
            }
            #endregion


            #region Save the Workbook
            StorageFile storageFile;
            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = fileName;
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync(fileName + ".xlsx", CreationCollisionOption.ReplaceExisting);
            }


            if (storageFile != null)
            {
                //Saving the workbook
                await workbook.SaveAsAsync(storageFile);

                workbook.Close();
                excelEngine.Dispose();

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been saved successfully.");

                UICommand yesCmd = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
                }
            }
            else
            {
                workbook.Close();
                excelEngine.Dispose();
            }
            #endregion
        }
コード例 #28
0
        /// <summary>
        /// Registers commands for UI elements
        /// </summary>
        private void RegisterCommands()
        {
            // Handle add category
            AddCategoryCommand = new Command(async(p) =>
            {
                // Prompt for name
                await DialogHelper.ShowClosableDialog <NamePromptDialog>(async(d) =>
                {
                    try
                    {
                        //create new category
                        var category = new ApiCategory()
                        {
                            Name  = d.Value,
                            Items = new ApiItem[] { }
                        };

                        // Send the category to the api
                        var resp = await KryptPadApi.SaveCategoryAsync(category);

                        // Set the id of the newly created category
                        category.Id = resp.Id;

                        // Add the category to the list
                        Categories.Add(category);

                        // Add view to the ItemsView object
                        ItemsView.Source = Categories;

                        // Refresh
                        OnPropertyChanged(nameof(ItemsView));

                        // Hide empty message
                        EmptyMessageVisibility = Visibility.Collapsed;
                    }
                    catch (WebException ex)
                    {
                        // Something went wrong in the api
                        await DialogHelper.ShowMessageDialogAsync(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        // Failed
                        await DialogHelper.ShowGenericErrorDialogAsync(ex);
                    }
                }, "Add Category");
            });

            // Handle add new item
            AddItemCommand = new Command(AddItemCommandHandler);

            // Handle item click
            ItemClickCommand = new Command((p) =>
            {
                var item     = p as ApiItem;
                var category = (from c in Categories
                                where c.Items.Contains(item)
                                select c).FirstOrDefault();

                // Navigate to edit
                NavigationHelper.Navigate(typeof(NewItemPage),
                                          new EditItemPageParams()
                {
                    Category = category,
                    Item     = item
                });
            });

            // Handle change passphrase command
            ChangePassphraseCommand = new Command(async(p) =>
            {
                var dialog = new ChangePassphraseDialog();

                await dialog.ShowAsync();
            });

            // Handle rename command
            RenameProfileCommand = new Command(async(p) =>
            {
                // Prompt for name
                await DialogHelper.GetValueAsync(async(d) =>
                {
                    try
                    {
                        // Set new name
                        var profile  = KryptPadApi.CurrentProfile;
                        profile.Name = d.Value;

                        // Send the category to the api
                        var resp = await KryptPadApi.SaveProfileAsync(profile);
                    }
                    catch (WebException ex)
                    {
                        // Something went wrong in the api
                        await DialogHelper.ShowMessageDialogAsync(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        // Failed
                        await DialogHelper.ShowGenericErrorDialogAsync(ex);
                    }
                }, "RENAME PROFILE", KryptPadApi.CurrentProfile.Name);
            });

            // Handle delete command
            DeleteProfileCommand = new Command(async(p) =>
            {
                var res = await DialogHelper.Confirm(
                    "All of your data in this profile will be deleted permanently. THIS ACTION CANNOT BE UNDONE. Are you sure you want to delete this entire profile?",
                    "WARNING - CONFIRM DELETE",
                    async(ap) =>
                {
                    try
                    {
                        // Delete the selected profile
                        await KryptPadApi.DeleteProfileAsync(KryptPadApi.CurrentProfile);

                        // Navigate back to the profiles list
                        NavigationHelper.Navigate(typeof(SelectProfilePage), null);
                    }
                    catch (WebException ex)
                    {
                        // Something went wrong in the api
                        await DialogHelper.ShowMessageDialogAsync(ex.Message);
                    }
                    catch (Exception ex)
                    {
                        // Failed
                        await DialogHelper.ShowGenericErrorDialogAsync(ex);
                    }
                }
                    );
            });

            // Download profile handler
            DownloadProfileCommand = new Command(async(prop) =>
            {
                try
                {
                    // Prompt for a place to save the file
                    var sfd = new FileSavePicker()
                    {
                        SuggestedFileName = KryptPadApi.CurrentProfile.Name,
                    };

                    //sfd.FileTypeChoices.Add("KryptPad Document Format", new List<string>(new[] { ".kdf" }));
                    sfd.FileTypeChoices.Add("KryptPad Document Format", new[] { ".kdf" });

                    // Show the picker
                    var file = await sfd.PickSaveFileAsync();

                    if (file != null)
                    {
                        // Get profile
                        var profileData = await KryptPadApi.DownloadCurrentProfileAsync();

                        // Save profile to file
                        using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                            using (var sw = new StreamWriter(fs.AsStreamForWrite()))
                            {
                                // Write the data
                                sw.Write(profileData);
                            }

                        await DialogHelper.ShowMessageDialogAsync("Profile downloaded successfully");
                    }
                }
                catch (WebException ex)
                {
                    // Something went wrong in the api
                    await DialogHelper.ShowMessageDialogAsync(ex.Message);
                }
                catch (Exception ex)
                {
                    // Failed
                    await DialogHelper.ShowGenericErrorDialogAsync(ex);
                }
            });

            // Handle category rename
            RenameCategoryCommand = new Command(RenameCategoryCommandHandler);

            // Handle category delete
            DeleteCategoryCommand = new Command(DeleteCategoryCommandHandler);

            // Handle selection mode
            SelectModeCommand = new Command(SelectModeCommandHandler);

            // Handle the move command
            MoveItemsCommand = new Command(MoveItemsCommandHandler, CanMoveItems);

            // Handle setting favorites
            SetFavoriteCommand = new Command(SetFavoriteCommandHandler);
        }
コード例 #29
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            #region Workbook initialization
            //New instance of XlsIO is created.[Equivalent to launching MS Excel with no workbooks open].
            //The instantiation process consists of two steps.

            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

            application.DefaultVersion = ExcelVersion.Excel2013;

            Assembly  assembly     = typeof(FindAndReplace).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.ReplaceOptions.xlsx";
            Stream    fileStream   = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook     = await application.Workbooks.OpenAsync(fileStream);

            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet worksheet = workbook.Worksheets[0];
            worksheet.UsedRange.AutofitColumns();
            #endregion

            #region Save the Workbook
            StorageFile storageFile;
            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
                savePicker.SuggestedFileName      = "InputTemplate";
                savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("InputTemplate.xlsx", CreationCollisionOption.ReplaceExisting);
            }


            if (storageFile != null)
            {
                //Saving the workbook
                await workbook.SaveAsAsync(storageFile);

                workbook.Close();
                excelEngine.Dispose();

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been saved successfully.");

                UICommand yesCmd = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(storageFile);
                }
            }
            else
            {
                workbook.Close();
                excelEngine.Dispose();
            }
            #endregion
        }
コード例 #30
0
        private async void toCSV()
        {
            FileSavePicker savePicker = new FileSavePicker();

            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

            // Dropdown of file types the user can save the file as
            savePicker.FileTypeChoices.Add("CSV", new List <string>()
            {
                ".csv"
            });
            savePicker.FileTypeChoices.Add("Plain Text", new List <string>()
            {
                ".txt"
            });

            // Default file name if the user does not type one in or select a file to replace
            savePicker.SuggestedFileName = "Exported_Readings";

            StorageFile file = await savePicker.PickSaveFileAsync();

            if (file != null)
            {
                // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                CachedFileManager.DeferUpdates(file);

                // write to file
                await FileIO.WriteTextAsync(file, "\"Time\",\"Heart Rate\"\n");

                foreach (Reading reading in readingList)
                {
                    await FileIO.AppendTextAsync(file, reading.date + "," + reading.rate + "\n");
                }

                // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
                // Completing updates may require Windows to ask for user input.
                FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                if (status == FileUpdateStatus.Complete)
                {
                    //OutputTextBlock.Text = "File " + file.Name + " was saved.";

                    ToastTemplateType toastType = ToastTemplateType.ToastText02;

                    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastType);

                    XmlNodeList toastTextElement = toastXml.GetElementsByTagName("text");
                    toastTextElement[0].AppendChild(toastXml.CreateTextNode("Band Graph Success"));
                    toastTextElement[1].AppendChild(toastXml.CreateTextNode("File " + file.Name + " was saved."));

                    IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
                    ((XmlElement)toastNode).SetAttribute("duration", "long");

                    ToastNotification toast = new ToastNotification(toastXml);
                    ToastNotificationManager.CreateToastNotifier().Show(toast);
                }
                else
                {
                    ToastTemplateType toastType = ToastTemplateType.ToastText02;

                    XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastType);

                    XmlNodeList toastTextElement = toastXml.GetElementsByTagName("text");
                    toastTextElement[0].AppendChild(toastXml.CreateTextNode("Band Graph Failure"));
                    toastTextElement[1].AppendChild(toastXml.CreateTextNode("File " + file.Name + " was not saved."));

                    IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
                    ((XmlElement)toastNode).SetAttribute("duration", "long");

                    ToastNotification toast = new ToastNotification(toastXml);
                    ToastNotificationManager.CreateToastNotifier().Show(toast);
                }
            }
            else
            {
                //OutputTextBlock.Text = "Operation cancelled.";
            }
        }
コード例 #31
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            WordDocument document = new WordDocument();
            //Open an existing word document.
            await document.OpenAsync(file);

            if (FindTextBox.Text.Trim() == string.Empty || ReplaceTextBox.Text.Trim() == string.Empty)
            {
                MessageDialog msgDialog = new MessageDialog("Please fill the find and replacement text in appropriate textboxes...");
                UICommand     okCmd     = new UICommand("Ok");
                msgDialog.Commands.Add(okCmd);
                IUICommand cmd = await msgDialog.ShowAsync();
            }
            else
            {
                document.Replace(FindTextBox.Text, ReplaceTextBox.Text, chkBoxMatchCase.IsChecked.Value, chkBoxWholeWord.IsChecked.Value);
                StorageFile stgFile = null;
                if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
                {
                    FileSavePicker savePicker = new FileSavePicker();
                    savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                    savePicker.SuggestedFileName      = "Sample";

                    if (rdDoc.IsChecked.Value)
                    {
                        savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                        {
                            ".doc"
                        });
                        stgFile = await savePicker.PickSaveFileAsync();

                        if (stgFile != null)
                        {
                            await document.SaveAsync(stgFile, FormatType.Doc);
                        }
                    }
                    else
                    {
                        savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                        {
                            ".docx"
                        });
                        stgFile = await savePicker.PickSaveFileAsync();

                        if (stgFile != null)
                        {
                            await document.SaveAsync(stgFile, FormatType.Docx);
                        }
                    }
                }
                else
                {
                    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                    stgFile = await local.CreateFileAsync("WordDocument.docx", CreationCollisionOption.ReplaceExisting);

                    if (stgFile != null)
                    {
                        await document.SaveAsync(stgFile, FormatType.Docx);
                    }
                }
                if (stgFile != null)
                {
                    MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");
                    UICommand     yesCmd    = new UICommand("Yes");
                    msgDialog.Commands.Add(yesCmd);
                    UICommand noCmd = new UICommand("No");
                    msgDialog.Commands.Add(noCmd);
                    IUICommand cmd = await msgDialog.ShowAsync();

                    if (cmd == yesCmd)
                    {
                        // Launch the retrieved file
                        bool success = await Windows.System.Launcher.LaunchFileAsync(stgFile);
                    }
                }
            }
        }
コード例 #32
0
        /// <summary>
        /// Creates PDF
        /// </summary>
        public async void CreatePDF(IList <InvoiceItem> dataSource, BillingInformation billInfo, double totalDue)
        {
            PdfDocument document = new PdfDocument();

            document.PageSettings.Orientation = PdfPageOrientation.Portrait;
            document.PageSettings.Margins.All = 50;
            PdfPage        page    = document.Pages.Add();
            PdfGraphics    g       = page.Graphics;
            PdfTextElement element = new PdfTextElement(@"Syncfusion Software 
2501 Aerial Center Parkway 
Suite 200 Morrisville, NC 27560 USA 
Tel +1 888.936.8638 Fax +1 919.573.0306");

            element.Font  = new PdfStandardFont(PdfFontFamily.TimesRoman, 12);
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            PdfLayoutResult result = element.Draw(page, new RectangleF(0, 0, page.Graphics.ClientSize.Width / 2, 200));

            Stream imgStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Invoice.Assets.SyncfusionLogo.jpg");

            PdfImage img = PdfImage.FromStream(imgStream);

            page.Graphics.DrawImage(img, new RectangleF(g.ClientSize.Width - 200, result.Bounds.Y, 190, 45));
            PdfFont subHeadingFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 14);

            g.DrawRectangle(new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(0, result.Bounds.Bottom + 40, g.ClientSize.Width, 30));
            element       = new PdfTextElement("INVOICE " + billInfo.InvoiceNumber.ToString(), subHeadingFont);
            element.Brush = PdfBrushes.White;
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 48));
            string currentDate = "DATE " + billInfo.Date.ToString("d");
            SizeF  textSize    = subHeadingFont.MeasureString(currentDate);

            g.DrawString(currentDate, subHeadingFont, element.Brush, new PointF(g.ClientSize.Width - textSize.Width - 10, result.Bounds.Y));

            element       = new PdfTextElement("BILL TO ", new PdfStandardFont(PdfFontFamily.TimesRoman, 12));
            element.Brush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            result        = element.Draw(page, new PointF(10, result.Bounds.Bottom + 25));

            g.DrawLine(new PdfPen(new PdfColor(34, 83, 142), 0.70f), new PointF(0, result.Bounds.Bottom + 3), new PointF(g.ClientSize.Width, result.Bounds.Bottom + 3));

            element       = new PdfTextElement(billInfo.Name, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 5, g.ClientSize.Width / 2, 100));

            element       = new PdfTextElement(billInfo.Address, new PdfStandardFont(PdfFontFamily.TimesRoman, 11));
            element.Brush = new PdfSolidBrush(new PdfColor(0, 0, 0));
            result        = element.Draw(page, new RectangleF(10, result.Bounds.Bottom + 3, g.ClientSize.Width / 2, 100));
            string[] headers = new string[] { "Item", "Quantity", "Rate", "Taxes", "Amount" };
            PdfGrid  grid    = new PdfGrid();

            grid.Columns.Add(headers.Length);
            //Adding headers in to the grid
            grid.Headers.Add(1);
            PdfGridRow headerRow = grid.Headers[0];
            int        count     = 0;

            foreach (string columnName in headers)
            {
                headerRow.Cells[count].Value = columnName;
                count++;
            }
            //Adding rows into the grid
            foreach (var item in dataSource)
            {
                PdfGridRow row = grid.Rows.Add();
                row.Cells[0].Value = item.ItemName;
                row.Cells[1].Value = item.Quantity.ToString();
                row.Cells[2].Value = "$" + item.Rate.ToString("#,###.00", CultureInfo.InvariantCulture);
                row.Cells[3].Value = "$" + item.Taxes.ToString("#,###.00", CultureInfo.InvariantCulture);
                row.Cells[4].Value = "$" + item.TotalAmount.ToString("#,###.00", CultureInfo.InvariantCulture);
            }

            PdfGridCellStyle cellStyle = new PdfGridCellStyle();

            cellStyle.Borders.All = PdfPens.White;
            PdfGridRow header = grid.Headers[0];

            PdfGridCellStyle headerStyle = new PdfGridCellStyle();

            headerStyle.Borders.All     = new PdfPen(new PdfColor(34, 83, 142));
            headerStyle.BackgroundBrush = new PdfSolidBrush(new PdfColor(34, 83, 142));
            headerStyle.TextBrush       = PdfBrushes.White;
            headerStyle.Font            = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            for (int i = 0; i < header.Cells.Count; i++)
            {
                if (i == 0)
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                }
                else
                {
                    header.Cells[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                }
            }

            header.Cells[0].Value = "ITEM";
            header.Cells[1].Value = "QUANTITY";
            header.Cells[2].Value = "RATE";
            header.Cells[3].Value = "TAXES";
            header.Cells[4].Value = "AMOUNT";
            header.ApplyStyle(headerStyle);
            grid.Columns[0].Width    = 180;
            cellStyle.Borders.Bottom = new PdfPen(new PdfColor(34, 83, 142), 0.70f);
            cellStyle.Font           = new PdfStandardFont(PdfFontFamily.TimesRoman, 11f);
            cellStyle.TextBrush      = new PdfSolidBrush(new PdfColor(0, 0, 0));
            foreach (PdfGridRow row in grid.Rows)
            {
                row.ApplyStyle(cellStyle);
                for (int i = 0; i < row.Cells.Count; i++)
                {
                    PdfGridCell cell = row.Cells[i];
                    if (i == 0)
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
                    }
                    else
                    {
                        cell.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Middle);
                    }

                    if (i > 1)
                    {
                        if (cell.Value.ToString().Contains("$"))
                        {
                            cell.Value = cell.Value.ToString();
                        }
                        else
                        {
                            if (cell.Value is double)
                            {
                                cell.Value = "$" + ((double)cell.Value).ToString("#,###.00", CultureInfo.InvariantCulture);
                            }
                            else
                            {
                                cell.Value = "$" + cell.Value.ToString();
                            }
                        }
                    }
                }
            }

            PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

            layoutFormat.Layout = PdfLayoutType.Paginate;

            PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, result.Bounds.Bottom + 40), new SizeF(g.ClientSize.Width, g.ClientSize.Height - 100)), layoutFormat);
            float pos = 0.0f;

            for (int i = 0; i < grid.Columns.Count - 1; i++)
            {
                pos += grid.Columns[i].Width;
            }

            PdfFont font = new PdfStandardFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);

            gridResult.Page.Graphics.DrawString("TOTAL DUE", font, new PdfSolidBrush(new PdfColor(34, 83, 142)), new RectangleF(new PointF(pos, gridResult.Bounds.Bottom + 10), new SizeF(grid.Columns[3].Width - pos, 20)), new PdfStringFormat(PdfTextAlignment.Right));
            gridResult.Page.Graphics.DrawString("Thank you for your business!", new PdfStandardFont(PdfFontFamily.TimesRoman, 12), new PdfSolidBrush(new PdfColor(0, 0, 0)), new PointF(pos - 210, gridResult.Bounds.Bottom + 60));
            pos += grid.Columns[4].Width;
            gridResult.Page.Graphics.DrawString("$" + totalDue.ToString("#,###.00", CultureInfo.InvariantCulture), font, new PdfSolidBrush(new PdfColor(0, 0, 0)), new RectangleF(pos, gridResult.Bounds.Bottom + 10, grid.Columns[4].Width - pos, 20), new PdfStringFormat(PdfTextAlignment.Right));
            StorageFile stFile = null;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.DefaultFileExtension = ".pdf";
                savePicker.SuggestedFileName    = "Invoice";
                savePicker.FileTypeChoices.Add("Adobe PDF Document", new List <string>()
                {
                    ".pdf"
                });
                stFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                stFile = await local.CreateFileAsync("Invoice.pdf", CreationCollisionOption.ReplaceExisting);
            }

            if (stFile != null)
            {
                Stream stream = await stFile.OpenStreamForWriteAsync();

                await document.SaveAsync(stream);

                stream.Flush();
                stream.Dispose();
                document.Close(true);

                MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File has been created successfully.");

                UICommand yesCmd = new UICommand("Yes");
                msgDialog.Commands.Add(yesCmd);
                UICommand noCmd = new UICommand("No");
                msgDialog.Commands.Add(noCmd);
                IUICommand cmd = await msgDialog.ShowAsync();

                if (cmd == yesCmd)
                {
                    // Launch the saved file
                    bool success = await Windows.System.Launcher.LaunchFileAsync(stFile);
                }
            }
        }