static ApplicationCommands()
 {
   Open = new UICommand("Open", typeof (ApplicationCommands));
   Close = new UICommand("Close", typeof (ApplicationCommands));
   ContextMenu = new UICommand("ContextMenu", typeof (ApplicationCommands));
   Copy = new UICommand("Copy", typeof (ApplicationCommands));
   CorrectionList = new UICommand("CorrectionList", typeof (ApplicationCommands));
   Cut = new UICommand("Cut", typeof (ApplicationCommands));
   Delete = new UICommand("Delete", typeof (ApplicationCommands));
   Find = new UICommand("Find", typeof (ApplicationCommands));
   Help = new UICommand("Help", typeof (ApplicationCommands));
   New = new UICommand("New", typeof (ApplicationCommands));
   Open = new UICommand("Open", typeof (ApplicationCommands));
   Paste = new UICommand("Paste", typeof (ApplicationCommands));
   Print = new UICommand("Print", typeof (ApplicationCommands));
   PrintPreview = new UICommand("PrintPreview", typeof (ApplicationCommands));
   Properties = new UICommand("Properies", typeof (ApplicationCommands));
   Redo = new UICommand("Redo", typeof (ApplicationCommands));
   Replace = new UICommand("Replace", typeof (ApplicationCommands));
   Save = new UICommand("Save", typeof (ApplicationCommands));
   SaveAs = new UICommand("SaveAs", typeof (ApplicationCommands));
   SelectAll = new UICommand("SelectAll", typeof (ApplicationCommands));
   Stop = new UICommand("Stop", typeof (ApplicationCommands));
   Undo = new UICommand("Undo", typeof (ApplicationCommands));
 }
Exemple #2
0
        public static void AddChangeColorCommand(this UICommandCollection menu, string text, Color defaultSelectedColor, Color automaticColor, Action<object, Color> handler)
        {
            var cmd = new UICommand("", text, CommandType.ColorPickerCommand);

            var colorPicker = new UIColorPicker();
            colorPicker.Configure();

            colorPicker.SelectedColor = defaultSelectedColor;
            colorPicker.AutomaticColor = automaticColor;
            colorPicker.SelectedColorChanged += (sender, e) =>
            {
                Color selectedColor = ((UIColorPicker)sender).SelectedColor;
                cmd.Image = DrawContextIcon(selectedColor);
                handler(sender, selectedColor);
            };

            colorPicker.AutomaticButtonClick += (sender, e) =>
            {
                cmd.Image = DrawContextIcon(automaticColor);
                handler(sender, automaticColor);
            };

            cmd.Control = colorPicker;
            cmd.Image = DrawContextIcon(defaultSelectedColor);
            menu.Add(cmd);
        }
 // ui thread only
 public void Enqueue( UICommand command )
 {
     lock (commandlist)
     {
         commandlist.Enqueue(command);
     }
 }
 void NewHeightMapHandler(UICommand command)
 {
     CmdNewHeightMap thiscommand = command as CmdNewHeightMap;
     HeightMap.GetInstance().Width = thiscommand.width * 64 + 1;
     HeightMap.GetInstance().Height = thiscommand.width * 64 + 1;
     HeightMap.GetInstance().Map = new float[HeightMap.GetInstance().Width, HeightMap.GetInstance().Height];
     lastfilename = "";
 }
 private void AttachScore(UICommand command)
 {
     if (IsolatedStorageSettings.ApplicationSettings.Contains(command.Id))
     {
         command.Score = (int)IsolatedStorageSettings.ApplicationSettings[command.Id];
         //MessageBox.Show(command.Name + "->" + command.Score.ToString());
     }
 }
 public void InitValuesTest() {
     UICommand command = new UICommand();
     Assert.AreEqual(null, command.Id);
     Assert.AreEqual(null, command.Command);
     Assert.AreEqual(null, command.Caption);
     Assert.AreEqual(null, command.Tag);
     Assert.AreEqual(false, command.IsCancel);
     Assert.AreEqual(false, command.IsDefault);
 }
 public ModalWindow(UICommand command, bool hasCloseButton)
     : this()
 {
     this.command = command;
     this.HasCloseButton = hasCloseButton;
     Content.Content = command.View;
     Title = command.Name;
     command.Closing += command_Closing;
 }
 public void ConstructorTest() {
     DelegateCommand c = new DelegateCommand(() => { });
     UICommand command = new UICommand(0, "label", c, true, true, 0);
     Assert.AreEqual(0, command.Id);
     Assert.AreEqual(c, command.Command);
     Assert.AreEqual("label", command.Caption);
     Assert.AreEqual(0, command.Tag);
     Assert.AreEqual(true, command.IsCancel);
     Assert.AreEqual(true, command.IsDefault);
 }
 public UriDownloaderViewModel(Uri uri, Version version)
 {
     this.uri = uri;
     this.version = version;
     Status = UpdaterStatus.Initializing;
     StartDownloadCommand = DelegateCommandFactory.Create(StartDownload);
     RestartCommand = new UICommand(new object(), "Restart", DelegateCommandFactory.Create(new Action(Restart), new Func<bool>(CanRestart)), true, false);
     CancelCommand = new UICommand(new object(), "Cancel", DelegateCommandFactory.Create(new Action(Cancel), new Func<bool>(CanCancel)), false, true);
     client = new WebClient();
     client.DownloadProgressChanged += OnDownloadProgressChanged;
     client.DownloadDataCompleted += DownloadDataCompleted;
 }
		public ErrorReportView()
		{
			InitializeComponent();
			Load += ViewLoad;
			AbortCommand = new UICommand(abortButton);
			CancelCommand = new UICommand(cancelButton);
			RetryCommand = new UICommand(retryButton);

			AbortCommand.PropertyChanged += (o, e) => UpdateVisibility(abortButton, AbortCommand);
			CancelCommand.PropertyChanged += (o, e) => UpdateVisibility(cancelButton, CancelCommand);
			RetryCommand.PropertyChanged += (o, e) => UpdateVisibility(retryButton, RetryCommand);
		}
		public void ButtonText()
		{
			var button = new Button {Text = "Button text"};
			var command = new UICommand(button);
			string propertyName = null;
			command.PropertyChanged += (sender, e) => propertyName = e.PropertyName;
			Assert.AreEqual("Button text", command.Text);

			button.Text = "Text1";
			Assert.AreEqual("Text1", command.Text);
			Assert.AreEqual("Text", propertyName);
		}
		public void ButtonEnabled()
		{
			var button = new Button {Enabled = true};
			var command = new UICommand(button);
			string propertyName = null;
			command.PropertyChanged += (sender, e) => propertyName = e.PropertyName;
			Assert.AreEqual(true, command.Enabled);

			button.Enabled = false;

			Assert.AreEqual(false, command.Enabled);
			Assert.AreEqual("Enabled", propertyName);
		}
Exemple #13
0
        /// <summary>
        /// Gets the command that owns GetCommands()
        /// </summary>
        public UICommand GetMainCommand(UIContextMenu menu)
        {
            Debug.Assert(_mainCommand == null);
            var marker = GetMarker();
            var cmd = menu.AddCommand(GetMainCommandText(marker));
            if (marker.Settings.Enabled)
            {
                cmd.Image = GetMainCommandImage(marker);
            }

            _mainCommand = cmd;
            return cmd;
        }
Exemple #14
0
        public static void AddComboBoxCommand(this UIContextMenu menu, string text, IEnumerable<string> list, string defaultValue, EventHandler handler)
        {
            var ctl = new UIComboBox
            {
                DataSource = list.ToArray(),
                SelectedValue = defaultValue,
                ComboStyle = ComboStyle.DropDownList
            };

            ctl.SelectedValueChanged += handler;

            var cmd = new UICommand("", text, CommandType.ComboBoxCommand);
            cmd.Control = ctl;
            menu.Commands.Add(cmd);
        }
Exemple #15
0
        public static Uri GetCommandImageUri(UICommand command)
        {
            if (command == null) { throw new ArgumentNullException("command"); }

            var core = command.ClientCommand;
            var imgName = core.Meta.ImageName;
            if (!string.IsNullOrEmpty(imgName))
            {
                if (!imgName.Contains("component"))
                {
                    imgName = "Images/" + imgName;
                }
                //图片应该是放在 CoreCommand 的程序集的 Images 文件夹中。
                return Helper.GetPackUri(core.GetType().Assembly, imgName, UriKind.Absolute);
            }

            return null;
        }
		public void ButtonCheckNotSupported()
		{
			var button = new Button();
			var checkBoxInterface = ProxyFactory.CreateDuckProxy<ICheckControl>(button);

			Assert.AreEqual(false, checkBoxInterface.IsCheckedSupported);
			Assert.AreEqual(false, checkBoxInterface.IsCheckedChangedSupported);

			var command = new UICommand(button);
			Assert.AreEqual(false, command.Checked);
			bool checkChangedRaised = false;
			command.PropertyChanged += (o, e) =>
			                           	{
			                           		if (e.PropertyName == "Checked")
			                           		{
			                           			checkChangedRaised = true;
			                           		}
			                           	};
			command.Checked = true;
			Assert.IsTrue(checkChangedRaised);
		}
		public ListConfigView()
		{
			InitializeComponent();
			_adapter = new VirtualDataGridViewAdapter<IConfigParameter>(DataGridView)
				.WithDisplaySettings(_displaySettings)
				.DefineCellValue(NameColumn, p => p.Name)
				.DefineCellValue(ParameterTypeColumn, p => p.ParameterType)
				.DefineCellValue(ValueColumn, p => p.GetDisplayText())
				.DefineCellValue(DescriptionColumn, p => p.Summary)
				.SetDefaultSortOrder(NameColumn)
				.SortBy(NameColumn);

			EditCommand = new UICommand(EditButton);
			RefreshCommand = new UICommand(RefreshButton);

			Load += delegate {
				BeginInvoke(new Action(() => SearchTextBox.Focus()));
				DataGridView.ClearSelection();
				DataGridView.CurrentCell = null;
			};
		}
        public void PropertyChangedTest() {
            UICommand command = new UICommand();

            bool idChanged = false;
            bool commandChanged = false;
            bool labelChanged = false;
            bool tagChanged = false;
            bool isCancelChanged = false;
            bool isDefaultChanged = false;

            PropertyChangedEventHandler propertyChanged = (s, e) => {
                if(e.PropertyName == ExpressionHelper.GetPropertyName(() => command.Id))
                    idChanged = true;
                if(e.PropertyName == ExpressionHelper.GetPropertyName(() => command.Command))
                    commandChanged = true;
                if(e.PropertyName == ExpressionHelper.GetPropertyName(() => command.Tag))
                    tagChanged = true;
                if(e.PropertyName == ExpressionHelper.GetPropertyName(() => command.Caption))
                    labelChanged = true;
                if(e.PropertyName == ExpressionHelper.GetPropertyName(() => command.IsDefault))
                    isDefaultChanged = true;
                if(e.PropertyName == ExpressionHelper.GetPropertyName(() => command.IsCancel))
                    isCancelChanged = true;
            };
            command.PropertyChanged += propertyChanged;

            command.Id = 0;
            Assert.IsTrue(idChanged);
            command.Command = new DelegateCommand(() => { });
            Assert.IsTrue(commandChanged);
            command.Tag = 0;
            Assert.IsTrue(tagChanged);
            command.IsCancel = true;
            Assert.IsTrue(isCancelChanged);
            command.IsDefault = true;
            Assert.IsTrue(isDefaultChanged);
            command.Caption = "label";
            Assert.IsTrue(labelChanged);
        }
Exemple #19
0
        private static void SetupContent(Button button, UICommand command)
        {
            var contentControl = new CommandContentControl();
            contentControl.SetBinding(CommandContentControl.LabelProperty, "Label");
            contentControl.DataContext = command.ClientCommand;

            var uri = CommandImageService.GetCommandImageUri(command);
            if (uri != null) { contentControl.ImageSource = new BitmapImage(uri); }

            button.Content = contentControl;
        }
        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
        }
        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(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);

            //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      = "DataTemplate";
                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("DataTemplate.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
        }
        public void PopSetting(bool bang)
        {
            //ObservableCollection<Level> before_lvs = Levels;
            //DB before_db = new DB(Db.Address, Db.Port, Db.Id, Db.Pw);
            //bool is_change = false;
            try
            {
                SettingViewModel setting_vm = new SettingViewModel();

                UICommand okCommand = new UICommand()
                {
                    Caption   = "OK",
                    IsCancel  = false,
                    IsDefault = true
                };

                UICommand cancelCommand = new UICommand()
                {
                    Id        = MessageBoxResult.Cancel,
                    Caption   = "Cancel",
                    IsCancel  = true,
                    IsDefault = false,
                };

                IDialogService service = this.GetService <IDialogService>("service1");

                UICommand result = service.ShowDialog(
                    dialogCommands: new List <UICommand>()
                {
                    okCommand, cancelCommand
                },
                    title: "Setting",
                    viewModel: setting_vm);
                //셋팅 다이알로그에서 설정한 값들로 Setting 변수 저장
                if (result == okCommand)
                {
                    Properties.Settings.Default.gas_yellow  = Levels[0].Yellow;
                    Properties.Settings.Default.gas_red     = Levels[0].Red;
                    Properties.Settings.Default.gas2_yellow = Levels[1].Yellow;
                    Properties.Settings.Default.gas2_red    = Levels[1].Red;
                    Properties.Settings.Default.gas3_yellow = Levels[2].Yellow;
                    Properties.Settings.Default.gas3_red    = Levels[2].Red;
                    Properties.Settings.Default.gas4_yellow = Levels[3].Yellow;
                    Properties.Settings.Default.gas4_red    = Levels[3].Red;
                    Properties.Settings.Default.gas5_yellow = Levels[4].Yellow;
                    Properties.Settings.Default.gas5_red    = Levels[4].Red;
                    Properties.Settings.Default.gas6_yellow = Levels[5].Yellow;
                    Properties.Settings.Default.gas6_red    = Levels[5].Red;
                    Properties.Settings.Default.address     = Db.Address;
                    Properties.Settings.Default.port        = Db.Port;
                    Properties.Settings.Default.id          = Db.Id;
                    Properties.Settings.Default.pw          = Db.Pw;
                    Properties.Settings.Default.alert       = setting_vm.Ischeck_pop;
                    Properties.Settings.Default.mail        = setting_vm.Ischeck_mail;
                    Properties.Settings.Default.toaddress   = setting_vm.ToAdress;
                    Properties.Settings.Default.Save();

                    Level_init();
                    DB_Init();
                    Device_init();
                    TabInit();
                    //for (int i = 0; i < Levels.Count; i++)
                    //{
                    //    if ((before_lvs[i].Yellow != Levels[i].Yellow) ||
                    //        (before_lvs[i].Red != Levels[i].Red))
                    //    {
                    //        is_change = true;
                    //    }
                    //}
                    //if ((before_db.Address != Db.Address) ||
                    //    (before_db.Port != Db.Port) ||
                    //    (before_db.Id != Db.Id) ||
                    //    (before_db.Pw != Db.Pw))
                    //{
                    //    is_change = true;
                    //}
                    //if(is_change)
                    //{
                    //    DXMessageBox.Show("DB 연결 속성값이 변경 되었습니다.", "가스 모니터링 시스템 v2.0");
                    //}
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        private async void Save(bool isDocFormat, WordDocument document)
        {
            StorageFile stgFile;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                // Dropdown of file types the user can save the file as
                if (isDocFormat)
                {
                    savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                    {
                        ".doc"
                    });
                }
                else
                {
                    savePicker.FileTypeChoices.Add("Word Document", new List <string>()
                    {
                        ".docx"
                    });
                }
                // Default file name if the user does not type one in or select a file to replace
                savePicker.SuggestedFileName = "Sample";
                stgFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                stgFile = await local.CreateFileAsync("WordDocument.docx", CreationCollisionOption.ReplaceExisting);
            }
            if (stgFile != null)
            {
                MemoryStream stream = new MemoryStream();
                if (isDocFormat)
                {
                    await document.SaveAsync(stream, FormatType.Doc);
                }
                else
                {
                    await document.SaveAsync(stream, FormatType.Docx);
                }
                document.Close();
                stream.Position = 0;
                Windows.Storage.Streams.IRandomAccessStream fileStream = await stgFile.OpenAsync(FileAccessMode.ReadWrite);

                Stream st = fileStream.AsStreamForWrite();
                st.SetLength(0);
                st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
                st.Flush();
                st.Dispose();
                fileStream.Dispose();
                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);
                }
            }
        }
Exemple #24
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            #region workbook Initialization
            //Instantiate the spreadsheet creation engine.
            ExcelEngine excelEngine = new ExcelEngine();

            //Instantiate the excel application object.
            IApplication application = excelEngine.Excel;

            //Set the default version as Excel 2010.
            application.DefaultVersion = ExcelVersion.Excel2010;

            Assembly  assembly     = typeof(Chart).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.Sparkline.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 WholeSale Report

            //A new Sparkline group is added to the sheet sparklinegroups
            ISparklineGroup sparklineGroup = sheet.SparklineGroups.Add();

            //Set the Sparkline group type as line
            sparklineGroup.SparklineType = SparklineType.Line;

            //Set to display the empty cell as line
            sparklineGroup.DisplayEmptyCellsAs = SparklineEmptyCells.Line;

            //Sparkline group style properties
            sparklineGroup.ShowFirstPoint     = true;
            sparklineGroup.FirstPointColor    = Color.FromArgb(255, 0, 128, 0);
            sparklineGroup.ShowLastPoint      = true;
            sparklineGroup.LastPointColor     = Color.FromArgb(255, 255, 140, 0);
            sparklineGroup.ShowHighPoint      = true;
            sparklineGroup.HighPointColor     = Color.FromArgb(255, 0, 0, 139);
            sparklineGroup.ShowLowPoint       = true;
            sparklineGroup.LowPointColor      = Color.FromArgb(255, 148, 0, 211);
            sparklineGroup.ShowMarkers        = true;
            sparklineGroup.MarkersColor       = Color.FromArgb(255, 0, 0, 0);
            sparklineGroup.ShowNegativePoint  = true;
            sparklineGroup.NegativePointColor = Color.FromArgb(255, 255, 0, 0);

            //set the line weight
            sparklineGroup.LineWeight = 0.3;

            //The sparklines are added to the sparklinegroup.
            ISparklines sparklines = sparklineGroup.Add();

            //Set the Sparkline Datarange .
            IRange dataRange = sheet.Range["D6:G17"];
            //Set the Sparkline Reference range.
            IRange referenceRange = sheet.Range["H6:H17"];

            //Create a sparkline with the datarange and reference range.
            sparklines.Add(dataRange, referenceRange);



            #endregion

            #region Retail Trade

            //A new Sparkline group is added to the sheet sparklinegroups
            sparklineGroup = sheet.SparklineGroups.Add();

            //Set the Sparkline group type as column
            sparklineGroup.SparklineType = SparklineType.Column;

            //Set to display the empty cell as zero
            sparklineGroup.DisplayEmptyCellsAs = SparklineEmptyCells.Zero;

            //Sparkline group style properties
            sparklineGroup.ShowHighPoint      = true;
            sparklineGroup.HighPointColor     = Color.FromArgb(255, 0, 128, 0);
            sparklineGroup.ShowLowPoint       = true;
            sparklineGroup.LowPointColor      = Color.FromArgb(255, 255, 0, 0);
            sparklineGroup.ShowNegativePoint  = true;
            sparklineGroup.NegativePointColor = Color.FromArgb(255, 0, 0, 0);

            //The sparklines are added to the sparklinegroup.
            sparklines = sparklineGroup.Add();

            //Set the Sparkline Datarange .
            dataRange = sheet.Range["D21:G32"];
            //Set the Sparkline Reference range.
            referenceRange = sheet.Range["H21:H32"];

            //Create a sparkline with the datarange and reference range.
            sparklines.Add(dataRange, referenceRange);

            #endregion

            #region Manufacturing Trade

            //A new Sparkline group is added to the sheet sparklinegroups
            sparklineGroup = sheet.SparklineGroups.Add();

            //Set the Sparkline group type as win/loss
            sparklineGroup.SparklineType = SparklineType.ColumnStacked100;

            sparklineGroup.DisplayEmptyCellsAs = SparklineEmptyCells.Zero;

            sparklineGroup.DisplayAxis        = true;
            sparklineGroup.AxisColor          = Color.FromArgb(255, 0, 0, 0);
            sparklineGroup.ShowFirstPoint     = true;
            sparklineGroup.FirstPointColor    = Color.FromArgb(255, 0, 128, 0);
            sparklineGroup.ShowLastPoint      = true;
            sparklineGroup.LastPointColor     = Color.FromArgb(255, 255, 165, 0);
            sparklineGroup.ShowNegativePoint  = true;
            sparklineGroup.NegativePointColor = Color.FromArgb(255, 255, 0, 0);

            sparklines = sparklineGroup.Add();

            dataRange      = sheet.Range["D36:G46"];
            referenceRange = sheet.Range["H36:H46"];

            sparklines.Add(dataRange, referenceRange);

            #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      = "Sparklines";
                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("Sparklines.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 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);
                }
            }
            else
            {
                workbook.Close();
                excelEngine.Dispose();
            }
            #endregion
        }
 private void PinCommand(UICommand command)
 {
     if (Config.IsolatedStorage.PinnedCommands.ContainsKey(command.Id) && Config.IsolatedStorage.PinnedCommands[command.Id])
     {
         var datacontext = DataContext as MainPageViewModel;
         var context = new UICommandContext() { Events = events, RegiseredCommands = RegisteredCommands.ToList() };
         command.Context = context;
         datacontext.TaskbarCommands.Add(command);
     }
 }
Exemple #26
0
        private async void btnGenerateExcel_Click(object sender, RoutedEventArgs e)
        {
            StorageFile storageFile;
            string      fileName = "Treemap_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("Treemap_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(Treemap).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.TreemapTemplate.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 Treemap Chart Settings
            chart.ChartType  = ExcelChartType.TreeMap;
            chart.DataRange  = sheet["A1:F13"];
            chart.ChartTitle = "Daily Food Sales";
            foreach (IChartSerie serie in chart.Series)
            {
                serie.SerieFormat.TreeMapLabelOption = ExcelTreeMapLabelOption.Banner;
            }
            #endregion

            chart.Legend.Position = ExcelLegendPosition.Top;

            if (this.rdBtnSheet.IsChecked != null && this.rdBtnSheet.IsChecked.Value)
            {
                chart.Activate();
            }
            else
            {
                workbook.Worksheets[0].Activate();
                IChartShape chartShape = chart as IChartShape;
                chartShape.TopRow      = 1;
                chartShape.BottomRow   = 22;
                chartShape.LeftColumn  = 8;
                chartShape.RightColumn = 15;
            }
            #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
        }
Exemple #27
0
        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(DataSort).GetTypeInfo().Assembly;
            string    resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.SortingData.xlsx";
            Stream    fileStream   = assembly.GetManifestResourceStream(resourcePath);
            IWorkbook workbook     = await application.Workbooks.OpenAsync(fileStream);

            #endregion

            #region sorting the data
            workbook.Version = ExcelVersion.Excel2007;
            IWorksheet worksheet = workbook.Worksheets[0];
            IRange     range     = worksheet["A2:D51"];

            IDataSort sorter = workbook.CreateDataSorter();
            sorter.SortRange = range;

            OrderBy orderBy = this.Ascending.IsChecked == true ? OrderBy.Ascending : OrderBy.Descending;

            string sortOn      = comboBox1.SelectedValue as string;
            int    columnIndex = GetSelectedIndex(sortOn);

            //Specify the sort field attributes (column index and sort order)
            ISortField field = sorter.SortFields.Add(columnIndex, SortOn.Values, orderBy);

            sorter.Algorithm = SortingAlgorithms.QuickSort;
            sorter.Sort();
            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      = "DataSortSample";
                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("DataSortSample.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
        }
Exemple #28
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      = "DataValidationSample";
                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("DataValidationSample.xls", CreationCollisionOption.ReplaceExisting);
                }
                else
                {
                    storageFile = await local.CreateFileAsync("DataValidationSample.xlsx", CreationCollisionOption.ReplaceExisting);
                }
            }


            if (storageFile == null)
            {
                return;
            }
            //Instantiate excel Engine
            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;

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

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

            //Data validation to list the values in the first cell
            IDataValidation validation = sheet.Range["C7"].DataValidation;

            sheet.Range["B7"].Text = "Select an item from the validation list";

            validation.ListOfValues       = new string[] { "PDF", "XlsIO", "DocIO" };
            validation.PromptBoxText      = "Data Validation list";
            validation.IsPromptBoxVisible = true;
            validation.ShowPromptBox      = true;

            sheet.Range["C7"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
            sheet.Range["C7"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
            sheet.Range["C7"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

            // Data Validation for Numbers
            IDataValidation validation1 = sheet.Range["C9"].DataValidation;

            sheet.Range["B9"].Text      = "Enter a Number to validate";
            validation1.AllowType       = ExcelDataType.Integer;
            validation1.CompareOperator = ExcelDataValidationComparisonOperator.Between;
            validation1.FirstFormula    = "0";
            validation1.SecondFormula   = "10";
            validation1.ShowErrorBox    = true;
            validation1.ErrorBoxText    = "Value must be between 0 and 10";
            validation1.ErrorBoxTitle   = "ERROR";
            validation1.PromptBoxText   = "Value must be between 0 and 10";
            validation1.ShowPromptBox   = true;
            sheet.Range["C9"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
            sheet.Range["C9"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
            sheet.Range["C9"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

            // Data Validation for Date
            IDataValidation validation2 = sheet.Range["C11"].DataValidation;

            sheet.Range["B11"].Text     = "Enter the Date to validate";
            validation2.AllowType       = ExcelDataType.Date;
            validation2.CompareOperator = ExcelDataValidationComparisonOperator.Between;
            validation2.FirstDateTime   = new DateTime(2012, 1, 1);
            validation2.SecondDateTime  = new DateTime(2012, 12, 31);
            validation2.ShowErrorBox    = true;
            validation2.ErrorBoxText    = "Value must be from 01/1/2012 to 31/12/2012";
            validation2.ErrorBoxTitle   = "ERROR";
            validation2.PromptBoxText   = "Value must be from 01/1/2012 to 31/12/2012";
            validation2.ShowPromptBox   = true;
            sheet.Range["C11"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
            sheet.Range["C11"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
            sheet.Range["C11"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

            // Data Validation for TextLength
            IDataValidation validation3 = sheet.Range["C13"].DataValidation;

            sheet.Range["B13"].Text     = "Enter the Text to validate";
            validation3.AllowType       = ExcelDataType.TextLength;
            validation3.CompareOperator = ExcelDataValidationComparisonOperator.Between;
            validation3.FirstFormula    = "1";
            validation3.SecondFormula   = "6";
            validation3.ShowErrorBox    = true;
            validation3.ErrorBoxText    = "Maximum 6 characters are allowed";
            validation3.ErrorBoxTitle   = "ERROR";
            validation3.PromptBoxText   = "Maximum 6 characters are allowed";
            validation3.ShowPromptBox   = true;
            sheet.Range["C13"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
            sheet.Range["C13"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
            sheet.Range["C13"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;

            // Data Validation for Time
            IDataValidation validation4 = sheet.Range["C15"].DataValidation;

            sheet.Range["B15"].Text     = "Enter the Time to validate";
            validation4.AllowType       = ExcelDataType.Time;
            validation4.CompareOperator = ExcelDataValidationComparisonOperator.Between;
            validation4.FirstFormula    = "10";
            validation4.SecondFormula   = "12";
            validation4.ShowErrorBox    = true;
            validation4.ErrorBoxText    = "Time must be between 10 and 12";
            validation4.ErrorBoxTitle   = "ERROR";
            validation4.PromptBoxText   = "Time must be between 10 and 12";
            validation4.ShowPromptBox   = true;
            sheet.Range["C15"].CellStyle.Borders.LineStyle = ExcelLineStyle.Medium;
            sheet.Range["C15"].CellStyle.Borders[ExcelBordersIndex.DiagonalDown].ShowDiagonalLine = false;
            sheet.Range["C15"].CellStyle.Borders[ExcelBordersIndex.DiagonalUp].ShowDiagonalLine   = false;
            sheet.Range["B2:C2"].Merge();
            sheet.Range["B2"].Text = "Simple Data validation";
            sheet.Range["B5"].Text = "Validation criteria";
            sheet.Range["C5"].Text = "Validation";
            sheet.Range["B5"].CellStyle.Font.Bold           = true;
            sheet.Range["C5"].CellStyle.Font.Bold           = true;
            sheet.Range["B2"].CellStyle.Font.Bold           = true;
            sheet.Range["B2"].CellStyle.Font.Size           = 16;
            sheet.Range["B2"].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignCenter;
            sheet.AutofitColumn(2);
            sheet["B7"].ColumnWidth = 40.3;
            sheet.UsedRange.AutofitRows();

            await workbook.SaveAsAsync(storageFile);

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

            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);
            }
        }
Exemple #29
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);
                }
            }
        }
        /// <summary>
        /// Method is export the selected records in SfDataGrid to Excel.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnExportSelectedToExcel(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.sfGrid.ExportToExcel(this.sfGrid.SelectedItems, new ExcelExportingOptions()
                {
                    CellsExportingEventHandler = CellExportingHandler,
                    ExportingEventHandler      = CustomizedexportingHandler
                }, workBook.Worksheets[0]);
            }
            else
            {
                this.sfGrid.ExportToExcel(this.sfGrid.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();
        }
        private async void OnExportToExcel(object sender, RoutedEventArgs e)
        {
            var options = new TreeGridExcelExportingOptions()
            {
                AllowOutliningGroups = (bool)AllowOutlining.IsChecked,
                AllowIndentColumn    = (bool)AllowIndentColumn.IsChecked,
                IsGridLinesVisible   = (bool)IsGridLinesVisible.IsChecked,
                CanExportHyperLink   = (bool)CanExportHyperLink.IsChecked,
                NodeExpandMode       = (nodeexpandMode.SelectedIndex == 0 ? NodeExpandMode.Default :
                                        (nodeexpandMode.SelectedIndex == 1 ? NodeExpandMode.ExpandAll : NodeExpandMode.CollapseAll)),
                ExcelVersion          = ExcelVersion.Excel2013,
                ExportingEventHandler = ExportingHandler
            };

            if ((bool)customizeColumns.IsChecked)
            {
                options.CellsExportingEventHandler = CustomizeCellExportingHandler;
            }

            excelEngine = new ExcelEngine();
            IWorkbook workBook = excelEngine.Excel.Workbooks.Create();

            treeGrid.ExportToExcel(workBook, options);

            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                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);

                options.CellsExportingEventHandler = null;
                options.ExportingEventHandler      = null;
                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 Launcher.LaunchFileAsync(storageFile);
                }
            }
        }
 UICommandInvokedHandler ConvertToAction(UICommand command) {
     return new UICommandInvokedHandler((d) => { command.Command.If(x => x.CanExecute(command)).Do(y => y.Execute(command)); });
 }
Exemple #33
0
 void ChangeBrushEffect(UICommand command)
 {
     brusheffect = (command as UICommandBrushEffect).effect;
 }
Exemple #34
0
        void ExportSlopeMapHandler(UICommand command)
        {
            CmdExportSlopeMap exportcmd = command as CmdExportSlopeMap;

            Save(exportcmd.FilePath);
        }
        public virtual void ShowMessage(string title, string content, UICommand alternative1, UICommand alternative2)
        {
            var messageDialog = new MessageDialog(content, title);

            messageDialog.Commands.Add(alternative1);
            messageDialog.Commands.Add(alternative2);
            messageDialog.DefaultCommandIndex = 0;
            messageDialog.CancelCommandIndex  = 1;
            messageDialog.ShowAsync();
        }
        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
        }
Exemple #37
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);
                    }
                }
            }
        }
        //lstViewPlaylist_RightTapped
        private async void lstViewPlaylist_RightTapped(Object sender, RightTappedRoutedEventArgs e)
        {
            PopupMenu   pMenu           = new PopupMenu();               //定义弹出菜单
            UICommand   cmd             = new UICommand();               //UiCommand类的实例,向弹出菜单添加命令
            ListBoxItem rightTappedSong = null;
            UIElement   controls        = e.OriginalSource as UIElement; //e.OriginalSource获取引发事件的对象的引用

            while (controls != null && controls != sender as UIElement)
            {
                if (controls is ListBoxItem)
                {
                    rightTappedSong = controls as ListBoxItem;//存储用户右击的歌曲的引用
                    if (currentSong != null && currentSong.SongTitle == (rightTappedSong.Content as string).Trim() && isPlaying)
                    {
                        cmd.Label = "Pause"; //如果右击正在播放的歌曲,则右击弹出菜单显示pause
                        cmd.Id    = "pause";
                    }
                    else
                    {
                        cmd.Label = "Play";
                        cmd.Id    = "play";
                    }
                    pMenu.Commands.Add(cmd); //cmd中的命令添加到了弹出菜单里
                    UICommand cmdDeleteFile = new UICommand();
                    cmdDeleteFile.Id    = "Delete";
                    cmdDeleteFile.Label = "Delete";
                    pMenu.Commands.Add(cmdDeleteFile);
                    break;
                }
                controls = VisualTreeHelper.GetParent(controls) as UIElement;// 返回可视树中某一对象的父对
            }

            UICommand cmdaddFile = new UICommand();//创建UICommand的实例,该对象负责在弹出菜单上显示一个标签,并且具有唯一Id

            cmdaddFile.Label = "Add";
            cmdaddFile.Id    = "Add";
            pMenu.Commands.Add(cmdaddFile); //将cmdaddFile的命令添加到弹出菜单

            //pMenu的ShowForSelectionAsync()异步方法,用于显示弹出菜单
            var selectedCommand = await pMenu.ShowForSelectionAsync(new Rect(e.GetPosition(null), e.GetPosition(null)));

            if (selectedCommand != null)
            {
                if (selectedCommand.Id.ToString() == "Add")
                {
                    Windows.Storage.Pickers.FileOpenPicker fop = new
                                                                 Windows.Storage.Pickers.FileOpenPicker();//创建文件打开捡取器的实例
                    fop.FileTypeFilter.Add(".mp3");
                    fop.FileTypeFilter.Add(".wav");
                    fop.FileTypeFilter.Add(".mp4");//可播放的文件类型,文件类型过滤器的Add方法
                    fop.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
                    //设置到Music文件夹默认的浏览位置
                    var selectedFile = await fop.PickSingleFileAsync();

                    if (selectedFile != null) //判断用户是否选择了文件
                    {
                        playList.Add(new Song(selectedFile.DisplayName, "ms-appx:///MediaCollections/Thumbnails/1.jpg", selectedFile));
                        loadPlayList();  //重新加载音乐播放列表
                    }
                }
                else
                {
                    for (int i = 0; i < playList.Count; i++) //构建播放列表
                    {
                        if (playList[i].SongTitle.Trim() == rightTappedSong.Content.ToString().Trim())
                        {
                            if (selectedCommand.Id.ToString() == "play")
                            {
                                lstViewPlaylist.SelectedIndex = i; //用户选择播放歌曲
                                await Task.Delay(1500);            //延迟1.5秒

                                playSong();                        //开始播放选中的歌曲
                                break;
                            }
                            //如果用户想停止当前播放的音乐
                            else if (selectedCommand.Id.ToString() == "pause")
                            {
                                pauseSong();   //
                                break;
                            }
                            else if (selectedCommand.Id.ToString() == "Delete")//删除音乐
                            {
                                if (currentSong != null && currentSong.SongFile == playList[i].SongFile)
                                {
                                    currentSong               = null;
                                    mediaSource.Source        = null;
                                    prgsBarSongPosition.Value = 0.0; //重置进度条的位置
                                    pauseSong();                     //停止播放音乐
                                }
                                playList.RemoveAt(i);                //从播放列表中移除歌曲
                                loadPlayList();                      //重新加载播放列表
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemple #39
0
        private void GatherUICommands(ComparisonItem cmpItem, List <UICommand> RClickCommands, bool IsLeftSourced)
        {
            if (cmpItem == null || cmpItem.NodeType == ResultNodeType.ObjectsCollection)
            {
                return;
            }

            if (cmpItem.NodeType == ResultNodeType.FakeNode)
            {
                GatherUICommands(cmpItem.Parent, RClickCommands, IsLeftSourced);
                return;
            }

            // gathering treeitem commands
            object srcObject = (IsLeftSourced) ? cmpItem.Left.Object : cmpItem.Right.Object;

            if (cmpItem.NodeType == ResultNodeType.PropertyDef)
            {
                if (srcObject != null)
                {
                    var PropDef = (PropDef)srcObject;
                    AddProviderCommands(PropDef as ICommandProvider, RClickCommands);

                    if (cmpItem.Status == ComparisonStatus.Modified || cmpItem.Status == ComparisonStatus.Match)
                    {
                        if (PropDef.Value is V8ModuleProcessor)
                        {
                            var cmd = new UICommand("Показать различия в модулях", cmpItem, new Action(
                                                        () =>
                            {
                                V8ModuleProcessor LeftVal  = ((PropDef)cmpItem.Left.Object).Value as V8ModuleProcessor;
                                V8ModuleProcessor RightVal = ((PropDef)cmpItem.Right.Object).Value as V8ModuleProcessor;
                                var viewer = LeftVal.GetDifferenceViewer(RightVal);
                                if (viewer != null)
                                {
                                    viewer.ShowDifference(LeftName, RightName);
                                }
                            }));

                            RClickCommands.Add(cmd);
                        }
                        else if (PropDef.Value is TemplateDocument)
                        {
                            var cmd = new UICommand("Показать различия в макетах", cmpItem, new Action(
                                                        () =>
                            {
                                TemplateDocument LeftVal  = ((PropDef)cmpItem.Left.Object).Value as TemplateDocument;
                                TemplateDocument RightVal = ((PropDef)cmpItem.Right.Object).Value as TemplateDocument;
                                var viewer = LeftVal.GetDifferenceViewer(RightVal);
                                if (viewer != null)
                                {
                                    viewer.ShowDifference(LeftName, RightName);
                                }
                            }));

                            RClickCommands.Add(cmd);
                        }
                        else if (PropDef.Value is MDUserDialogBase)
                        {
                            var cmd = new UICommand("Показать различия в диалогах", cmpItem, new Action(
                                                        () =>
                            {
                                MDUserDialogBase LeftVal  = ((PropDef)cmpItem.Left.Object).Value as MDUserDialogBase;
                                MDUserDialogBase RightVal = ((PropDef)cmpItem.Right.Object).Value as MDUserDialogBase;
                                var viewer = new Comparison.ExternalTextDiffViewer(LeftVal.ToString(), RightVal.ToString());
                                if (viewer != null)
                                {
                                    viewer.ShowDifference(LeftName, RightName);
                                }
                            }));

                            RClickCommands.Add(cmd);
                        }
                    }
                    GatherUICommands(cmpItem.Parent, RClickCommands, IsLeftSourced);
                }
            }
            else if (cmpItem.NodeType == ResultNodeType.Object)
            {
                var Provider = srcObject as ICommandProvider;
                AddProviderCommands(Provider, RClickCommands);
            }

            if (srcObject != null && srcObject is IMDPropertyProvider)
            {
                var cmd = new UICommand("Отчет по свойствам", srcObject, () =>
                {
                    PropertiesReport repGenerator;
                    string windowTitle;

                    if (cmpItem.Left.Object != null && cmpItem.Right.Object != null)
                    {
                        repGenerator = new PropertiesReportCompare(cmpItem.Left.Object as IMDPropertyProvider, cmpItem.Right.Object as IMDPropertyProvider);
                        windowTitle  = String.Format("Отчет по свойствам: {0}/{1}", cmpItem.Left.Object.ToString(), cmpItem.Right.Object.ToString());
                    }
                    else
                    {
                        repGenerator = new PropertiesReportSingle((IMDPropertyProvider)srcObject);
                        windowTitle  = srcObject.ToString();
                    }

                    Dispatcher.BeginInvoke(new Action(() =>
                    {
                        FlowDocViewer fdViewer = new FlowDocViewer();
                        fdViewer.Title         = windowTitle;
                        fdViewer.Document      = repGenerator.GenerateReport();
                        fdViewer.Show();
                    }));
                });

                RClickCommands.Add(cmd);
            }
        }
 public override void ShowMessage(string title, string content, UICommand alternative1, UICommand alternative2)
 {
     base.ShowMessage(title, content, alternative1, alternative2);
 }
Exemple #41
0
        private async void btnImportXml_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      = "ImportXMLSample";
                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("ImportXMLSample.xls", CreationCollisionOption.ReplaceExisting);
                }
                else
                {
                    storageFile = await local.CreateFileAsync("ImportXMLSample.xlsx", CreationCollisionOption.ReplaceExisting);
                }
            }

            if (storageFile == null)
            {
                return;
            }



            //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 3 worksheets
            IWorkbook workbook = application.Workbooks.Create(1);
            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];

            Assembly assembly   = typeof(ImportXML).GetTypeInfo().Assembly;
            Stream   fileStream = assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.customers.xml");

            // Import the XML contents to worksheet
            XlsIOExtensions exten = new XlsIOExtensions();

            exten.ImportXML(fileStream, sheet, 1, 1, true);

            // Apply style for header
            IStyle headerStyle = sheet[1, 1, 1, sheet.UsedRange.LastColumn].CellStyle;

            headerStyle.Font.Bold  = true;
            headerStyle.Font.Color = ExcelKnownColors.Brown;
            headerStyle.Font.Size  = 10;

            // Autofit columns
            sheet.Columns[0].ColumnWidth = 11;
            sheet.Columns[1].ColumnWidth = 30.5;
            sheet.Columns[2].ColumnWidth = 20;
            sheet.Columns[3].ColumnWidth = 25.6;
            sheet.Columns[6].ColumnWidth = 10.5;
            sheet.Columns[4].ColumnWidth = 40;
            sheet.Columns[5].ColumnWidth = 25.5;
            sheet.Columns[7].ColumnWidth = 9.6;
            sheet.Columns[8].ColumnWidth = 15;
            sheet.Columns[9].ColumnWidth = 15;

            await workbook.SaveAsAsync(storageFile);

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

            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);
            }
        }
 private async void OnLogoutCommandInvoked(IUICommand command)
 {
     MessageDialog confirmLogout = new MessageDialog("Are you sure you want to logout?", "We're sad to see you go. :(");
     UICommand ok = new UICommand("Yep");
     UICommand cancel = new UICommand("Nah");
     
     confirmLogout.DefaultCommandIndex = 0;
     confirmLogout.CancelCommandIndex = 1;
     
     confirmLogout.Commands.Add(ok);
     confirmLogout.Commands.Add(cancel);
     
     IUICommand selected = await confirmLogout.ShowAsync();
     if (selected == ok)
     {
         var settings = SettingsModelFactory.GetSettingsModel();
         App.UserContext.Logout(settings);
         await new MessageDialog("Logout successful. Restart Awful to complete.").ShowAsync();
     }
 }
 private void RemoveFromTaskbarIfCommandIsNotPinned(UICommand command)
 {
     var datacontext = DataContext as MainPageViewModel;
     if (!(Config.IsolatedStorage.PinnedCommands.ContainsKey(command.Id) && Config.IsolatedStorage.PinnedCommands[command.Id]))
     {
         datacontext.TaskbarCommands.Remove(command);
     }
 }
Exemple #44
0
        protected EventPanelRundownElementViewmodelBase(IEvent ev, EventPanelViewmodelBase parent) : base(ev, parent)
        {
            Media = ev.Media;
            ev.PositionChanged += EventPositionChanged;
            ev.SubEventChanged += OnSubeventChanged;

            CommandToggleHold = new UICommand
            {
                ExecuteDelegate = o =>
                {
                    Event.IsHold = !Event.IsHold;
                    Event.Save();
                },
                CanExecuteDelegate = _canToggleHold
            };
            CommandToggleEnabled = new UICommand
            {
                ExecuteDelegate = o =>
                {
                    Event.IsEnabled = !Event.IsEnabled;
                    Event.Save();
                },
                CanExecuteDelegate = o => Event.PlayState == TPlayState.Scheduled && Event.HaveRight(EventRight.Modify)
            };
            CommandToggleLayer = new UICommand
            {
                ExecuteDelegate = l =>
                {
                    if (!(l is string layerName) || !Enum.TryParse(layerName, true, out VideoLayer layer))
                    {
                        return;
                    }
                    if (_hasSubItemsOnLayer(layer))
                    {
                        var layerEvent = Event.SubEvents.FirstOrDefault(e => e.Layer == layer);
                        layerEvent?.Delete();
                    }
                    else
                    {
                        EngineViewmodel.AddMediaEvent(Event, TStartType.WithParent, TMediaType.Still, layer, true);
                    }
                },
                CanExecuteDelegate = _canToggleLayer
            };
            CommandAddNextRundown = new UICommand
            {
                ExecuteDelegate    = o => EngineViewmodel.AddSimpleEvent(Event, TEventType.Rundown, false),
                CanExecuteDelegate = _canAddNextItem
            };
            CommandAddNextEmptyMovie = new UICommand
            {
                ExecuteDelegate    = o => EngineViewmodel.AddSimpleEvent(Event, TEventType.Movie, false),
                CanExecuteDelegate = CanAddNextMovie
            };
            CommandAddNextLive = new UICommand
            {
                ExecuteDelegate    = o => EngineViewmodel.AddSimpleEvent(Event, TEventType.Live, false),
                CanExecuteDelegate = CanAddNewLive
            };
            CommandAddNextMovie = new UICommand
            {
                ExecuteDelegate = o => EngineViewmodel.AddMediaEvent(Event, TStartType.After, TMediaType.Movie,
                                                                     VideoLayer.Program, false),
                CanExecuteDelegate = CanAddNextMovie
            };
            CommandAddAnimation = new UICommand
            {
                ExecuteDelegate = o => EngineViewmodel.AddMediaEvent(Event, TStartType.WithParent,
                                                                     TMediaType.Animation, VideoLayer.Animation, true),
                CanExecuteDelegate = o => Event.PlayState == TPlayState.Scheduled && Event.HaveRight(EventRight.Modify)
            };
            CommandAddCommandScript = new UICommand
            {
                ExecuteDelegate    = o => EngineViewmodel.AddCommandScriptEvent(Event),
                CanExecuteDelegate = o => Event.PlayState == TPlayState.Scheduled && Event.HaveRight(EventRight.Modify)
            };
        }
		public EditConfigView()
		{
			InitializeComponent();
			SaveCommand = new UICommand(SaveButton);
			CancelCommand = new UICommand(CancelButton);
		}
Exemple #46
0
        private async void ClearButton_Click(object sender, RoutedEventArgs e)
        {
            var dig   = new MessageDialog("若应用无法使用,请尝试清除数据,清除数据后会应用将返回登陆界面。\n\n是否继续?", "警告");
            var btnOk = new UICommand("是");

            dig.Commands.Add(btnOk);
            var btnCancel = new UICommand("否");

            dig.Commands.Add(btnCancel);
            var result = await dig.ShowAsync();

            if (null != result && result.Label == "是")
            {
                try
                {
                    appSetting.Values.Clear();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                DelectRemind();
                try
                {
                    var vault          = new Windows.Security.Credentials.PasswordVault();
                    var credentialList = vault.FindAllByResource(resourceName);
                    foreach (var item in credentialList)
                    {
                        vault.Remove(item);
                    }
                }
                catch { }
                appSetting.Values["CommunityPerInfo"]       = false;
                appSetting.Values["isUseingBackgroundTask"] = false;
                IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
                IStorageFile   storageFileWR     = await applicationFolder.CreateFileAsync("kb", CreationCollisionOption.OpenIfExists);

                try
                {
                    await storageFileWR.DeleteAsync();

                    if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.StartScreen.JumpList"))
                    {
                        if (JumpList.IsSupported())
                        {
                            DisableSystemJumpListAsync();
                        }
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine("个人 -> 切换账号删除课表数据异常");
                }
                try
                {
                    await storageFileWR.DeleteAsync();
                }
                catch (Exception error)
                {
                    Debug.WriteLine(error.Message);
                    Debug.WriteLine("设置 -> 重置应用异常");
                }
                //Application.Current.Exit();
                Frame rootFrame = Window.Current.Content as Frame;
                rootFrame.Navigate(typeof(LoginPage));
            }
            else if (null != result && result.Label == "否")
            {
            }
        }
 IUICommand ConvertToUIPopupCommand(UICommand command) {
     return new Windows.UI.Popups.UICommand((string)command.Caption, ConvertToAction(command), command.Id ?? command);
 }
        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      = "ConditionalFormattings";
                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("ConditionalFormattings.xlsx", CreationCollisionOption.ReplaceExisting);
            }


            if (storageFile == null)
            {
                return;
            }
            //Instantiate excel Engine
            ExcelEngine  excelEngine = new ExcelEngine();
            IApplication application = excelEngine.Excel;


            application.DefaultVersion = ExcelVersion.Excel2013;

            Assembly assembly     = typeof(CondFormat).GetTypeInfo().Assembly;
            string   resourcePath = "Syncfusion.SampleBrowser.UWP.XlsIO.XlsIO.Tutorials.Samples.Assets.Resources.Templates.CFTemplate.xlsx";
            Stream   fileStream   = assembly.GetManifestResourceStream(resourcePath);

            IWorkbook myWorkbook = await excelEngine.Excel.Workbooks.OpenAsync(fileStream);

            IWorksheet sheet = myWorkbook.Worksheets[0];

            #region Databar
            //Add condition for the range
            IConditionalFormats formats = sheet.Range["C7:C46"].ConditionalFormats;
            IConditionalFormat  format  = formats.AddCondition();

            //Set Data bar and icon set for the same cell
            //Set the format type
            format.FormatType = ExcelCFType.DataBar;
            IDataBar dataBar = format.DataBar;

            //Set the constraint
            dataBar.MinPoint.Type  = ConditionValueType.LowestValue;
            dataBar.MinPoint.Value = "0";
            dataBar.MaxPoint.Type  = ConditionValueType.HighestValue;
            dataBar.MaxPoint.Value = "0";

            //Set color for Bar
            dataBar.BarColor = Color.FromArgb(255, 156, 208, 243);

            //Hide the value in data bar
            dataBar.ShowValue = false;
            #endregion

            #region Iconset
            //Add another condition in the same range
            format = formats.AddCondition();

            //Set Icon format type
            format.FormatType = ExcelCFType.IconSet;
            IIconSet iconSet = format.IconSet;
            iconSet.IconSet = ExcelIconSetType.FourRating;
            iconSet.IconCriteria[0].Type  = ConditionValueType.LowestValue;
            iconSet.IconCriteria[0].Value = "0";
            iconSet.IconCriteria[1].Type  = ConditionValueType.HighestValue;
            iconSet.IconCriteria[1].Value = "0";
            iconSet.ShowIconOnly          = true;

            //Sets Icon sets for another range
            formats                       = sheet.Range["E7:E46"].ConditionalFormats;
            format                        = formats.AddCondition();
            format.FormatType             = ExcelCFType.IconSet;
            iconSet                       = format.IconSet;
            iconSet.IconSet               = ExcelIconSetType.ThreeSymbols;
            iconSet.IconCriteria[0].Type  = ConditionValueType.LowestValue;
            iconSet.IconCriteria[0].Value = "0";
            iconSet.IconCriteria[1].Type  = ConditionValueType.HighestValue;
            iconSet.IconCriteria[1].Value = "0";
            iconSet.ShowIconOnly          = true;
            #endregion

            #region Duplicate
            formats           = sheet.Range["D7:D46"].ConditionalFormats;
            format            = formats.AddCondition();
            format.FormatType = ExcelCFType.Duplicate;

            format.BackColorRGB = Color.FromArgb(255, 255, 199, 206);
            #endregion

            #region TopBottom and AboveBelowAverage
            sheet                 = myWorkbook.Worksheets[1];
            formats               = sheet.Range["N6:N35"].ConditionalFormats;
            format                = formats.AddCondition();
            format.FormatType     = ExcelCFType.TopBottom;
            format.TopBottom.Type = ExcelCFTopBottomType.Bottom;

            format.BackColorRGB = Color.FromArgb(255, 51, 153, 102);

            formats           = sheet.Range["M6:M35"].ConditionalFormats;
            format            = formats.AddCondition();
            format.FormatType = ExcelCFType.AboveBelowAverage;
            format.AboveBelowAverage.AverageType = ExcelCFAverageType.Below;

            format.FontColorRGB = Color.FromArgb(255, 255, 255, 255);
            format.BackColorRGB = Color.FromArgb(255, 166, 59, 38);
            #endregion

            await myWorkbook.SaveAsAsync(storageFile);

            //Close the workbook.
            myWorkbook.Close();

            //No exception will be thrown if there are unsaved workbooks.
            excelEngine.ThrowNotSavedOnDestroy = false;
            excelEngine.Dispose();
            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);
            }
        }
Exemple #49
0
 public UICommandContainer(UICommand command, params object[] parameters)
 {
     _Command = command;
     _Parameters = parameters;
 }
Exemple #50
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      = "FormulaSample";
                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("FormulaSample.xls", CreationCollisionOption.ReplaceExisting);
                }
                else
                {
                    storageFile = await local.CreateFileAsync("FormulaSample.xlsx", CreationCollisionOption.ReplaceExisting);
                }
            }

            if (storageFile == null)
            {
                return;
            }
            //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 (this.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 3 worksheets
            IWorkbook workbook = application.Workbooks.Create(1);
            //The first worksheet object in the worksheets collection is accessed.
            IWorksheet sheet = workbook.Worksheets[0];

            #region Insert Array Formula

            sheet.Range["A2"].Text      = "Array formulas";
            sheet.Range["B2:E2"].Number = 3;
            sheet.Names.Add("ArrayRange", sheet.Range["B2:E2"]);
            sheet.Range["B3:E3"].Number           = 5;
            sheet.Range["A2"].CellStyle.Font.Bold = true;
            sheet.Range["A2"].CellStyle.Font.Size = 14;

            #endregion

            #region Excel functions

            sheet.Range["A5"].Text = "Formula";
            sheet.Range["B5"].Text = "Result";

            sheet.Range["A7"].Text    = "ABS(ABS(-B3))";
            sheet.Range["B7"].Formula = "ABS(ABS(-B3))";

            sheet.Range["A9"].Text    = "SUM(B3,C3)";
            sheet.Range["B9"].Formula = "SUM(B3,C3)";

            sheet.Range["A11"].Text    = "MIN(10,20,30,5,15,35,6,16,36)";
            sheet.Range["B11"].Formula = "MIN(10,20,30,5,15,35,6,16,36)";

            sheet.Range["A13"].Text    = "MAX(10,20,30,5,15,35,6,16,36)";
            sheet.Range["B13"].Formula = "MAX(10,20,30,5,15,35,6,16,36)";

            sheet.Range["A5:B5"].CellStyle.Font.Bold = true;
            sheet.Range["A5:B5"].CellStyle.Font.Size = 14;

            #endregion

            #region Simple formulas
            sheet.Range["C7"].Number   = 10;
            sheet.Range["C9"].Number   = 10;
            sheet.Range["A15"].Text    = "C7+C9";
            sheet.Range["B15"].Formula = "C7+C9";

            #endregion

            sheet.Range["B1"].Text = "Excel formula support";
            sheet.Range["B1"].CellStyle.Font.Bold = true;
            sheet.Range["B1"].CellStyle.Font.Size = 14;
            sheet.Range["B1:E1"].Merge();
            sheet.Range["A1:A15"].AutofitColumns();
            sheet.UsedRange.AutofitRows();
            sheet.UsedRange.RowHeight = 19;
            sheet["A1"].ColumnWidth   = 29;

            await workbook.SaveAsAsync(storageFile);

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

            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);
            }
        }
 private void IncrementScore(UICommand command)
 {
     var score = 1;
     if (IsolatedStorageSettings.ApplicationSettings.Contains(command.Id))
     {
         score = (int)IsolatedStorageSettings.ApplicationSettings[command.Id] + 1;
     }
     //MessageBox.Show("issolated storage update hits " + score);
     IsolatedStorageSettings.ApplicationSettings[command.Id] = score;
 }
Exemple #52
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
        }
 private void RegisterCommandEvents(UICommand command)
 {
     command.BeforeShow += command_BeforeShow;
     command.AfterShow += command_AfterShow;
     command.Closing += command_Closing;
 }
Exemple #54
0
        private async void SaveConfirmation()
        {
            try
            {
                EditedHousing = new HousingPost();
                int numPB = 0;

                EditedHousing.Kitchen = SelectedHousing.Kitchen;
                EditedHousing.Wifi    = SelectedHousing.Wifi;
                EditedHousing.Office  = SelectedHousing.Office;
                EditedHousing.Shower  = SelectedHousing.Shower;
                EditedHousing.Toilet  = SelectedHousing.Toilet;

                EditedHousing.StartDate = new DateTime(StartDay.Year, StartDay.Month, StartDay.Day, StartTime.Hours, StartTime.Minutes, 0);
                EditedHousing.EndDate   = new DateTime(EndDay.Year, EndDay.Month, EndDay.Day, EndTime.Hours, EndTime.Minutes, 0);

                if (StartDay > EndDay)
                {
                    throw new AddEditHousingException(1);
                }
                if (StartDay == EndDay)
                {
                    throw new AddEditHousingException(2);
                }
                if (SelectedBedType.Code <= 0)
                {
                    throw new AddEditHousingException(3);
                }
                EditedHousing.BedType = SelectedBedType.Code;
                if (!String.IsNullOrWhiteSpace(Description))
                {
                    EditedHousing.Description = Description;
                }
                else
                {
                    EditedHousing.Description = null;
                }
                if (String.IsNullOrWhiteSpace(SelectedHousing.Number))
                {
                    throw new AddressException(1);
                }
                EditedHousing.Number = SelectedHousing.Number;
                if (!String.IsNullOrWhiteSpace(strPostBox))
                {
                    bool parsed = Int32.TryParse(strPostBox, out numPB);
                    if (!parsed)
                    {
                        throw new AddressException(2);
                    }
                }
                if (String.IsNullOrWhiteSpace(SelectedHousing.Street))
                {
                    throw new AddressException(5);
                }
                else
                {
                    EditedHousing.Street = SelectedHousing.Street;
                }
                if (SelectedLocality != null)
                {
                    EditedHousing.ZipCode = SelectedLocality.Zip;
                    EditedHousing.City    = SelectedLocality.Name;
                }
                else
                {
                    throw new AddressException(9);
                }
                if (!String.IsNullOrWhiteSpace(NewPicture))
                {
                    EditedHousing.Pictures = NewPicture;
                }
                else
                {
                    EditedHousing.Pictures = SelectedHousing.Pictures;
                }
                EditedHousing.PostBox = numPB;

                MessageDialog msgDialog = new MessageDialog("Etes-vous sûr de vouloir sauvegarder les modifications effectuées sur ce logement ?", "Confirmation de modification");

                UICommand okBtn = new UICommand("Oui");
                okBtn.Invoked = SaveHousing;
                msgDialog.Commands.Add(okBtn);

                UICommand cancelBtn = new UICommand("Non");
                msgDialog.Commands.Add(cancelBtn);

                await msgDialog.ShowAsync();
            }
            catch (AddEditHousingException addUserEx)
            {
                await DisplayException(addUserEx.ErrorMessage);
            }
            catch (AddressException addressEx)
            {
                await DisplayException(addressEx.ErrorMessage);
            }
        }
        private void SetupBehaviorBasedOnAttributes(UICommand command)
        {
            if (command.HasAttribute<PinToTaskbarAttribute>())
            {
                if (!Config.IsolatedStorage.PinnedCommands.ContainsKey(command.Id))
                {
                    var datacontext = DataContext as MainPageViewModel;
                    Config.IsolatedStorage.PinnedCommands[command.Id] = true;
                    //datacontext.TaskbarCommands.Add(command);
                }
            }

            if (command.HasAttribute<AttachToTrayAttribute>())
            {
                //MessageBox.Show("attach to tray " + command.Name);
                var context = new UICommandContext() { Events = events, RegiseredCommands = RegisteredCommands.ToList() };
                command.Execute(context);
            }

            if (command.HasAttribute<ExecuteAtStartupAttribute>())
            {
              var context = new UICommandContext() { Events = events, RegiseredCommands = RegisteredCommands.ToList() };
              command.Execute(context);
            }

            if (command.HasAttribute<KeyboardShortcutAttribute>())
            {
                var attribute = command.GetAttribute<KeyboardShortcutAttribute>();
                command.AddParameterDiscription(attribute.ToString());
            }
        }
        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      = "Edit";
                if (rdBtnXls.IsChecked.Value)
                {
                    savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                    {
                        ".xls"
                    });
                }
                else if (rdBtnXltm.IsChecked.Value)
                {
                    savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                    {
                        ".xltm"
                    });
                }
                else
                {
                    savePicker.FileTypeChoices.Add("Excel Files", new List <string>()
                    {
                        ".xlsm",
                    });
                }
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                if (rdBtnXls.IsChecked.Value)
                {
                    storageFile = await local.CreateFileAsync("Edit.xls", CreationCollisionOption.ReplaceExisting);
                }
                else if (rdBtnXltm.IsChecked.Value)
                {
                    storageFile = await local.CreateFileAsync("Edit.xltm", CreationCollisionOption.ReplaceExisting);
                }
                else
                {
                    storageFile = await local.CreateFileAsync("Edit.xlsm", CreationCollisionOption.ReplaceExisting);
                }
            }

            if (storageFile == null)
            {
                return;
            }

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

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

            workbook.Version = ExcelVersion.Excel2016;

            #region VbaProject
            //Access Vba Project from workbook
            IVbaProject vbaProject = workbook.VbaProject;
            IVbaModule  vbaModule  = vbaProject.Modules["Module1"];
            vbaModule.Code = vbaModule.Code.Replace("xlAreaStacked", "xlLine");
            #endregion


            #region Saving the workbook
            ExcelSaveType type = ExcelSaveType.SaveAsMacro;

            if (storageFile.Name.EndsWith(".xls"))
            {
                workbook.Version = ExcelVersion.Excel97to2003;
                type             = ExcelSaveType.SaveAsMacro;
            }
            else if (storageFile.Name.EndsWith(".xltm"))
            {
                type = ExcelSaveType.SaveAsMacroTemplate;
            }

            await workbook.SaveAsAsync(storageFile, type);

            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
        }
        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
        }
Exemple #58
0
        public async void GenerateReport(IList <InvoiceItem> items, BillingInformation billInfo)
        {
            Assembly executingAssembly = typeof(MainPage).GetTypeInfo().Assembly;

            Stream inputStream = executingAssembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Invoice.Assets.InvoiceTemplate.xlsx");

            ExcelEngine excelEngine = new ExcelEngine();
            IWorkbook   book        = await excelEngine.Excel.Workbooks.OpenAsync(inputStream);

            inputStream.Dispose();

            //Create Template Marker Processor
            ITemplateMarkersProcessor marker = book.CreateTemplateMarkersProcessor();

            //Binding the business object with the marker.
            marker.AddVariable("InvoiceItem", items);
            marker.AddVariable("BillInfo", billInfo);
            marker.AddVariable("Company", billInfo);
            //Applies the marker.
            marker.ApplyMarkers(UnknownVariableAction.Skip);
            StorageFile storageFile = null;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                savePicker.SuggestedFileName      = "Invoice";

                savePicker.FileTypeChoices.Add("Invoice", new List <string>()
                {
                    ".xlsx",
                });
                storageFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                storageFile = await local.CreateFileAsync("SpreadsheetSample.xlsx", CreationCollisionOption.ReplaceExisting);
            }
            if (storageFile != null)
            {
                IWorksheet sheet = book.Worksheets[0];
                sheet["G1"].ColumnWidth = 10;
                //XlsIO saves the file Asynchronously
                await book.SaveAsAsync(storageFile);

                book.Close();
                excelEngine.Dispose();
                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);
                }
            }
        }
Exemple #59
0
 public UICommandEventArgs(UICommand command)
 {
     Command = command;
 }
        /// <summary>
        /// Export the UI data to Word document.
        /// </summary>
        /// <param name="invoiceItems">The InvoiceItems.</param>
        /// <param name="billInfo">The BillingInformation.</param>
        /// <param name="totalDue">The TotalDue.</param>
        public async void CreateWord(IList <InvoiceItem> invoiceItems, BillingInformation billInfo, double totalDue)
        {
            //Load Template document stream

            Stream inputStream = typeof(MainPage).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.DocIO.DocIO.Invoice.Assets.Template.docx");

            //Create instance
            WordDocument document = new WordDocument();
            //Open Template document
            await document.OpenAsync(inputStream, FormatType.Word2013);

            //Dispose input stream
            inputStream.Dispose();

            //Set Clear Fields to false
            document.MailMerge.ClearFields = false;
            //Create Mail Merge Data Table
            MailMergeDataTable mailMergeDataTable = new MailMergeDataTable("Invoice", invoiceItems);

            //Executes mail merge using the data generated in the app.
            document.MailMerge.ExecuteGroup(mailMergeDataTable);

            //Mail Merge Billing information
            string[] fieldNames  = { "Name", "Address", "Date", "InvoiceNumber", "DueDate", "TotalDue" };
            string[] fieldValues = { billInfo.Name, billInfo.Address, billInfo.Date.ToString("d"), billInfo.InvoiceNumber, billInfo.DueDate.ToString("d"), totalDue.ToString("#,###.00", CultureInfo.InvariantCulture) };
            document.MailMerge.Execute(fieldNames, fieldValues);

            StorageFile stgFile = null;

            if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
            {
                FileSavePicker savePicker = new FileSavePicker();
                savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                // Dropdown of file types the user can save the file as
                savePicker.FileTypeChoices.Add("Invoice", new List <string>()
                {
                    ".docx"
                });
                // Default file name if the user does not type one in or select a file to replace
                savePicker.SuggestedFileName = "Invoice";
                stgFile = await savePicker.PickSaveFileAsync();
            }
            else
            {
                StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                stgFile = await local.CreateFileAsync("Invoice.docx", CreationCollisionOption.ReplaceExisting);
            }
            if (stgFile != null)
            {
                //Save as Docx format
                await document.SaveAsync(stgFile, FormatType.Word2013);

                //Close instance
                document.Close();

                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(stgFile);
                }
            }
        }