Esempio n. 1
0
        public string GetFileSavePath(string title, string defaultExt, string filter)
        {
            if (VistaFileDialog.IsVistaFileDialogSupported)
            {
                var saveFileDialog = new VistaSaveFileDialog
                                     {
                                         Title = title,
                                         DefaultExt = defaultExt,
                                         CheckFileExists = false,
                                         RestoreDirectory = true,
                                         Filter = filter
                                     };

                if (saveFileDialog.ShowDialog() == true)
                    return saveFileDialog.FileName;
            }
            else
            {
                var ofd = new Microsoft.Win32.SaveFileDialog
                          {
                              Title = title,
                              DefaultExt = defaultExt,
                              CheckFileExists = false,
                              RestoreDirectory = true,
                              Filter = filter
                          };

                if (ofd.ShowDialog() == true)
                    return ofd.FileName;
            }

            return "";
        }
Esempio n. 2
0
        public void SaveCurrentDocument()
        {
            // Configure save file dialog box
            var dlg = new Microsoft.Win32.SaveFileDialog
            {
                FileName = "Faktura",
                DefaultExt = ".xps",
                Filter = "XPS Documents (.xps)|*.xps"
            };

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                string filename = dlg.FileName;

                FixedDocument doc = CreateMyWPFControlReport();
                File.Delete(filename);
                var xpsd = new XpsDocument(filename, FileAccess.ReadWrite);
                XpsDocumentWriter xw = XpsDocument.CreateXpsDocumentWriter(xpsd);

                xw.Write(doc);
                xpsd.Close();
            }
        }
Esempio n. 3
0
 public bool Execute()
 {
     SaveFileDialog dialog = new SaveFileDialog();
     dialog.FileName = "export.csv";
     dialog.Filter = "*.csv|*.csv|All files|*.*";
     if (dialog.ShowDialog() == true)
     {
         try
         {
             using (TextWriter writer = File.CreateText(dialog.FileName))
             {
                 writer.WriteLine("File,Time,TimeDif");
                 for (int i = 0; i < ServiceProvider.Settings.DefaultSession.Files.Count; i++)
                 {
                     var file = ServiceProvider.Settings.DefaultSession.Files[i];
                     writer.WriteLine("{0},{1},{2}", file.FileName, file.FileDate.ToString("O"),
                         (i > 0
                             ? Math.Round(
                                 (file.FileDate - ServiceProvider.Settings.DefaultSession.Files[i - 1].FileDate)
                                     .TotalMilliseconds, 0)
                             : 0));
                 }
                 PhotoUtils.Run(dialog.FileName);
             }
         }
         catch (Exception ex)
         {
             MessageBox.Show("Error to export " + ex.Message);
             Log.Error("Error to export ", ex);
         }
     }
     return true;
 }
        /// <summary>
        /// Presents the user with a folder browser dialog.
        /// </summary>
        /// <param name="filter">Filename filter for if the OS doesn't support a folder browser.</param>
        /// <returns>Full path the user selected.</returns>
        private static string ShowFolderBrowser(string filter)
        {
            bool cancelled = false;
            string path = null;

            if (VistaFolderBrowserDialog.IsVistaFolderDialogSupported)
            {
                var dlg = new VistaFolderBrowserDialog();

                cancelled = !(dlg.ShowDialog() ?? false);

                if (!cancelled)
                {
                    path = Path.GetFullPath(dlg.SelectedPath);
                }
            }
            else
            {
                var dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.Filter = filter;
                dlg.FilterIndex = 1;

                cancelled = !(dlg.ShowDialog() ?? false);

                if (!cancelled)
                {
                    path = Path.GetFullPath(Path.GetDirectoryName(dlg.FileName)); // Discard whatever filename they chose
                }
            }

            return path;
        }
Esempio n. 5
0
        void SetConfigurationMenu(MainWindowViewModel viewModel)
        {
            ConfigurationContextMenu.Items.Clear();
            foreach (var item in viewModel.Configrations)
            {
                ConfigurationContextMenu.Items.Add(new MenuItem { FontSize = 12, Header = item.Item1, Command = item.Item2 });
            }
            ConfigurationContextMenu.Items.Add(new Separator());
            var saveCommand = new ReactiveCommand();
            saveCommand.Subscribe(_ =>
            {
                var dialog = new Microsoft.Win32.SaveFileDialog();
                dialog.FilterIndex = 1;
                dialog.Filter = "JSON Configuration|*.json";
                dialog.InitialDirectory = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "configuration");

                if (dialog.ShowDialog() == true)
                {
                    var fName = dialog.FileName;
                    if (!fName.EndsWith(".json")) fName = fName + ".json";
                    viewModel.SaveCurrentConfiguration(fName);
                    viewModel.LoadConfigurations();
                    SetConfigurationMenu(viewModel); // reset
                }
            });
            ConfigurationContextMenu.Items.Add(new MenuItem { FontSize = 12, Header = "Save...", Command = saveCommand });
        }
Esempio n. 6
0
        private void MenuItem_Click_2(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "NewFile";
            dlg.DefaultExt = ".txt";
            dlg.Filter = "Text document (.txt)|*.txt";

            Nullable<bool> result = dlg.ShowDialog();

            if (result == true)
            {
                filename = dlg.FileName;
            }
            try
            {
                FileStream fs = new FileStream(filename, FileMode.Create);
                StreamWriter outstr = new StreamWriter(fs);
                outstr.Write(textBox1.Text);
                outstr.Close();
                fs.Close();
            }
            catch (Exception error)
            {
                MessageBox.Show(error.ToString());
            }
        }
Esempio n. 7
0
        private void btnExcelBS_Click( object sender, RoutedEventArgs e )
        {
            if ( Data.FocusedQuery == null ) return;

            Microsoft.Win32.SaveFileDialog fd = new Microsoft.Win32.SaveFileDialog( );
            fd.InitialDirectory = Environment.GetFolderPath( System.Environment.SpecialFolder.Desktop );
            fd.FileName = DefaultExcelFileName( );
            fd.ShowDialog( );
            var ci = this.Data.FocusedQuery.GoogleQuery.CompanyInfo;

            var blah = fd.ShowDialog( );
            if ( fd.ShowDialog( ).Value )
            {
                KNMFinExcel.Google.ExcelGoogle.SaveBalanceSheets( fd.FileName, ci );
            }
        }
 private  async void buttonExport_Click(object sender, RoutedEventArgs e)
 {
     var model = getModel();
     if ((model != null) && (model.Count > 1))
     {
         try
         {
             Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
             dlg.DefaultExt = ".tsv";
             dlg.Filter = "Tab Separated values (*.tsv)|*.tsv";
             Nullable<bool> result = dlg.ShowDialog();
             String filename = null;
             if ((result != null) && result.HasValue && (result.Value == true))
             {
                 filename = dlg.FileName;
             }
             if (!String.IsNullOrEmpty(filename)){
                 this.buttonExport.IsEnabled = false;
                  await performExport(model, filename);
             }
         }
         catch (Exception/* ex */)
         {
         }
         this.buttonExport.IsEnabled = true;
     }//model
 }
Esempio n. 9
0
		public override bool Save()
		{
			/*
			 * If the file is still undefined, open a save file dialog
			 */
			if (IsUnboundNonExistingFile)
			{
				var sf = new Microsoft.Win32.SaveFileDialog();
				sf.Filter = "All files (*.*)|*.*";
				sf.FileName = AbsoluteFilePath;

				if (!sf.ShowDialog().Value)
					return false;
				else
				{
					AbsoluteFilePath = sf.FileName;
					Modified = true;
				}
			}
			try
			{
				if (Modified)
				{
					Editor.Save(AbsoluteFilePath);
					lastWriteTime = File.GetLastWriteTimeUtc(AbsoluteFilePath);
				}
			}
			catch (Exception ex) { ErrorLogger.Log(ex); return false; }
			Modified = false;
			return true;
		}
Esempio n. 10
0
        public string GetSaveFilePath(string exporttype)
        {
            Dictionary<string, string> type = new Dictionary<string, string>()
            {
                {"HTML", "HTML|*.html"},
                {"TXT", "TXT|*.txt"}
            };

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

            dlg.FileName = "accounts"; // Default file name
            dlg.DefaultExt = type[exporttype].Split('*')[1]; // Default file extension
            dlg.Filter = type[exporttype]; // Filter files by extension

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                return dlg.FileName;

            }
            else
            {
                return null;
            }
        }
Esempio n. 11
0
 private void btnExport_Click(object sender, RoutedEventArgs e)
 {
     var dlg = new Microsoft.Win32.SaveFileDialog();
     dlg.DefaultExt = "xlsx";
     dlg.Filter = "Excel Workbook (*.xlsx)|*.xlsx|" + "HTML File (*.htm;*.html)|*.htm;*.html|" + "Comma Separated Values (*.csv)|*.csv|" + "Text File (*.txt)|*.txt";
     if (dlg.ShowDialog() == true)
     {
         var ext = System.IO.Path.GetExtension(dlg.SafeFileName).ToLower();
         ext = ext == ".htm" ? "ehtm" : ext == ".html" ? "ehtm" : ext;
         switch (ext)
         {
             case "ehtm":
                 {
                     C1FlexGrid1.Save(dlg.FileName, C1.WPF.FlexGrid.FileFormat.Html, SaveOptions.Formatted);
                     break;
                 }
             case ".csv":
                 {
                     C1FlexGrid1.Save(dlg.FileName, C1.WPF.FlexGrid.FileFormat.Csv, SaveOptions.Formatted);
                     break;
                 }
             case ".txt":
                 {
                     C1FlexGrid1.Save(dlg.FileName, C1.WPF.FlexGrid.FileFormat.Text, SaveOptions.Formatted);
                     break;
                 }
             default:
                 {
                     Save(dlg.FileName,C1FlexGrid1);
                     break;
                 }
         }
     }
 }
Esempio n. 12
0
        bool zapis_zawartosci(byte[] zawartosc)
        {
            var dlg = new Microsoft.Win32.SaveFileDialog();
            // Set filter for file extension and default file extension 

            // Display OpenFileDialog by calling ShowDialog method 
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox 
            if (result == true)
            {
                // Open document 
                filename = dlg.FileName;
                var file = File.Open(filename, FileMode.OpenOrCreate);
                var plik = new BinaryWriter(file);
                plik.Write(zawartosc);
                plik.Close();
                return true;
            }
            else
            {
                MessageBox.Show("Problem z zapisaniem pliku");
                return false;
            }
        }
Esempio n. 13
0
        private void NewRAWRItem_Click(object sender, RoutedEventArgs e)
        {
            // Open a file chooser to choose where to put the RAWR system
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "RAWR";
            dlg.DefaultExt = ".img";
            dlg.Filter = "Virtual Image Files (.img)|*.img";
            dlg.Title = "Create New RAWR Virtual Disc";

            // Show file chooser
            Nullable<bool> result = dlg.ShowDialog();

            // Format the RAWR system on selected filename if selected
            if (result == true)
            {
                // Show my progress window of formatting my RAWR filesystem
                pgFormatRAWR.Show();

                // Create a BackgroundWorker that will create my RAWR file system
                BackgroundWorker rawrWriter = new BackgroundWorker();

                rawrWriter.DoWork += new DoWorkEventHandler(rawrWriter_DoWork);
                rawrWriter.ProgressChanged += new ProgressChangedEventHandler(rawrWriter_ProgressChanged);
                rawrWriter.RunWorkerCompleted += new RunWorkerCompletedEventHandler(rawrWriter_RunWorkerCompleted);

                rawrWriter.WorkerReportsProgress = true;
                rawrWriter.RunWorkerAsync(dlg.FileName); // Passing in my file name to the worker
            }
        }
        /// <summary>
        /// Scripter: YONGTOK KIM
        /// Description : Save the image to the file.
        /// </summary>

        public static string SaveImageCapture(BitmapSource bitmap)
        {
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;


            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "Image"; // Default file name
            dlg.DefaultExt = ".Jpg"; // Default file extension
            dlg.Filter = "Image (.jpg)|*.jpg"; // Filter files by extension

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save Image
                string filename = dlg.FileName;
                FileStream fstream = new FileStream(filename, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();

                return filename;
            }

            return null;
        }
Esempio n. 15
0
        /// <summary>
        /// ドロップ情報をCSVに出力する
        /// </summary>
        /// <param name="dropList"></param>
        public static void OutputCsv(List<DatDropData> dropList)
        {
            if (dropList.Count == 0)
            {
                MessageBox.Show("ドロップ情報が0件のため、処理を中止します。");
                return;
            }

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            //保存先の初期値(マイドキュメント)
            dlg.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            dlg.Title = "保存先のファイルを選択してください";
            dlg.FileName = "ドロップ情報";
            dlg.Filter = "CSVファイル(*.csv)|*.csv";
            if (dlg.ShowDialog() == true)
            {
                try
                {
                    using (var sw = new System.IO.StreamWriter(dlg.FileName, false, System.Text.Encoding.GetEncoding("Shift_JIS")))
                    {
                        //ダブルクォーテーションで囲む
                        Func<string, string> dqot = (str) => { return "\"" + str.Replace("\"", "\"\"") + "\""; };
                        foreach (DatDropData d in dropList)
                            sw.WriteLine(dqot(d.DropWinDecision) + "," + dqot(d.DropKanmusuName));
                    }
                    MessageBox.Show("保存しました。");
                }
                catch (SystemException ex)
                {
                    MessageBox.Show(ClsConst.ErrorMessage);
                    ClsLogWrite.LogWrite("CSV出力中にエラーが起きました。",ex);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Skapar en CreateHistorical data och sparar ner och strukturerar data i en excelfil
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLaddaNer_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result;
            if (!string.IsNullOrEmpty(txtSymbol.Text) && fromDate.SelectedDate.HasValue && toDate.SelectedDate.HasValue && !string.IsNullOrEmpty(format))
            {

                CreateHistoricalData hd = new CreateHistoricalData(txtSymbol.Text, fromDateStr, toDateStr, format);

                Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
                saveFileDialog.DefaultExt = ".xlsx";
                saveFileDialog.Filter = "Jespers Excelfil(.xlsx)|*.xlsx";
                if (saveFileDialog.ShowDialog() == true)
                {
                    try
                    {
                        hd.CreateExcel(saveFileDialog.FileName);
                    }
                    catch (WebException)
                    {
                        result = MessageBox.Show("Det finns ingen aktie med denna symbol, använd sökfältet. ", "FEL!", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    catch (Exception ex)
                    {
                        result = MessageBox.Show("Något gick fel "+ex.ToString(), "FEL!", MessageBoxButton.OK, MessageBoxImage.Error);
                        return;
                    }
                    result = MessageBox.Show("Din fil är sparad "+saveFileDialog.FileName, "Grattis!", MessageBoxButton.OK, MessageBoxImage.Information);
                }

            }
        }
		private void btnExportToPdf_Click(object sender, System.Windows.RoutedEventArgs e)
		{
            Model.Patient selectedPatient = GetSelectedPatient();

            if (selectedPatient != null)
            {
                try
                {
                    // Configure save file dialog box
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.FileName = selectedPatient.FullName + "_" + DateTime.Now.ToString("dd-MMMM-yyyy"); // Default file name
                    dlg.DefaultExt = ".pdf"; // Default file extension
                    dlg.Filter = "Text documents (.pdf)|*.pdf"; // Filter files by extension

                    if (dlg.ShowDialog() == true)
                    {
                        ExportToPdf(dlg.FileName, selectedPatient);
                        MessageBox.Show("PDF generado", "Información", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("No se pudo generar el PDF.\n\n Detalle del error:\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
		}
Esempio n. 18
0
 public void Execute(CommandContext ctx)
 {
     Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
     string defaultFileName = string.Format("RegexTester_{0}", DateTime.Now.ToString("yyyy_MM_dd__HH_mm_ss"));
     dlg.FileName = defaultFileName;
     dlg.DefaultExt = ".txt";
     dlg.Filter = "Text documents (.txt)|*.txt";
     Nullable<bool> result = dlg.ShowDialog();
     if (result == true)
     {
         string fileName = dlg.FileName;
         StringBuilder sb = new StringBuilder();
         sb.Append("Regex Tester: version=").AppendLine(GetVersion())
           .AppendLine(new String('-', 40))
           .Append("REGEX MODE: ").AppendLine(ctx.RegexMode.ToString())
           .Append("REGEX OPTIONS: ").AppendLine(ctx.RegexOptions.ToString())
           .Append("INPUT REGEX: ").AppendLine(ctx.InputRegex)
           .Append("INPUT FORMAT: ").AppendLine(ctx.InputFormat)
           .AppendLine(string.Format("{0}INPUT TEXT{1}", PREFIX, POSTFIX))
           .AppendLine(ctx.InputText)
           .AppendLine(string.Format("{0}OUTPUT TEXT{1}", PREFIX, POSTFIX))
           .Append(ctx.OutputText);
         File.WriteAllText(fileName, sb.ToString(), Encoding.UTF8);
     }
 }
Esempio n. 19
0
        public static void saveSlides(Microsoft.Office.Interop.PowerPoint.Presentation presentation)
        {
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            //string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string filePath = desktopPath + "\\Slides.pptx";

            // Microsoft.Office.Interop.PowerPoint.FileConverter fc = new Microsoft.Office.Interop.PowerPoint.FileConverter();
            // if (fc.CanSave) { }
            //https://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog(v=vs.110).aspx

            //Browse Files
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.InitialDirectory = desktopPath+"\\Scano";
            dlg.DefaultExt = ".pptx";
            dlg.Filter = "PPTX Files (*.pptx)|*.pptx";
            Nullable<bool> result = dlg.ShowDialog();
            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                filePath = dlg.FileName;
                //textBox1.Text = filename;
            }
            else
            {
                System.Console.WriteLine("Couldn't show the dialog.");
            }

            presentation.SaveAs(filePath,
            Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
            Microsoft.Office.Core.MsoTriState.msoTriStateMixed);
            System.Console.WriteLine("PowerPoint application saved in {0}.", filePath);
        }
Esempio n. 20
0
        private void btnDestination_Click(object sender, RoutedEventArgs e)
        {
            var saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.FileName = "Select File to Convert";

            Nullable<bool> result = saveFileDialog.ShowDialog();

            if (result == true)
            {
                entDestination.Text = saveFileDialog.FileName.ToLower();
                if (!(entDestination.Text.EndsWith(".shp") ||
                       entDestination.Text.EndsWith(".kml")))
                {
                    entDestination.Text = "Extension Must be SHP or KML";
                    btnConvert.IsEnabled = false;
                }
                else
                {
                    if (entSource.Text.EndsWith(".shp") ||
                           entSource.Text.EndsWith(".kml"))
                    {
                        btnConvert.IsEnabled = true;
                    }
                }
            }
        }
Esempio n. 21
0
        public string GetFileSavePath(string title, string defaultExt, string filter)
        {
            if (VistaSaveFileDialog.IsVistaFileDialogSupported)
            {
                VistaSaveFileDialog saveFileDialog = new VistaSaveFileDialog();
                saveFileDialog.Title = title;
                saveFileDialog.DefaultExt = defaultExt;
                saveFileDialog.CheckFileExists = false;
                saveFileDialog.RestoreDirectory = true;

                saveFileDialog.Filter = filter;

                if (saveFileDialog.ShowDialog() == true)
                    return saveFileDialog.FileName;
            }
            else
            {
                Microsoft.Win32.SaveFileDialog ofd = new Microsoft.Win32.SaveFileDialog();
                ofd.Title = title;
                ofd.DefaultExt = defaultExt;
                ofd.CheckFileExists = false;
                ofd.RestoreDirectory = true;

                ofd.Filter = filter;

                if (ofd.ShowDialog() == true)
                    return ofd.FileName;
            }

            return "";
        }
Esempio n. 22
0
        public static void SaveImageCapture(BitmapSource bitmap)
        {
            var encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.QualityLevel = 100;

            // Configure save file dialog box
            var dlg = new Microsoft.Win32.SaveFileDialog
            {
                FileName = "Image",
                DefaultExt = ".Jpg",
                Filter = "Image (.jpg)|*.jpg"
            };

            // Show save file dialog box
            var result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save Image
                string filename = dlg.FileName;
                var fstream = new FileStream(filename, FileMode.Create);
                encoder.Save(fstream);
                fstream.Close();
            }
        }
		private async void ExportEventLogButton_Click(object sender, RoutedEventArgs e)
		{
			XDocument doc = new XDocument(
				new XDeclaration("1.0", "UTF-8", "true"),
				new XElement("LogEntries",
					from entry in (this.DataContext as MainViewModel).LogEntries
					select new XElement("LogEntry",
						new XElement("Date", entry.EventDateTimeUTC),
						new XElement("Type", entry.Level),
						new XElement("DeploymentId", entry.DeploymentId),
						new XElement("Role", entry.Role),
						new XElement("Instance", entry.RoleInstance),
						new XElement("Message", entry.Message)
					)
				)
			);

			// Configure save file dialog box
			Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
			dlg.FileName = "Export.xml";

			// Show save file dialog box
			if (dlg.ShowDialog() == true)
			{
				doc.Save(dlg.FileName);
			}
		}
Esempio n. 24
0
        private void OnCommand()
        {
            // Configure open file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = _viewModel.Workspace.Path; // Default file name
            dlg.DefaultExt = ".jws"; // Default file extension
            dlg.Filter = "Jade Workspace files (.jws)|*.jws"; // Filter files by extension
            dlg.CheckFileExists = true;
            dlg.CheckPathExists = true;

            // Show open file dialog box
            Nullable<bool> result = dlg.ShowDialog();
            
            // Process open file dialog box results
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;

                try
                {
                    JadeData.Workspace.IWorkspace workspace = JadeData.Persistence.Workspace.Reader.Read(filename);
                    _viewModel.Workspace = new JadeControls.Workspace.ViewModel.Workspace(workspace);
                }
                catch (System.Exception e)
                {

                }
            }
        }
Esempio n. 25
0
        public static Boolean DumpDataToFile(object data)
        {
            if (data != null)
            {
                // Configure save file dialog box
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = "calibrate_rawdatadump"; // Default file name
                dlg.DefaultExt = ".csv"; // Default file extension
                dlg.Filter = "CSV documents (.csv)|*.csv|XML documents (.xml)|*.xml"; // Filter files by extension

                // Show save file dialog box
                Nullable<bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    if (Path.GetExtension(dlg.FileName).ToLower() == ".csv")
                    {
                        return DataDumper.ToCsv(dlg.FileName, data);
                    }
                    else
                    {
                        return DataDumper.ToXml(dlg.FileName, data);
                    }
                }
            }
            return false;
        }
Esempio n. 26
0
 private void button2_Click(object sender, RoutedEventArgs e)
 {
     if (listBox1.SelectedItem != null)
     {
         Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();
         dialog.FileName = "Блок " + block_index + " запись " + (listBox1.SelectedIndex + 1);
         //dialog.DefaultExt = ".";
         dialog.Filter = "Все файлы (*.*)|*.*";
         dialog.Title = "Выберите файл для сохранения данных";
         Nullable<bool> result = dialog.ShowDialog();
         if (result == true)
         {
             selected_record = links[listBox1.SelectedIndex];
             file2save = dialog.FileName;
             Thread saving = new Thread(save_thread);
             saving.Start();
         }
         else
         {
             addText("\n" + get_time() + " Не выбран файл для сохранения.");
         }
     }
     else
         addText("\n" + get_time() + " Не выбрана запись для сохранения.");
 }
        private void btnAddNew_Click(object sender, RoutedEventArgs e)
        {
            // Create OpenFileDialog
            var dlg = new Microsoft.Win32.SaveFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".mdb";
            dlg.Filter = "TestFrame Databases (.mdb)|*.mdb";

            // Display OpenFileDialog by calling ShowDialog method
            Nullable<bool> result = dlg.ShowDialog();

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                // Open document
                string filename = dlg.FileName;
                string shortname = Globals.InputBox("Enter shortname for database:");
                Parallel.Invoke( () => {
                        TFDBManager.NewDatabase(shortname, filename);
                    });

                FillList();
                listDatabases.SelectedValue = shortname;

            }
        }
Esempio n. 28
0
        public static void SaveAsImage(FrameworkElement visual)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".png";
            dlg.Filter = "PNG Image (.png)|*.png|JPEG Image (.jpg)|*.jpg";

            if (dlg.ShowDialog().Value)
            {
                BitmapSource img = (BitmapSource)ToImageSource(visual);

                FileStream stream = new FileStream(dlg.FileName, FileMode.Create);
                BitmapEncoder encoder = null; // new BitmapEncoder();

                if (dlg.SafeFileName.ToLower().EndsWith(".png"))
                {
                    encoder = new PngBitmapEncoder();
                }
                else
                {
                    encoder = new JpegBitmapEncoder();
                }

                encoder.Frames.Add(BitmapFrame.Create(img));
                encoder.Save(stream);
                stream.Close();
            }
        }
Esempio n. 29
0
        public static bool ExportData()
        {

            // Configure save file dialog box
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = "SearchData"; // Default file name
            dlg.DefaultExt = ".txt"; // Default file extension
            dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension 

            // Show save file dialog box
            Nullable<bool> result = dlg.ShowDialog();

            // Process save file dialog box results 
            if (result == true)
            {
                // Save document 
                string filename = dlg.FileName;
                using (StreamWriter sw = new StreamWriter(filename))
                {
                    sw.WriteLine("[" + comboIndex + "] " + commName);
                    sw.WriteLine();
                    sw.WriteLine("\t" + perCapitaIncome);
                    sw.WriteLine("\t" + hardshipIndex);
                    sw.WriteLine("\t" + crimesName);

                    foreach (Database.CrimeType ct in crimes)
                    {
                        sw.WriteLine("\t\t" + ct.CrimeName + ": " + ct.CrimeCount.ToString() + " [" + ct.Percentage + "%]");
                    }
                }
                return true;
            }
            return false;
        }
Esempio n. 30
0
        private void _btnSave_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".csv";
            dlg.Filter =
                "Comma Separated Values (*.csv)|*.csv|" +
                "Plain text (*.txt)|*.txt|" +
                "HTML (*.html)|*.html";
            if (dlg.ShowDialog() == true)
            {
                // select format based on file extension
                var fileFormat = FileFormat.Csv;
                switch (System.IO.Path.GetExtension(dlg.SafeFileName).ToLower())
                {
                    case ".htm":
                    case ".html":
                        fileFormat = FileFormat.Html;
                        break;
                    case ".txt":
                        fileFormat = FileFormat.Text;
                        break;
                }

                // save the file
                using (var stream = dlg.OpenFile())
                {
                    _flex.Save(stream, fileFormat);
                }
            }
        }
Esempio n. 31
0
 private void ExecutedSaveCommand(object sender, ExecutedRoutedEventArgs e)
 {
     try
     {
         var dialog = new Microsoft.Win32.SaveFileDialog();
         if (dialog?.ShowDialog() ?? false)
         {
             _main.Save(dialog.FileName);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error ButtonSave" + ex.Message);
     }
     finally
     {
         ErrorMsg();
     }
 }
        private void saveResultsToTextFile(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.DefaultExt = "txt";
            saveFileDialog.FileName   = "wyniki";
            saveFileDialog.Filter     = "Plik tekstowy (*.txt)|*.txt";

            if (saveFileDialog.ShowDialog() == true)
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("Zestaw uczący L: [");

                for (int i = 0; i < amountOfLearningPoints; i++)
                {
                    stringBuilder.Append("(" + learningSet[i, 0] + "," + learningSet[i, 1] + ")");

                    if (i != amountOfLearningPoints - 1)
                    {
                        stringBuilder.Append(", ");
                    }
                }

                stringBuilder.AppendLine("]");

                stringBuilder.Append(
                    "Epoka".PadRight(10) + "|" +
                    "t".PadRight(10) + "|" +
                    "x0(t)".PadRight(10) + "|" +
                    "x1(t)".PadRight(10) + "|" +
                    "x2(t)".PadRight(10) + "|" +
                    "d(t)".PadRight(10) + "|" +
                    "w0(t)".PadRight(10) + "|" +
                    "w1(t)".PadRight(10) + "|" +
                    "w2(t)".PadRight(10) + "|" +
                    "s(t)".PadRight(10) + "|" +
                    "y(t)".PadRight(10) + "|" +
                    "ok?".PadRight(10) + "\n"
                    );

                int iterationCount = 0;
                foreach (SingleIteration singleIteration in iterationHistory)
                {
                    stringBuilder.Append(
                        ((int)(iterationCount / amountOfLearningPoints)).ToString().PadRight(10) + "|" +
                        iterationCount.ToString().PadRight(10) + "|" +
                        singleIteration.inputs[0].ToString().PadRight(10) + "|" +
                        singleIteration.inputs[1].ToString().PadRight(10) + "|" +
                        singleIteration.inputs[2].ToString().PadRight(10) + "|" +
                        singleIteration.expectedResult.ToString().PadRight(10) + "|" +
                        singleIteration.weights[0].ToString().PadRight(10) + "|" +
                        singleIteration.weights[1].ToString().PadRight(10) + "|" +
                        singleIteration.weights[2].ToString().PadRight(10) + "|" +
                        singleIteration.sumResult.ToString().PadRight(10) + "|" +
                        singleIteration.uniPolarResult.ToString().PadRight(10) + "|" +
                        singleIteration.isOK.ToString().PadRight(10) + "\n"
                        );

                    iterationCount++;
                }

                File.WriteAllText(saveFileDialog.FileName, stringBuilder.ToString());
            }
        }
Esempio n. 33
0
        private void menu_check(object sender, RoutedEventArgs e)
        {
            menuType tmp = (menuType)(int.Parse((sender as MenuItem).Tag.ToString()));
            //MessageBox.Show(tmp.ToString());
            Process myProcess;

            switch (tmp)
            {
            case menuType.MENU_CALIBRATION:
                EvoCalibrationWin wina = new EvoCalibrationWin(_my._MachineInfo);
                wina.Show();
                break;

            case menuType.MENU_IMPORT:
                Microsoft.Win32.OpenFileDialog op = new Microsoft.Win32.OpenFileDialog();
                op.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + "outport";
                op.Filter           = "evos File|*.evos";
                op.FilterIndex      = 1;
                if ((bool)op.ShowDialog())
                {
                    string savePath = op.FileName;
                    if (MessageBox.Show("Overwrite the current config?", "Hint", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        FunctionFileManage.ImpportDB(savePath);
                    }
                }
                break;

            case menuType.MENU_EXPORT:
                Microsoft.Win32.SaveFileDialog openFileDialog = new Microsoft.Win32.SaveFileDialog();
                openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + "outport";
                openFileDialog.Filter           = "evos File|*.evos";
                openFileDialog.FilterIndex      = 1;

                if ((bool)openFileDialog.ShowDialog())
                {
                    string savePath = openFileDialog.FileName;
                    FunctionFileManage.ExportDB(savePath);
                }
                break;

            case menuType.MENU_COM:
                _my.ComCmd.Execute(513);
                break;

            case menuType.MENU_VISUAL:
                myProcess = new Process();
                try
                {
                    myProcess.StartInfo.UseShellExecute = false;
                    myProcess.StartInfo.FileName        = "GIFConverter.exe";
                    myProcess.StartInfo.CreateNoWindow  = true;
                    myProcess.Start();
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1.Message);
                }
                break;

            case menuType.MENU_PIC:
                myProcess = new Process();
                try
                {
                    myProcess.StartInfo.UseShellExecute = false;
                    myProcess.StartInfo.FileName        = "EVO.TOOL.MAKEPIC.exe";
                    myProcess.StartInfo.CreateNoWindow  = true;
                    myProcess.Start();
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1.Message);
                }
                break;

            case menuType.MENU_USB:
                myProcess = new Process();
                try
                {
                    myProcess.StartInfo.UseShellExecute = false;
                    myProcess.StartInfo.FileName        = "EVO.TOOL.USBFILE.exe";
                    myProcess.StartInfo.CreateNoWindow  = true;
                    myProcess.Start();
                }
                catch (Exception e1)
                {
                    Console.WriteLine(e1.Message);
                }
                break;

            case menuType.MENU_HELP:
                MessageBox.Show("Coming Soon!!!");
                break;

            case menuType.MENU_ABOUT:
                MessageBox.Show("Version:" + MajorVersion.ToString() + "." + MinorVersion.ToString() + " supported by Crem", "Infomation");
                break;

            default:
                break;
            }
        }
Esempio n. 34
0
        private bool SaveWorkflow()
        {
            bool IsSuccess = false;

            SaveXaml();

            if (string.IsNullOrEmpty(_idpeRule.Xaml))
            {
                MessageBox.Show("Can not save blank rule ", "Validation check", MessageBoxButton.OK, MessageBoxImage.Hand);
                return(IsSuccess);
            }

            if (!this._WorkflowDesigner.IsInErrorState())
            {
                TabItem ti = TabCtrl.SelectedItem as TabItem;
                if (ti.Header == "Designer")
                {
                    if (string.IsNullOrEmpty(_idpeRule.Name) || _idpeRule.Name == "New Rule Designer")
                    {
                        _idpeRule.Name = "new rule1";
                    }

                    _idpeRule.Xaml = this._WorkflowDesigner.Text;
                    RulesExtraInformation rulesExtraInformation = new RulesExtraInformation(_idpeRule);
                    _idpeRule.Name        = rulesExtraInformation.RuleName;
                    _idpeRule.Description = rulesExtraInformation.RuleDescription;

                    if (Keyboard.Modifiers == ModifierKeys.Control)
                    {
                        Save();
                    }
                    else
                    {
                        if (rulesExtraInformation.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            _idpeRule.Name        = rulesExtraInformation.RuleName;
                            _idpeRule.Description = rulesExtraInformation.RuleDescription;
                            Save();
                            rulesExtraInformation.Close();
                        }
                        else
                        {
                            return(false); //to avoid closing this form, we dont want to close and lose
                        }
                    }
                    if (RuleForm != null)
                    {
                        RuleForm.RefreshRules(RuleForm.txtSearch.Text);
                    }
                }
                else
                {
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.FileName   = _idpeRule.Name + ".xml";
                    dlg.DefaultExt = ".xml";
                    dlg.Filter     = "XML documents (.xml)|*.xml";

                    Nullable <bool> result = dlg.ShowDialog();

                    if (result == true)
                    {
                        this._WorkflowDesigner.Save(dlg.FileName);
                    }
                }

                IsSuccess          = true;
                _IsWorkflowChanged = false;
            }
            else
            {
                this.AddErrors();
                IsSuccess = false;
            }
            return(IsSuccess);
        }
        private void SaveButton_OnClick(object sender, RoutedEventArgs e)
        {
            MapType mapType = MapType.GM;

            if (GMType.IsChecked.Value)
            {
                mapType = MapType.GM;
            }
            else if (PlayerType.IsChecked.Value)
            {
                mapType = MapType.Player;
            }

            int tileSize;

            if (Size16.IsChecked.Value)
            {
                tileSize = 16;
            }
            else if (Size32.IsChecked.Value)
            {
                tileSize = 32;
            }
            else if (Size70.IsChecked.Value)
            {
                tileSize = 70;
            }
            else if (SizeCustom.IsChecked.Value)
            {
                if (!int.TryParse(SizeCustomTextBox.Text, out tileSize))
                {
                    MessageBox.Show(this, "Please input a valid custom pixel size.", "Tile size error");
                    return;
                }

                if (tileSize <= 0)
                {
                    MessageBox.Show(this, "Custom pixel size must be larger than zero.", "Tile size error");
                }
            }
            else
            {
                tileSize = TileHelper.UI_MAP_TILE_PIXELSIZE;
            }

            var dialog = new Microsoft.Win32.SaveFileDialog
            {
                Title        = "Choose save location",
                FileName     = "dungeon",
                DefaultExt   = ".png",
                AddExtension = true,
                Filter       = "All Files|*.*"
            };

            var result = dialog.ShowDialog();

            if (result != null && result.Value)
            {
                if (!dialog.FileName.EndsWith(".png"))
                {
                    dialog.FileName = dialog.FileName + ".png";
                }
                var image = GetImage(tileSize, mapType);
                BitmapHelper.SaveBitmapSource(image, dialog.FileName, TileHelper.UI_MAP_TILE_PIXELSIZE, tileSize);
            }
        }
Esempio n. 36
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender == ButtonPreset0)
            {
                TryPresetFromResource("preset0.xaml");
            }

            if (sender == ButtonPreset1)
            {
                TryPresetFromResource("preset1.xaml");
            }

            if (sender == ButtonFixNames)
            {
                ApplyRegexToXaml(
                    new Regex("Name=\"(\\w+)\"", RegexOptions.Multiline),
                    (Match m) =>
                {
                    return("");
                });
            }

            if (sender == ButtonFixRotTrans)
            {
                ApplyRegexToXaml(
                    new Regex("<RotateTransform\\s+Angle=\"([+-01234567890.]+)\\s+([+-01234567890.]+)\\s+" +
                              "([+-01234567890.]+)\"/>", RegexOptions.Multiline),
                    (Match m) =>
                {
                    var x = $"<RotateTransform Angle=\"{m.Groups[1].ToString()}\" " +
                            $"CenterX=\"{m.Groups[2].ToString()}\" " +
                            $"CenterY=\"{m.Groups[3].ToString()}\"/>";
                    return(x);
                });
            }

            if (sender == ButtonDisplay)
            {
                TryDisplayXaml();
            }

            if (sender == ButtonSave)
            {
                // choose filename
                var dlg = new Microsoft.Win32.SaveFileDialog();
                var fn  = "" + TextBlockFilename.Text;
                if (fn == "")
                {
                    fn = "new.xaml";
                }
                dlg.FileName   = fn;
                dlg.DefaultExt = "*.xaml";
                dlg.Filter     = "XAML file (*.xaml)|*.xaml|All files (*.*)|*.*";

                // save
                try
                {
                    if (true == dlg.ShowDialog())
                    {
                        // get text
                        var txt = "" + textEdit.Text;

                        // write
                        File.WriteAllText(dlg.FileName, txt);
                    }
                }
                catch
                {
                    DisplayInfo("Error writing file.");
                }
            }

            if (sender == ButtonTagFill)
            {
                InsertText(" Tag=\"StateToFill\"");
            }

            if (sender == ButtonTagStroke)
            {
                InsertText(" Tag=\"StateToStroke\"");
            }

            if (sender == ButtonTagTwoNozzleHoriz)
            {
                InsertText("<Ellipse xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" Canvas.Left=\"-2.9\" " +
                           "Width=\"5.5\" Canvas.Top=\"10.1\" Height=\"5.5\" Name=\"circle4145\" " +
                           "StrokeThickness=\"0.37247378\" Stroke=\"#FFFF0000\" StrokeMiterLimit=\"4\" Tag=\"Nozzle#1\"/>" +
                           Environment.NewLine +
                           "<Ellipse xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" Canvas.Left=\"22.3\" " +
                           "Width=\"5.5\" Canvas.Top=\"10.2\" Height=\"5.5\" Name=\"circle41459\" " +
                           "StrokeThickness=\"0.37247378\" Stroke=\"#FFFF0000\" StrokeMiterLimit=\"4\" Tag=\"Nozzle#2\"/>");
            }
        }
Esempio n. 37
0
        public AasxPluginResultBase ActivateAction(string action, params object[] args)
        {
            if (action == "set-json-options" && args != null && args.Length >= 1 && args[0] is string)
            {
                var newOpt = Newtonsoft.Json.JsonConvert.DeserializeObject <AasxPluginExportTable.ExportTableOptions>(
                    (args[0] as string));
                if (newOpt != null)
                {
                    this.options = newOpt;
                }
            }

            if (action == "get-json-options")
            {
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(
                    this.options, Newtonsoft.Json.Formatting.Indented);
                return(new AasxPluginResultBaseObject("OK", json));
            }

            if (action == "get-licenses")
            {
                var lic = new AasxPluginResultLicense();
                lic.shortLicense = "The OpenXML SDK is under MIT license." + Environment.NewLine +
                                   "The ClosedXML library is under MIT license.";

                lic.isStandardLicense = true;
                lic.longLicense       = AasxPluginHelper.LoadLicenseTxtFromAssemblyDir(
                    "LICENSE.txt", Assembly.GetExecutingAssembly());

                return(lic);
            }

            if (action == "get-events" && this.eventStack != null)
            {
                // try access
                return(this.eventStack.PopEvent());
            }

            if (action == "export-submodel" && args != null && args.Length >= 3 &&
                args[0] is IFlyoutProvider && args[1] is AdminShell.AdministrationShellEnv &&
                args[2] is AdminShell.Submodel)
            {
                // flyout provider
                var fop = args[0] as IFlyoutProvider;

                // which Submodel
                var env = args[1] as AdminShell.AdministrationShellEnv;
                var sm  = args[2] as AdminShell.Submodel;
                if (env == null || sm == null)
                {
                    return(null);
                }

                // the Submodel elements need to have parents
                sm.SetAllParents();

                // prepare list of items to be exported
                var list = new ExportTableAasEntitiesList();
                ExportTable_EnumerateSubmodel(list, env, broadSearch: false, depth: 1, sm: sm, sme: null);

                // handle the export dialogue
                var uc = new ExportTableFlyout();
                uc.Presets = this.options.Presets;
                fop?.StartFlyoverModal(uc);
                if (uc.Result == null)
                {
                    return(null);
                }
                var job = uc.Result;

                // get the output file
                var dlg = new Microsoft.Win32.SaveFileDialog();
                // ReSharper disable EmptyGeneralCatchClause
                try
                {
                    dlg.InitialDirectory = System.IO.Path.GetDirectoryName(
                        System.AppDomain.CurrentDomain.BaseDirectory);
                }
                catch { }
                // ReSharper enable EmptyGeneralCatchClause
                dlg.Title = "Select text file to be exported";

                if (job.Format == (int)ExportTableRecord.FormatEnum.TSF)
                {
                    dlg.FileName   = "new.txt";
                    dlg.DefaultExt = "*.txt";
                    dlg.Filter     =
                        "Tab separated file (*.txt)|*.txt|Tab separated file (*.tsf)|*.tsf|All files (*.*)|*.*";
                }
                if (job.Format == (int)ExportTableRecord.FormatEnum.LaTex)
                {
                    dlg.FileName   = "new.tex";
                    dlg.DefaultExt = "*.tex";
                    dlg.Filter     = "LaTex file (*.tex)|*.tex|All files (*.*)|*.*";
                }
                if (job.Format == (int)ExportTableRecord.FormatEnum.Excel)
                {
                    dlg.FileName   = "new.xlsx";
                    dlg.DefaultExt = "*.xlsx";
                    dlg.Filter     = "Microsoft Excel (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                }
                if (job.Format == (int)ExportTableRecord.FormatEnum.Word)
                {
                    dlg.FileName   = "new.docx";
                    dlg.DefaultExt = "*.docx";
                    dlg.Filter     = "Microsoft Word (*.docx)|*.docx|All files (*.*)|*.*";
                }

                fop?.StartFlyover(new EmptyFlyout());
                var res = dlg.ShowDialog(fop?.GetWin32Window());

                try
                {
                    if (res == true)
                    {
                        Log.Info("Exporting table: {0}", dlg.FileName);
                        var success = false;
                        try
                        {
                            if (job.Format == (int)ExportTableRecord.FormatEnum.TSF)
                            {
                                success = job.ExportTabSeparated(dlg.FileName, list);
                            }
                            if (job.Format == (int)ExportTableRecord.FormatEnum.LaTex)
                            {
                                success = job.ExportLaTex(dlg.FileName, list);
                            }
                            if (job.Format == (int)ExportTableRecord.FormatEnum.Excel)
                            {
                                success = job.ExportExcel(dlg.FileName, list);
                            }
                            if (job.Format == (int)ExportTableRecord.FormatEnum.Word)
                            {
                                success = job.ExportWord(dlg.FileName, list);
                            }
                        }
                        catch
                        {
                            success = false;
                        }

                        if (!success)
                        {
                            fop?.MessageBoxFlyoutShow(
                                "Some error occured while exporting the table. Please refer to the log messages.",
                                "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "When exporting table, an error occurred");
                }

                fop?.CloseFlyover();
            }

            // default
            return(null);
        }
        private void ImprimirFinalmente(List <ARTICULO> ArtExcel)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".xlsx";
            dlg.Filter     = "Documentos Excel (.xlsx)|*.xlsx";
            if (dlg.ShowDialog() == true)
            {
                string filename = dlg.FileName;
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                excel.Visible = false;

                Workbook  excelPrint      = excel.Workbooks.Open(@"C:\Programs\ElaraInventario\Resources\ExcelInventarioFisico.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                Worksheet excelSheetPrint = (Worksheet)excelPrint.Worksheets[1];

                //Folio
                excel.Cells[8, 6] = SelectedAlmacen.ALMACEN_NAME;
                //Fecha
                excel.Cells[8, 23] = DateTime.Now.ToShortDateString() + " - " + DateTime.Now.ToShortTimeString();

                int X = 11;
                Microsoft.Office.Interop.Excel.Borders borders;

                for (int i = 0; i < ArtExcel.Count; i++)
                {
                    //No.
                    excel.Range[excel.Cells[X, 2], excel.Cells[X, 3]].Merge();
                    excel.Range[excel.Cells[X, 2], excel.Cells[X, 3]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 2] = (i + 1).ToString() + ".-";
                    borders           = excel.Range[excel.Cells[X, 2], excel.Cells[X, 3]].Borders;
                    borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //ARTÍCULO
                    excel.Range[excel.Cells[X, 4], excel.Cells[X, 22]].Merge();
                    excel.Range[excel.Cells[X, 4], excel.Cells[X, 22]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 4] = ArtExcel[i].ARTICULO1;
                    borders           = excel.Range[excel.Cells[X, 4], excel.Cells[X, 22]].Borders;
                    borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //SKU
                    excel.Range[excel.Cells[X, 23], excel.Cells[X, 28]].Merge();
                    excel.Range[excel.Cells[X, 23], excel.Cells[X, 28]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    if (ArtExcel[i].CATEGORIA != null && ArtExcel[i].CATEGORIA.CATEGORIA_NAME != null)
                    {
                        excel.Cells[X, 23] = ArtExcel[i].CATEGORIA.CATEGORIA_NAME;
                    }
                    borders           = excel.Range[excel.Cells[X, 23], excel.Cells[X, 28]].Borders;
                    borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //No. de Serie
                    excel.Range[excel.Cells[X, 29], excel.Cells[X, 35]].Merge();
                    excel.Range[excel.Cells[X, 29], excel.Cells[X, 35]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    if (ArtExcel[i].MODELO != null && ArtExcel[i].MODELO.MODELO_NAME != null)
                    {
                        excel.Cells[X, 29] = ArtExcel[i].MODELO.MODELO_NAME;
                    }
                    borders           = excel.Range[excel.Cells[X, 29], excel.Cells[X, 35]].Borders;
                    borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //cantidad
                    excel.Range[excel.Cells[X, 36], excel.Cells[X, 41]].Merge();
                    excel.Range[excel.Cells[X, 36], excel.Cells[X, 41]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 36] = ArtExcel[i].EQUIPO.EQUIPO_NAME;
                    borders            = excel.Range[excel.Cells[X, 36], excel.Cells[X, 41]].Borders;
                    borders.LineStyle  = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                    ItemDataMapper iaux = new ItemDataMapper();

                    if (IsSKU)
                    {
                        //Moneda
                        excel.Range[excel.Cells[X, 42], excel.Cells[X, 47]].Merge();
                        excel.Range[excel.Cells[X, 42], excel.Cells[X, 47]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                        if (ArtExcel[i].CATEGORIA != null && ArtExcel[i].CATEGORIA.CATEGORIA_NAME != null)
                        {
                            excel.Cells[X, 42] = iaux.ExcelGetMonedaSKU(ArtExcel[i].CATEGORIA.CATEGORIA_NAME);
                        }
                        borders           = excel.Range[excel.Cells[X, 42], excel.Cells[X, 47]].Borders;
                        borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                        //Tipo de Cambio
                        excel.Range[excel.Cells[X, 48], excel.Cells[X, 53]].Merge();
                        excel.Range[excel.Cells[X, 48], excel.Cells[X, 53]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                        if (ArtExcel[i].CATEGORIA != null && ArtExcel[i].CATEGORIA.CATEGORIA_NAME != null)
                        {
                            excel.Cells[X, 48] = iaux.ExcelGetTcSKU(ArtExcel[i].CATEGORIA.CATEGORIA_NAME);
                        }
                        borders           = excel.Range[excel.Cells[X, 48], excel.Cells[X, 53]].Borders;
                        borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                        //Costo Unitario
                        excel.Range[excel.Cells[X, 54], excel.Cells[X, 59]].Merge();
                        excel.Range[excel.Cells[X, 54], excel.Cells[X, 59]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                        if (ArtExcel[i].CATEGORIA != null && ArtExcel[i].CATEGORIA.CATEGORIA_NAME != null)
                        {
                            excel.Cells[X, 54] = iaux.ExcelGetCostoUnitarioSKU(ArtExcel[i].CATEGORIA.CATEGORIA_NAME).ToString();
                        }
                        borders           = excel.Range[excel.Cells[X, 54], excel.Cells[X, 59]].Borders;
                        borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    }
                    else
                    {
                        //Moneda
                        excel.Range[excel.Cells[X, 42], excel.Cells[X, 47]].Merge();
                        excel.Range[excel.Cells[X, 42], excel.Cells[X, 47]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                        if (ArtExcel[i].MODELO != null && ArtExcel[i].MODELO.MODELO_NAME != null)
                        {
                            excel.Cells[X, 42] = iaux.ExcelGetMonedaNUMEROSERIE(ArtExcel[i].MODELO.MODELO_NAME);
                        }
                        borders           = excel.Range[excel.Cells[X, 42], excel.Cells[X, 47]].Borders;
                        borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                        //Tipo de Cambio
                        excel.Range[excel.Cells[X, 48], excel.Cells[X, 53]].Merge();
                        excel.Range[excel.Cells[X, 48], excel.Cells[X, 53]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                        if (ArtExcel[i].MODELO != null && ArtExcel[i].MODELO.MODELO_NAME != null)
                        {
                            excel.Cells[X, 48] = iaux.ExcelGetTcNUMEROSERIE(ArtExcel[i].MODELO.MODELO_NAME);
                        }
                        borders           = excel.Range[excel.Cells[X, 48], excel.Cells[X, 53]].Borders;
                        borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                        //Costo Unitario
                        excel.Range[excel.Cells[X, 54], excel.Cells[X, 59]].Merge();
                        excel.Range[excel.Cells[X, 54], excel.Cells[X, 59]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                        if (ArtExcel[i].MODELO != null && ArtExcel[i].MODELO.MODELO_NAME != null)
                        {
                            excel.Cells[X, 54] = iaux.ExcelGetCostoUnitarioNUMEROSERIE(ArtExcel[i].MODELO.MODELO_NAME).ToString();
                        }
                        borders           = excel.Range[excel.Cells[X, 54], excel.Cells[X, 59]].Borders;
                        borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    }

                    //ESTATUS
                    excel.Range[excel.Cells[X, 60], excel.Cells[X, 66]].Merge();
                    excel.Range[excel.Cells[X, 60], excel.Cells[X, 66]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                    if (Int32.Parse(ArtExcel[i].EQUIPO.EQUIPO_NAME) > 0)
                    {
                        excel.Cells[X, 60] = "Artículo en existencia";
                    }
                    else
                    {
                        excel.Cells[X, 60] = "Artículo extraviado";
                    }

                    borders           = excel.Range[excel.Cells[X, 60], excel.Cells[X, 66]].Borders;
                    borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    X++;
                }

                excelSheetPrint.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excel.Visible = true;
            }
        }
Esempio n. 39
0
        public void Import(Window parentWindow, ImportWizardContext context, IProgressObserver progress, Action <ImportStatusLevel, string> logFunc)
        {
            this.ParentWindow = parentWindow;
            this.Importer     = context.Importer;
            this.Mappings     = context.FieldMappings;
            this.Progress     = progress;
            this.LogFunc      = logFunc;


            if (Progress != null)
            {
                Progress.ProgressStart("Initialising...");
            }

            if (!InitImport())
            {
                return;
            }

            ProgressMsg("Importing data - Stage 1", 0);
            if (!DoStage1())
            {
                return;
            }

            CreateColumnIndexes();


            Cancelled = false;

            var connection = User.GetConnection();

            LogMsg("Importing data - Stage 2", 10);
            int rowCount    = 0;
            int lastPercent = 0;

            DateTime timeStarted = DateTime.Now;
            DateTime lastCheck   = timeStarted;

            RowSource.Reset();

            while (RowSource.MoveNext() && !Cancelled)
            {
                ImportCurrentRow(rowCount++, connection);

                var dblPercent = (double)((double)rowCount / (double)RowSource.RowCount) * 90;
                int percent    = ((int)dblPercent) + 10;

                var timeSinceLastUpdate = DateTime.Now - lastCheck;

                if (percent != lastPercent || timeSinceLastUpdate.Seconds > 5)
                {
                    var timeSinceStart = DateTime.Now - timeStarted;

                    var avgMillisPerRow = (double)(timeSinceStart.TotalMilliseconds == 0 ? 1 : timeSinceStart.TotalMilliseconds) / (double)(rowCount == 0 ? 1 : rowCount);
                    var rowsLeft        = RowSource.RowCount - rowCount;
                    var secondsLeft     = (int)((double)(rowsLeft * avgMillisPerRow) / 1000.0);

                    lastCheck = DateTime.Now;

                    TimeSpan ts = new TimeSpan(0, 0, secondsLeft);

                    var message = string.Format("Importing rows - Stage 2 ({0} of {1}). {2} remaining.", rowCount, RowSource.RowCount, ts.ToString());
                    ProgressMsg(message, percent);
                    lastPercent = percent;
                }
            }

            ProgressMsg("Importing rows - Stage 2 Complete", 100);

            LogMsg("{0} Rows successfully imported, {1} rows failed with errors", _successCount, _errorCount);

            LogMsg("Cleaning up staging database...");

            if (RowSource.Service.GetErrorCount() > 0)
            {
                if (ParentWindow.Question("Errors were encountered during the import. Rejected rows can be corrected and re-imported by re-running the import wizard and selecting the 'Import Error Database' option. Would you like to save the rejected rows so that they can be corrected and re-imported?", "Save rejected rows?", System.Windows.MessageBoxImage.Exclamation))
                {
                    // Clean out just the imported records, leaving just the error rows...
                    LogMsg("Purging successfully imported rows from staging database...");
                    RowSource.Service.PurgeImportedRecords();
                    LogMsg("Saving mapping information to staging database...");
                    RowSource.Service.SaveMappingInfo(Importer, Mappings);
                    LogMsg("Disconnecting from staging database...");
                    RowSource.Service.Disconnect();

                    var dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.Filter = "SQLite database files|*.sqlite|All files (*.*)|*.*";
                    dlg.Title  = "Save error database file";
                    if (dlg.ShowDialog().ValueOrFalse())
                    {
                        LogMsg("Copying staging database from {0} to {1}", RowSource.Service.FileName, dlg.FileName);
                        System.IO.File.Copy(RowSource.Service.FileName, dlg.FileName, true);
                    }
                }
            }

            connection.Close();
        }
Esempio n. 40
0
            /// <summary>
            /// The export transaction invoice.
            /// </summary>
            /// <param name="transOrder">
            /// The trans order.
            /// </param>
            public static void ExportTransactionInvoice(TransactionOrder transOrder)
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName = transOrder.DateTransaction.ToString("MMMMM dd yyyy") + " - " + transOrder.RefNo;
                // Default file name
                dlg.DefaultExt = ".xlsx";                         // Default file extension
                dlg.Filter     = "Excel Document (.xlsx)|*.xlsx"; // Filter files by extension
                Nullable <bool> result = dlg.ShowDialog();

                if (result == true)
                {
                    string   filename     = dlg.FileName;
                    FileInfo templateFile = new FileInfo(@"Invoice Template.xlsx");
                    FileInfo newFile      = new FileInfo(filename);
                    if (newFile.Exists)
                    {
                        try
                        {
                            newFile.Delete();
                            newFile = new FileInfo(filename);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("The file is currently being used, close the file or choose a different name.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                            return;
                        }
                    }
                    var config = StockbookWindows.OpenConfig();
                    using (ExcelPackage package = new ExcelPackage(newFile, templateFile))
                    {
                        var currency = string.Empty;
                        switch (config.Currency)
                        {
                        case "PHP - ₱":
                            currency = "₱#,###,##0.00";
                            break;

                        case "USD - $":
                            currency = "$#,###,##0.00";
                            break;

                        case "YEN - ¥":
                            currency = "¥#,###,##0.00";
                            break;
                        }

                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                        worksheet.Cells["A1"].Value = config.CompanyName;
                        worksheet.Cells["A2"].Value = "SALES INVOICE - REFERENCE NUMBER: " + transOrder.RefNo;
                        worksheet.Cells["A3"].Value = "DATE: " + transOrder.DateTransaction.ToString("MMMM dd, yyyy");
                        worksheet.Cells["A4"].Value = "SOLD TO: " + transOrder.Particular;
                        worksheet.Cells["A5"].Value = "ADDRESS: " + transOrder.ParticularAddress;
                        worksheet.Cells["A6"].Value = "SALESMAN: " + transOrder.SalesmanName;
                        worksheet.Cells["F4"].Value = "TERMS: " + transOrder.Terms;
                        worksheet.Cells["F5"].Value = "DISCOUNT: " + transOrder.DiscountPercentage + "%";
                        int     i            = 9;
                        decimal unitTotal    = 0;
                        decimal billedTotal  = 0;
                        string  tempCategory = string.Empty;
                        foreach (var trans in transOrder.Transactions)
                        {
                            decimal tempTotal = 0;
                            if (trans.CaseTransact != 0)
                            {
                                tempTotal = trans.Product.CaseValue * trans.CaseTransact;
                                worksheet.Cells["A" + i].Value = trans.Product.ProdCode;
                                worksheet.Cells["B" + i].Value = trans.Product.Name;
                                worksheet.Cells["C" + i].Value = "Case";
                                worksheet.Cells["D" + i].Value = trans.CaseTransact;
                                worksheet.Cells["E" + i].Value = trans.Product.CaseValue;
                                unitTotal += tempTotal;
                                if (transOrder.DiscountPercentage > 0)
                                {
                                    tempTotal = ((transOrder.DiscountPercentage / 100) + 1) * tempTotal;
                                }
                                billedTotal += tempTotal;
                                worksheet.Cells["F" + i].Value = tempTotal;
                                i++;
                            }
                            if (trans.PackTransact != 0)
                            {
                                tempTotal = trans.Product.PackValue * trans.PackTransact;
                                worksheet.Cells["A" + i].Value = trans.Product.ProdCode;
                                worksheet.Cells["B" + i].Value = trans.Product.Name;
                                worksheet.Cells["C" + i].Value = "Pack";
                                worksheet.Cells["D" + i].Value = trans.PackTransact;
                                worksheet.Cells["E" + i].Value = trans.Product.PackValue;
                                unitTotal += tempTotal;
                                if (transOrder.DiscountPercentage > 0)
                                {
                                    tempTotal = ((transOrder.DiscountPercentage / 100) + 1) * tempTotal;
                                }
                                billedTotal += tempTotal;
                                worksheet.Cells["F" + i].Value = tempTotal;
                                i++;
                            }
                            if (trans.PieceTransact != 0)
                            {
                                tempTotal = trans.Product.PieceValue * trans.PieceTransact;
                                worksheet.Cells["A" + i].Value = trans.Product.ProdCode;
                                worksheet.Cells["B" + i].Value = trans.Product.Name;
                                worksheet.Cells["C" + i].Value = "Piece";
                                worksheet.Cells["D" + i].Value = trans.PieceTransact;
                                worksheet.Cells["E" + i].Value = trans.Product.PieceValue;
                                unitTotal += tempTotal;
                                if (transOrder.DiscountPercentage > 0)
                                {
                                    tempTotal = ((transOrder.DiscountPercentage / 100) + 1) * tempTotal;
                                }
                                billedTotal += tempTotal;
                                worksheet.Cells["F" + i].Value = tempTotal;
                                i++;
                            }
                        }

                        worksheet.Cells["A" + 9 + ":A" + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells["b" + 9 + ":B" + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells["C" + 9 + ":C" + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells["D" + 9 + ":D" + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells["E" + 9 + ":E" + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        worksheet.Cells["F" + 9 + ":F" + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;

                        worksheet.Cells["A" + 9 + ":A" + i].Style.WrapText = true;
                        worksheet.Cells["b" + 9 + ":B" + i].Style.WrapText = true;
                        worksheet.Cells["C" + 9 + ":C" + i].Style.WrapText = true;
                        worksheet.Cells["D" + 9 + ":D" + i].Style.WrapText = true;
                        worksheet.Cells["E" + 9 + ":E" + i].Style.WrapText = true;
                        worksheet.Cells["F" + 9 + ":F" + i].Style.WrapText = true;

                        i++;
                        worksheet.Cells["C" + i + ":C" + (i + 2)].Style.Numberformat.Format = currency;
                        worksheet.Cells["F" + i + ":F" + (i + 2)].Style.Numberformat.Format = currency;

                        worksheet.Cells["C" + i + ":C" + (i + 2)].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                        worksheet.Cells["F" + i + ":F" + (i + 2)].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
                        worksheet.Cells["E" + i + ":E" + (i + 2)].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
                        worksheet.Cells["B" + i + ":B" + (i + 2)].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;

                        worksheet.Cells["B" + i].Value       = "Vatable Sales: ";
                        worksheet.Cells["C" + i].Value       = billedTotal * (decimal)0.88;
                        worksheet.Cells["B" + (i + 1)].Value = "12% VAT: ";
                        worksheet.Cells["C" + (i + 1)].Value = billedTotal * (decimal)0.12;
                        worksheet.Cells["B" + (i + 2)].Value = "Total w/o Discount: ";
                        worksheet.Cells["C" + (i + 2)].Value = billedTotal;

                        worksheet.Cells["E" + i].Value       = "Invoice Amt.: ";
                        worksheet.Cells["F" + i].Value       = unitTotal;
                        worksheet.Cells["E" + (i + 1)].Value = "Discount: " + transOrder.DiscountPercentage + "%";
                        worksheet.Cells["F" + (i + 1)].Value = unitTotal * (transOrder.DiscountPercentage / 100);
                        worksheet.Cells["E" + (i + 2)].Value = "Total w/ Discount: ";
                        worksheet.Cells["F" + (i + 2)].Value = billedTotal;

                        i += 6;
                        worksheet.Cells["A" + i].Value       = "PREPARED BY/DATE";
                        worksheet.Cells["A" + (i + 3)].Value = "PRINT NAME & SIGNATURE";
                        worksheet.Cells["D" + i].Value       = "DELIVERED BY/DATE";
                        worksheet.Cells["D" + (i + 3)].Value = "PRINT NAME & SIGNATURE";
                        i += 6;
                        worksheet.Cells["A" + i].Value       = "CHECKED BY/DATE";
                        worksheet.Cells["A" + (i + 3)].Value = "PRINT NAME & SIGNATURE";
                        worksheet.Cells["D" + i].Value       = "APPROVED BY";
                        worksheet.Cells["D" + (i + 3)].Value = "PRINT NAME & SIGNATURE";
                        worksheet.View.PageLayoutView        = false;

                        package.Save();
                    }
                }
            }
Esempio n. 41
0
        public Task OutputResultsAsync(IQueryRunner runner)
        {
            var dlg = new Microsoft.Win32.SaveFileDialog
            {
                DefaultExt = ".txt",
                Filter     = "Tab separated text file|*.txt|Comma separated text file - UTF8|*.csv|Comma separated text file - Unicode|*.csv|Custom Export Format (Configure in Options)|*.csv"
            };

            string fileName   = "";
            long   durationMs = 0;
            // Show save file dialog box
            var result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                fileName = dlg.FileName;
                return(Task.Run(() =>
                {
                    try
                    {
                        runner.OutputMessage("Query Started");

                        var sw = Stopwatch.StartNew();

                        string sep = "\t";
                        bool shouldQuoteStrings = true; //default to quoting all string fields
                        string decimalSep = System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.CurrencyDecimalSeparator;
                        string isoDateFormat = string.Format(Constants.IsoDateMask, decimalSep);
                        var enc = Encoding.UTF8;

                        switch (dlg.FilterIndex)
                        {
                        case 1:     // tab separated
                            sep = "\t";
                            break;

                        case 2:     // utf-8 csv
                            sep = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
                            break;

                        case 3:     //unicode csv
                            enc = Encoding.Unicode;
                            sep = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
                            break;

                        case 4:
                            // TODO - custom export format
                            sep = runner.Options.GetCustomCsvDelimiter();
                            shouldQuoteStrings = runner.Options.CustomCsvQuoteStringFields;
                            break;
                        }

                        var daxQuery = runner.QueryText;
                        var reader = runner.ExecuteDataReaderQuery(daxQuery);

                        try
                        {
                            if (reader != null)
                            {
                                int iFileCnt = 1;
                                var outputFilename = fileName;

                                runner.OutputMessage("Command Complete, writing output file");

                                bool moreResults = true;

                                while (moreResults)
                                {
                                    int iMaxCol = reader.FieldCount - 1;
                                    int iRowCnt = 0;
                                    if (iFileCnt > 1)
                                    {
                                        outputFilename = AddFileCntSuffix(fileName, iFileCnt);
                                    }

                                    using (var textWriter = new System.IO.StreamWriter(outputFilename, false, enc))
                                    {
                                        using (var csvWriter = new CsvHelper.CsvWriter(textWriter))
                                        {
                                            // CSV Writer config

                                            csvWriter.Configuration.Delimiter = sep;

                                            // Datetime as ISOFormat

                                            csvWriter.Configuration.TypeConverterOptionsCache.AddOptions(
                                                typeof(DateTime),
                                                new CsvHelper.TypeConversion.TypeConverterOptions()
                                            {
                                                Formats = new string[] { isoDateFormat }
                                            });

                                            // write out clean column names

                                            foreach (var colName in reader.CleanColumnNames())
                                            {
                                                csvWriter.WriteField(colName);
                                            }

                                            csvWriter.NextRecord();

                                            while (reader.Read())
                                            {
                                                iRowCnt++;

                                                for (int iCol = 0; iCol < reader.FieldCount; iCol++)
                                                {
                                                    var fieldValue = reader[iCol];

                                                    // quote all string fields
                                                    if (reader.GetFieldType(iCol) == typeof(string))
                                                    {
                                                        if (reader.IsDBNull(iCol))
                                                        {
                                                            csvWriter.WriteField("", shouldQuoteStrings);
                                                        }
                                                        else
                                                        {
                                                            csvWriter.WriteField(fieldValue.ToString(), shouldQuoteStrings);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        csvWriter.WriteField(fieldValue);
                                                    }
                                                }

                                                csvWriter.NextRecord();

                                                if (iRowCnt % 1000 == 0)
                                                {
                                                    runner.NewStatusBarMessage(string.Format("Written {0:n0} rows to the file output", iRowCnt));
                                                }
                                            }
                                        }
                                    }

                                    runner.OutputMessage(
                                        string.Format("Query {2} Completed ({0:N0} row{1} returned)"
                                                      , iRowCnt
                                                      , iRowCnt == 1 ? "" : "s", iFileCnt)
                                        );

                                    runner.RowCount = iRowCnt;

                                    moreResults = reader.NextResult();

                                    iFileCnt++;
                                }

                                sw.Stop();
                                durationMs = sw.ElapsedMilliseconds;

                                runner.SetResultsMessage("Query results written to file", OutputTargets.File);
                                runner.ActivateOutput();
                            }
                            else
                            {
                                runner.OutputError("Query Batch Completed with errors", durationMs);
                            }
                        }
                        finally
                        {
                            if (reader != null)
                            {
                                reader.Dispose();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        runner.ActivateOutput();
                        runner.OutputError(ex.Message);
#if DEBUG
                        runner.OutputError(ex.StackTrace);
#endif
                    }
                    finally
                    {
                        runner.OutputMessage("Query Batch Completed", durationMs);
                        runner.QueryCompleted();
                    }
                }));
            }
            // else dialog was cancelled so return an empty task.
            return(Task.Run(() => { }));
        }
Esempio n. 42
0
        private void Export(object sender, RoutedEventArgs e)
        {
            var part = _editor.Part;

            if (part == null)
            {
                return;
            }

            var onRawContent = part.Type == "Raw Content";
            var contentBlock = onRawContent ? _editor.GetRootBlock() : _lastSelectedBlock;

            if (contentBlock == null)
            {
                return;
            }

            var mimeTypes = _editor.GetSupportedExportMimeTypes(contentBlock);

            if (mimeTypes == null)
            {
                return;
            }

            if (mimeTypes.Count() == 0)
            {
                return;
            }

            string filterList = "";

            for (int i = 0; i < mimeTypes.Count(); ++i)
            {
                // format filter as "name|extension1;extension2;...;extensionX"
                var    extensions = MimeTypeF.GetFileExtensions(mimeTypes[i]).Split(',');
                string filter     = MimeTypeF.GetName(mimeTypes[i]) + "|";

                for (int j = 0; j < extensions.Count(); ++j)
                {
                    if (j > 0)
                    {
                        filter += ";";
                    }

                    filter += "*" + extensions[j];
                }

                if (i > 0)
                {
                    filterList += "|";
                }

                filterList += filter;
            }

            // Show save dialog
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

                dlg.FileName   = "Interactive Ink Document"; // Default file name
                dlg.DefaultExt = System.String.Empty;        // Default file extension
                dlg.Filter     = filterList;                 // Filter files by extension

                bool?result = dlg.ShowDialog();

                if ((bool)result)
                {
                    var filePath    = dlg.FileName;
                    var filterIndex = dlg.FilterIndex - 1;
                    var extensions  = MimeTypeF.GetFileExtensions(mimeTypes[filterIndex]).Split(',');

                    if (extensions.Count() > 0)
                    {
                        int ext;

                        for (ext = 0; ext < extensions.Count(); ++ext)
                        {
                            if (filePath.EndsWith(extensions[ext], StringComparison.OrdinalIgnoreCase))
                            {
                                break;
                            }
                        }

                        if (ext >= extensions.Count())
                        {
                            filePath += extensions[0];
                        }

                        try
                        {
                            var drawer = new ImageDrawer();

                            drawer.ImageLoader = UcEditor.ImageLoader;

                            _editor.WaitForIdle();
                            _editor.Export_(contentBlock, filePath, drawer);

                            System.Diagnostics.Process.Start(filePath);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                }
            }
        }
Esempio n. 43
0
        protected override void PerformAction(object parameter)
        {
            var photo = parameter as FacebookPhoto;

            if (photo == null)
            {
                return;
            }

            string defaultFileName = "Facebook Photo";

            if (photo.Album != null)
            {
                defaultFileName = photo.Album.Title + " (" + (photo.Album.Photos.IndexOf(photo) + 1) + ")";
            }

            string filePath = null;

            if (Utility.IsOSVistaOrNewer)
            {
                IFileSaveDialog pFileSaveDialog = null;
                try
                {
                    pFileSaveDialog = CLSID.CoCreateInstance <IFileSaveDialog>(CLSID.FileSaveDialog);
                    pFileSaveDialog.SetOptions(pFileSaveDialog.GetOptions() | FOS.FORCEFILESYSTEM | FOS.OVERWRITEPROMPT);
                    pFileSaveDialog.SetTitle("Select where to save the photo");
                    pFileSaveDialog.SetOkButtonLabel("Save Photo");
                    var filterspec = new COMDLG_FILTERSPEC {
                        pszName = "Images", pszSpec = "*.jpg;*.png;*.bmp;*.gif"
                    };
                    pFileSaveDialog.SetFileTypes(1, ref filterspec);
                    pFileSaveDialog.SetFileName(defaultFileName);
                    Guid clientId = _SavePhotoId;
                    pFileSaveDialog.SetClientGuid(ref clientId);

                    IShellItem pItem = null;
                    try
                    {
                        pItem = ShellUtil.GetShellItemForPath(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
                        pFileSaveDialog.SetDefaultFolder(pItem);
                    }
                    finally
                    {
                        Utility.SafeRelease(ref pItem);
                    }

                    HRESULT hr = pFileSaveDialog.Show(new WindowInteropHelper(Application.Current.MainWindow).Handle);
                    if (hr.Failed)
                    {
                        Assert.AreEqual((HRESULT)Win32Error.ERROR_CANCELLED, hr);
                        return;
                    }

                    pItem = null;
                    try
                    {
                        pItem    = pFileSaveDialog.GetResult();
                        filePath = ShellUtil.GetPathFromShellItem(pItem);
                    }
                    finally
                    {
                        Utility.SafeRelease(ref pItem);
                    }
                }
                finally
                {
                    Utility.SafeRelease(ref pFileSaveDialog);
                }
            }
            else
            {
                var saveFileDialog = new Microsoft.Win32.SaveFileDialog
                {
                    Filter           = "Image Files|*.jpg;*.png;*.bmp;*.gif",
                    FileName         = defaultFileName,
                    InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures),
                };

                if (saveFileDialog.ShowDialog(Application.Current.MainWindow) != true)
                {
                    return;
                }

                filePath = saveFileDialog.FileName;
            }

            FacebookImageSaveOptions fiso = FacebookImageSaveOptions.FindBetterName;

            // We told the file dialog to prompt about overwriting, so if the user specified a location
            // with a file extension and the file already exists, prepare to overwrite.
            // This isn't quite right because the file extension may be different, so we may overwrite a jpg
            // when it was asked to be a gif, but it's not a likely scenario.
            if (System.IO.File.Exists(filePath))
            {
                fiso = FacebookImageSaveOptions.Overwrite;
            }

            photo.Image.SaveToFile(FacebookImageDimensions.Big, filePath, true, fiso, _OnPhotoSaveProgressCallback, null);
        }
Esempio n. 44
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender == ButtonSelectCertFile)
            {
                // choose filename
                var dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.DefaultExt = "*.*";
                dlg.Filter     = "PFX file (*.pfx)|*.pfx|Cert file (*.cer)|*.cer|All files (*.*)|*.*";

                // save
                if (true == dlg.ShowDialog())
                {
                    ComboBoxCertFile.Text = dlg.FileName;
                }
            }

            if (sender == ButtonSavePreset)
            {
                // choose filename
                var dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName   = "new.json";
                dlg.DefaultExt = "*.json";
                dlg.Filter     = "Preset JSON file (*.json)|*.json|All files (*.*)|*.*";

                // save
                if (true == dlg.ShowDialog())
                {
                    try
                    {
                        var pr = this.ThisToPreset();
                        pr.SaveToFile(dlg.FileName);
                    }
                    catch (Exception ex)
                    {
                        AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex);
                    }
                }
            }

            if (sender == ButtonLoadPreset)
            {
                // choose filename
                var dlg = new Microsoft.Win32.OpenFileDialog();
                dlg.FileName   = "new.json";
                dlg.DefaultExt = "*.json";
                dlg.Filter     = "Preset JSON file (*.json)|*.json|All files (*.*)|*.*";

                // save
                if (true == dlg.ShowDialog())
                {
                    try
                    {
                        var pr = SecureConnectPreset.LoadFromFile(dlg.FileName);
                        this.ActivatePreset(pr);
                    }
                    catch (Exception ex)
                    {
                        AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex);
                    }
                }
            }

            if (sender == ButtonStart)
            {
                this.Result = ThisToPreset();
                ControlClosed?.Invoke();
            }
        }
Esempio n. 45
0
        /// <summary>
        /// Export the resulting data.
        /// </summary>
        public void ExportResult()
        {
            if (!IsExportDataResultEnabled)
            {
                return;
            }

            if (DataResult != null)
            {
                // ask user if they want to export all data if there is more than one page
                bool allData = false;
                if (DataResult.IsMore)
                {
                    string answer = App.MessageUser(
                        "Would you like to export all remaining data from your query or only the data that is currently displayed?",
                        "Export Data",
                        System.Windows.MessageBoxImage.Question,
                        new string[] { "All data", "Currently displayed data", "Cancel" });

                    if (answer == "Cancel")
                    {
                        return;
                    }

                    allData = (answer == "All data");
                }

                // get file name for export
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.Filter          = "CSV Files (*.csv)|*.csv";
                dlg.Title           = "Export data";
                dlg.DefaultExt      = "csv";
                dlg.OverwritePrompt = true;

                bool?dlgResult = dlg.ShowDialog();
                if (dlgResult.HasValue && dlgResult.Value)
                {
                    using (StreamWriter writer = new StreamWriter(File.Open(dlg.FileName, FileMode.OpenOrCreate)))
                    {
                        // write column names
                        for (int i = 0; i < DataResult.Data.Columns.Count; i++)
                        {
                            writer.Write(NormCSVText(DataResult.Data.Columns[i].ColumnName));
                            if (i != DataResult.Data.Columns.Count - 1)
                            {
                                writer.Write(",");
                            }
                        }
                        writer.WriteLine();

                        DataSelectResult result = DataResult;
                        while (result != null)
                        {
                            // write rows
                            foreach (DataRow row in result.Data.Rows)
                            {
                                for (int i = 0; i < DataResult.Data.Columns.Count; i++)
                                {
                                    writer.Write(NormCSVText(row[i] as string));
                                    if (i != DataResult.Data.Columns.Count - 1)
                                    {
                                        writer.Write(",");
                                    }
                                }
                                writer.WriteLine();
                            }

                            // check for more data
                            if (result.IsMore && allData)
                            {
                                result = Project.Client.Data.Select(result);
                            }
                            else
                            {
                                result = null;
                            }
                        }

                        // close stream
                        writer.Flush();
                        writer.Close();
                    }
                }
            }
        }
Esempio n. 46
0
        private void generatePDF()
        {
            do
            {
                transaction_idValue = "0" + transaction_idValue;
            }while (transaction_idValue.Length < 8);

            PdfDocument document = new PdfDocument();

            document.Info.Title = "STI Front Line PDF";
            PdfPage   page = document.AddPage();
            XGraphics gfx  = XGraphics.FromPdfPage(page);
            XFont     font = new XFont("Verdana", 20, XFontStyle.Bold);

            page.Width  = 612;
            page.Height = 792;

            const string    times_new_roman = "Times New Roman";
            XPdfFontOptions options         = new XPdfFontOptions(PdfFontEncoding.WinAnsi, PdfFontEmbedding.Default);
            XFont           fontHeader      = new XFont(times_new_roman, 20, XFontStyle.Regular, options);

            gfx.DrawString("Student Information", fontHeader, XBrushes.DarkSlateGray, 30, 50);

            XPen pen = new XPen(XColors.Black, 0.5);

            gfx.DrawLine(pen, 30, 60, 580, 60);

            const string arial       = "Arial";
            XFont        fontRegular = new XFont(arial, 12, XFontStyle.Regular, options);

            gfx.DrawString("Transaction ID ", fontRegular, XBrushes.Black, 119, 110);
            gfx.DrawString("School Level ", fontRegular, XBrushes.Black, 128, 125);
            gfx.DrawString("Student ID ", fontRegular, XBrushes.Black, 140, 140);
            gfx.DrawString("Course ", fontRegular, XBrushes.Black, 158, 155);
            gfx.DrawString("Year/Grade ", fontRegular, XBrushes.Black, 135, 170);
            gfx.DrawString("LRN/ESC ", fontRegular, XBrushes.Black, 145, 185);
            gfx.DrawString("Student Name ", fontRegular, XBrushes.Black, 120, 200);
            gfx.DrawString("Birth Date ", fontRegular, XBrushes.Black, 143, 215);
            gfx.DrawString("Birth Place ", fontRegular, XBrushes.Black, 139, 230);
            gfx.DrawString("Citizenship ", fontRegular, XBrushes.Black, 138, 245);
            gfx.DrawString("Civil Status ", fontRegular, XBrushes.Black, 137, 260);
            gfx.DrawString("Gender ", fontRegular, XBrushes.Black, 157, 275);
            gfx.DrawString("Current Address ", fontRegular, XBrushes.Black, 109, 290);
            gfx.DrawString("Permanent Address ", fontRegular, XBrushes.Black, 91, 305);
            gfx.DrawString("Landline ", fontRegular, XBrushes.Black, 151, 320);
            gfx.DrawString("Mobile ", fontRegular, XBrushes.Black, 161, 335);
            gfx.DrawString("Email ", fontRegular, XBrushes.Black, 167, 350);
            gfx.DrawString("Previous School Level ", fontRegular, XBrushes.Black, 78, 365);
            gfx.DrawString("Graduation ", fontRegular, XBrushes.Black, 138, 380);
            gfx.DrawString("Last School Attended ", fontRegular, XBrushes.Black, 82, 395);
            gfx.DrawString("Previous Level ", fontRegular, XBrushes.Black, 118, 410);
            gfx.DrawString("Previous School Year Attended ", fontRegular, XBrushes.Black, 30, 425);
            gfx.DrawString("Previous Year/Grade ", fontRegular, XBrushes.Black, 85, 440);
            gfx.DrawString("Term ", fontRegular, XBrushes.Black, 168, 455);
            gfx.DrawString("Father's Name ", fontRegular, XBrushes.Black, 119, 470);
            gfx.DrawString("Father's Contact No. ", fontRegular, XBrushes.Black, 87, 485);
            gfx.DrawString("Father's Occupation ", fontRegular, XBrushes.Black, 89, 500);
            gfx.DrawString("Father's Email ", fontRegular, XBrushes.Black, 120, 515);
            gfx.DrawString("Mother's Name ", fontRegular, XBrushes.Black, 116, 530);
            gfx.DrawString("Mother's Contact No. ", fontRegular, XBrushes.Black, 84, 545);
            gfx.DrawString("Mother's Occupation ", fontRegular, XBrushes.Black, 86, 560);
            gfx.DrawString("Mother's Email ", fontRegular, XBrushes.Black, 117, 575);
            gfx.DrawString("Guardian's Name ", fontRegular, XBrushes.Black, 103, 590);
            gfx.DrawString("Guardian's Contact No. ", fontRegular, XBrushes.Black, 71, 605);
            gfx.DrawString("Guardian's Occupation ", fontRegular, XBrushes.Black, 74, 620);
            gfx.DrawString("Guardian's Email ", fontRegular, XBrushes.Black, 106, 635);
            gfx.DrawString("Time & Data Enrolled ", fontRegular, XBrushes.Black, 83, 650);
            gfx.DrawString("School Year " + ": ", fontRegular, XBrushes.Black, 131, 665);

            gfx.DrawString(": " + transaction_idValue, fontRegular, XBrushes.Black, 200, 110);
            gfx.DrawString(": " + school_levelValue, fontRegular, XBrushes.Black, 200, 125);
            gfx.DrawString(": " + student_idValue, fontRegular, XBrushes.Black, 200, 140);
            gfx.DrawString(": " + courseValue, fontRegular, XBrushes.Black, 200, 155);
            gfx.DrawString(": " + year_or_gradeValue, fontRegular, XBrushes.Black, 200, 170);
            gfx.DrawString(": " + lrn_or_escValue, fontRegular, XBrushes.Black, 200, 185);
            gfx.DrawString(": " + student_nameValue, fontRegular, XBrushes.Black, 200, 200);
            gfx.DrawString(": " + birth_dateValue, fontRegular, XBrushes.Black, 200, 215);
            gfx.DrawString(": " + birth_placeValue, fontRegular, XBrushes.Black, 200, 230);
            gfx.DrawString(": " + citizenshipValue, fontRegular, XBrushes.Black, 200, 245);
            gfx.DrawString(": " + civil_statusValue, fontRegular, XBrushes.Black, 200, 260);
            gfx.DrawString(": " + genderValue, fontRegular, XBrushes.Black, 200, 275);
            gfx.DrawString(": " + current_addressValue, fontRegular, XBrushes.Black, 200, 290);
            gfx.DrawString(": " + permanent_addressValue, fontRegular, XBrushes.Black, 200, 305);
            gfx.DrawString(": " + landlineValue, fontRegular, XBrushes.Black, 200, 320);
            gfx.DrawString(": " + mobileValue, fontRegular, XBrushes.Black, 200, 335);
            gfx.DrawString(": " + emailValue, fontRegular, XBrushes.Black, 200, 350);
            gfx.DrawString(": " + previous_school_levelValue, fontRegular, XBrushes.Black, 200, 365);
            gfx.DrawString(": " + graduationValue, fontRegular, XBrushes.Black, 200, 380);
            gfx.DrawString(": " + last_school_attendedValue, fontRegular, XBrushes.Black, 200, 395);
            gfx.DrawString(": " + previous_levelValue, fontRegular, XBrushes.Black, 200, 410);
            gfx.DrawString(": " + previous_school_year_attendedValue, fontRegular, XBrushes.Black, 200, 425);
            gfx.DrawString(": " + previous_year_or_gradeValue, fontRegular, XBrushes.Black, 200, 440);
            gfx.DrawString(": " + termValue, fontRegular, XBrushes.Black, 200, 455);
            gfx.DrawString(": " + father_nameValue, fontRegular, XBrushes.Black, 200, 470);
            gfx.DrawString(": " + father_contact_noValue, fontRegular, XBrushes.Black, 200, 485);
            gfx.DrawString(": " + father_occupationValue, fontRegular, XBrushes.Black, 200, 500);
            gfx.DrawString(": " + father_emailValue, fontRegular, XBrushes.Black, 200, 515);
            gfx.DrawString(": " + mother_nameValue, fontRegular, XBrushes.Black, 200, 530);
            gfx.DrawString(": " + mother_contact_noValue, fontRegular, XBrushes.Black, 200, 545);
            gfx.DrawString(": " + mother_occupationValue, fontRegular, XBrushes.Black, 200, 560);
            gfx.DrawString(": " + mother_emailValue, fontRegular, XBrushes.Black, 200, 575);
            gfx.DrawString(": " + guardian_nameValue, fontRegular, XBrushes.Black, 200, 590);
            gfx.DrawString(": " + guardian_contact_noValue, fontRegular, XBrushes.Black, 200, 605);
            gfx.DrawString(": " + guardian_occupationValue, fontRegular, XBrushes.Black, 200, 620);
            gfx.DrawString(": " + guardian_emailValue, fontRegular, XBrushes.Black, 200, 635);
            gfx.DrawString(": " + time_and_date_enrolledValue, fontRegular, XBrushes.Black, 200, 650);
            gfx.DrawString(": " + school_yearValue, fontRegular, XBrushes.Black, 200, 665);

            gfx.DrawLine(pen, 30, 720, 580, 720);

            DateTime currentTime = DateTime.Now;

            String Time_And_Date_Generated = currentTime.ToString("MM-dd-yyyy hh:mm tt");

            gfx.DrawString("" + Time_And_Date_Generated, fontRegular, XBrushes.Black, 30, 745);

            string filename = string.Empty;

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName   = student_nameValue;
            dlg.DefaultExt = ".pdf";
            dlg.Filter     = "PDF documents (.pdf)|*.pdf";

            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                try
                {
                    filename = dlg.FileName;
                    document.Save(filename);
                    Process.Start(filename);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("File is open with other programs.");
                }
            }
        }
Esempio n. 47
0
        private void print_but_Click(object sender, RoutedEventArgs e)
        {
            var msg = new CustomMaterialMessageBox
            {
                TxtMessage = { Text = "are you sure ? ", Foreground = Brushes.Black },
                TxtTitle   = { Text = "PURCHASE ORDER", Foreground = Brushes.Black },
                BtnOk      = { Content = "Yes" },
                BtnCancel  = { Content = "No" },
                // MainContentControl = { Background = Brushes.MediumVioletRed },
                TitleBackgroundPanel = { Background = Brushes.Yellow },

                BorderBrush = Brushes.Yellow
            };

            msg.Show();
            var results = msg.Result;

            if (results == MessageBoxResult.OK)
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName   = "purchase order";            // Default file name
                dlg.DefaultExt = ".pdf";                      // Default file extension
                dlg.Filter     = "PDF document (.pdf)|*.pdf"; // Filter files by extension
                // Show save file dialog box
                Nullable <bool> result = dlg.ShowDialog();

                // Process save file dialog box results
                if (result == true)
                {
                    string    filename = dlg.FileName;
                    Document  document = new Document(PageSize.A4, 10, 10, 10, 10);
                    PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
                    File.SetAttributes(filename, FileAttributes.Normal);
                    document.Open();
                    string h1 = "\n\n\n\n\n\n\n\n\n\nPURCHASE ORDER\n\n\n";
                    iTextSharp.text.Paragraph p1 = new iTextSharp.text.Paragraph();
                    p1.Alignment = Element.ALIGN_CENTER;
                    p1.Font      = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 20f, BaseColor.BLACK);
                    p1.Add(h1);
                    document.Add(p1);
                    iTextSharp.text.Paragraph p3 = new iTextSharp.text.Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)));
                    document.Add(p3);
                    iTextSharp.text.Paragraph p4 = new iTextSharp.text.Paragraph("\n\n\n");
                    document.Add(p4);
                    PdfPTable table1 = new PdfPTable(2);
                    table1.AddCell("ITEM");
                    table1.AddCell("QUANTITY");
                    try
                    {
                        DataTable ds = new DataTable(typeof(Item).Name);

                        //Get all the properties
                        PropertyInfo[] Props = typeof(Item).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                        foreach (PropertyInfo prop in Props)
                        {
                            //Defining type of data column gives proper data table
                            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable <>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
                            //Setting column names as Property names
                            ds.Columns.Add(prop.Name, type);
                        }
                        foreach (Item item in inventory_table.ItemsSource)
                        {
                            var values = new object[Props.Length];
                            for (int i = 0; i < Props.Length; i++)
                            {
                                //inserting property values to datatable rows
                                values[i] = Props[i].GetValue(item, null);
                            }
                            ds.Rows.Add(values);
                        }
                        for (int i = 0; i < ds.Rows.Count; i++)
                        {
                            object o = ds.Rows[i][5];
                            string a = o.ToString();
                            if (o != DBNull.Value)
                            {
                                if (ds.Rows[i][6].ToString() != "0")
                                {
                                    double quantity = Convert.ToDouble(ds.Rows[i][4]) + Convert.ToDouble(ds.Rows[i][6]);
                                    if (quantity >= 0)
                                    {
                                        bool success = dbhandler.purchase_update(ds.Rows[i][1].ToString(), quantity.ToString());
                                        if (success)
                                        {
                                            //log += "ITEM:" + ds.Rows[i][0].ToString() + " PREVIOUS ORDER:" + ds.Rows[i][3].ToString() + " RECENT ORDER:" + ds.Rows[i][5].ToString() + " STATUS: ordered" + " ENTRY :" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
                                            table1.AddCell(ds.Rows[i][1].ToString());
                                            table1.AddCell(ds.Rows[i][6].ToString());
                                        }

                                        else
                                        {
                                            MessageBox.Show("FAIL");
                                        }
                                    }

                                    else
                                    {
                                        MessageBox.Show(ds.Rows[i][0].ToString() + ": VALUE CAN'T BE LESS THAN ZERO", "WARNING");
                                    }
                                }
                            }
                        }



                        document.Add(table1);
                        document.Close();
                    }
                    catch (Exception m)
                    {
                        MessageBox.Show(m.Message);
                    }

                    MaterialMessageBox.Show(@"Purchase order generated in " + filename);
                    // dbhandler.log_update(dbhandler.Storelog, log);
                    Items.Clear();
                    table_update();
                }
            }
        }
Esempio n. 48
0
        public void Exportar(DataGrid dg)
        {
            try
            {
                List <Object> itens = new List <object>((IEnumerable <object>)dg.ItemsSource);

                if (itens != null && itens.Count > 0)
                {
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.FileName   = "dadosLista";
                    dlg.DefaultExt = ".csv";
                    dlg.Filter     = "Arquivo CSV (.csv)|*.csv";

                    Nullable <bool> result = dlg.ShowDialog();

                    if (result == true)
                    {
                        FileStream fs = new FileStream(dlg.FileName, FileMode.Create, FileAccess.ReadWrite);

                        StringBuilder sb = new StringBuilder();

                        foreach (DataGridColumn coluna in dg.Columns)
                        {
                            sb.Append("\"");
                            sb.Append(coluna.Header.ToString());
                            sb.Append("\"");
                            sb.Append(",");
                        }
                        sb.AppendLine();

                        foreach (Object item in itens)
                        {
                            foreach (DataGridColumn coluna in dg.Columns)
                            {
                                Binding  binding       = (Binding)((DataGridBoundColumn)coluna).Binding;
                                string   path          = binding.Path.Path;
                                string[] hierarquiaObj = path.Split('.');

                                Object itemAux = item;
                                for (int i = 0; i < hierarquiaObj.Length - 1; i++)
                                {
                                    itemAux = itemAux.GetType().GetProperty(hierarquiaObj[i]).GetValue(itemAux, null);
                                }

                                string prop = hierarquiaObj[hierarquiaObj.Length - 1];

                                string conteudo = itemAux.GetType().GetProperty(prop).
                                                  GetValue(itemAux, null).ToString();

                                sb.Append("\"");
                                sb.Append(conteudo);
                                sb.Append("\"");
                                sb.Append(",");
                            }
                            sb.AppendLine();
                        }
                        fs.Write(System.Text.Encoding.Default.GetBytes(sb.ToString()), 0,
                                 sb.ToString().Length);
                        fs.Flush();
                        fs.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            dateborder.Visibility         = Visibility.Visible;
            timenow.Content               = DateTime.Now.ToString("HH:mm:ss");
            invoiceid.BorderThickness     = new Thickness(0, 0, 0, 0);
            nameField.BorderThickness     = new Thickness(0, 0, 0, 0);
            product1.BorderThickness      = new Thickness(0, 0, 0, 0);
            product2.BorderThickness      = new Thickness(0, 0, 0, 0);
            product3.BorderThickness      = new Thickness(0, 0, 0, 0);
            product4.BorderThickness      = new Thickness(0, 0, 0, 0);
            product5.BorderThickness      = new Thickness(0, 0, 0, 0);
            product6.BorderThickness      = new Thickness(0, 0, 0, 0);
            product7.BorderThickness      = new Thickness(0, 0, 0, 0);
            product8.BorderThickness      = new Thickness(0, 0, 0, 0);
            product9.BorderThickness      = new Thickness(0, 0, 0, 0);
            product10.BorderThickness     = new Thickness(0, 0, 0, 0);
            product11.BorderThickness     = new Thickness(0, 0, 0, 0);
            product12.BorderThickness     = new Thickness(0, 0, 0, 0);
            product13.BorderThickness     = new Thickness(0, 0, 0, 0);
            product14.BorderThickness     = new Thickness(0, 0, 0, 0);
            product15.BorderThickness     = new Thickness(0, 0, 0, 0);
            product16.BorderThickness     = new Thickness(0, 0, 0, 0);
            product17.BorderThickness     = new Thickness(0, 0, 0, 0);
            product18.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM1Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM2Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM3Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM4Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM5Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM6Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM7Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM8Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM9Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            MM10Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM11Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM12Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM13Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM14Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM15Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM16Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM17Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            MM18Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu1Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu2Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu3Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu4Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu5Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu6Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu7Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu8Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu9Field.BorderThickness      = new Thickness(0, 0, 0, 0);
            Qu10Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu11Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu12Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu13Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu14Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu15Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu16Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu17Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            Qu18Field.BorderThickness     = new Thickness(0, 0, 0, 0);
            bank1Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            bank2Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            bank3Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            bank4Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            banknum1Field.BorderThickness = new Thickness(0, 0, 0, 0);
            banknum2Field.BorderThickness = new Thickness(0, 0, 0, 0);
            banknum3Field.BorderThickness = new Thickness(0, 0, 0, 0);
            banknum4Field.BorderThickness = new Thickness(0, 0, 0, 0);
            iban1Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            iban2Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            iban3Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            iban4Field.BorderThickness    = new Thickness(0, 0, 0, 0);
            sumField.BorderThickness      = new Thickness(0, 0, 0, 0);
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Filter      = "PDF Files|*.pdf";
            dlg.FilterIndex = 0;
            dlg.FileName    = "ΔΑ-" + invoiceid.Text;
            Nullable <bool> result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                string temp = Path.GetTempPath();
                // string savePath = Path.GetDirectoryName(dlg.FileName);
                WriteToPDF(print, temp + @"\temp.png", dlg.FileName);
                SaveDeliveryNoteToDatabase();
            }
        }
Esempio n. 50
0
 private void Button_Click_5(object sender, RoutedEventArgs e)
 {
     Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
     sfd.ShowDialog();
 }
Esempio n. 51
0
        public void PDFExport(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName   = "Document";
            dlg.DefaultExt = ".pdf";
            dlg.Filter     = "PDF files (*.pdf)|*.pdf";
            Nullable <bool> result = dlg.ShowDialog();

            if (result == true)
            {
                string data     = "";
                int    lmsCount = 0;
                double tmpMax   = 0;
                double tmpMin   = 0;
                double tmpAvg   = 0;
                double humMax   = 0;
                double humMin   = 0;
                double humAvg   = 0;
                int    ct       = 0;
                bool   first    = true;

                Spire.Pdf.PdfDocument doc  = new Spire.Pdf.PdfDocument();
                PdfPageBase           page = doc.Pages.Add();
                page.Canvas.DrawString("DATA REPORT",
                                       new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 20f),
                                       new PdfSolidBrush(new PdfRGBColor()),
                                       300, 10);
                if (debut.SelectedDate.HasValue && fin.SelectedDate.HasValue && run)
                {
                    List <MStatement> lms = man.GetAllStatementByDate(mainWindow.captor, debut.SelectedDate.Value, fin.SelectedDate.Value.AddDays(1));
                    foreach (MStatement s in lms)
                    {
                        data += string.Format("{0}.\t{1}\t{2}\t{3}\r\n", s.StatementId, s.DateTime, s.Temperature, s.Humidity);
                        if (first)
                        {
                            tmpMin = s.Temperature;
                            tmpMax = s.Temperature;
                            tmpAvg = s.Temperature;
                            humMin = s.Humidity;
                            humMax = s.Humidity;
                            humAvg = s.Humidity;
                            first  = false;
                        }
                        else
                        {
                            if (tmpMin > s.Temperature)
                            {
                                tmpMin = s.Temperature;
                            }
                            if (tmpMax < s.Temperature)
                            {
                                tmpMax = s.Temperature;
                            }
                            tmpAvg += s.Temperature;
                            if (humMin > s.Humidity)
                            {
                                humMin = s.Humidity;
                            }
                            if (humMax < s.Humidity)
                            {
                                humMax = s.Humidity;
                            }
                            humAvg += s.Humidity;
                        }
                        ct++;
                    }
                    tmpAvg   = tmpAvg / ct;
                    humAvg   = humAvg / ct;
                    lmsCount = lms.Count;
                }
                else
                {
                    List <MStatement> lms = man.GetAllStatement(mainWindow.captor);
                    foreach (MStatement s in lms)
                    {
                        data += string.Format("{0}.\t{1}\t{2}\t{3}\r\n", s.StatementId, s.DateTime, s.Temperature, s.Humidity);
                        if (first)
                        {
                            tmpMin = s.Temperature;
                            tmpMax = s.Temperature;
                            tmpAvg = s.Temperature;
                            humMin = s.Humidity;
                            humMax = s.Humidity;
                            humAvg = s.Humidity;
                            first  = false;
                        }
                        else
                        {
                            if (tmpMin > s.Temperature)
                            {
                                tmpMin = s.Temperature;
                            }
                            if (tmpMax < s.Temperature)
                            {
                                tmpMax = s.Temperature;
                            }
                            tmpAvg += s.Temperature;
                            if (humMin > s.Humidity)
                            {
                                humMin = s.Humidity;
                            }
                            if (humMax < s.Humidity)
                            {
                                humMax = s.Humidity;
                            }
                            humAvg += s.Humidity;
                        }
                        ct++;
                    }
                    tmpAvg   = Math.Round(tmpAvg / ct, 1);
                    humAvg   = Math.Round(humAvg / ct, 1);
                    lmsCount = lms.Count;
                }
                string info = string.Format("SN: {0}\nTotal Records: {1}\nTemp Max/Min/Avg: {2}/{3}/{4}\nHumidity Max/Min/Avg: {5}/{6}/{7}", mainWindow.captor.Serial_number, lmsCount, tmpMax, tmpMin, tmpAvg, humMax, humMin, humAvg);
                page.Canvas.DrawImage();
                page.Canvas.DrawString(info,
                                       new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 12f),
                                       new PdfSolidBrush(new PdfRGBColor()),
                                       10, 60);

                page.Canvas.DrawString("Temperature and humidity data",
                                       new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 18f),
                                       new PdfSolidBrush(new PdfRGBColor()),
                                       10, 140);

                page.Canvas.DrawString(data,
                                       new Spire.Pdf.Graphics.PdfFont(PdfFontFamily.Helvetica, 12f),
                                       new PdfSolidBrush(new PdfRGBColor()),
                                       10, 160);
                FileStream to_stream = new FileStream(dlg.FileName, FileMode.Create);
                doc.SaveToStream(to_stream);
                to_stream.Close();
                doc.Close();
            }
        }
        public void AttempImprimir()
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".xlsx";
            dlg.Filter     = "Documentos Excel (.xlsx)|*.xlsx";
            if (dlg.ShowDialog() == true)
            {
                string filename = dlg.FileName;
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                excel.Visible = false;

                Workbook  excelPrint      = excel.Workbooks.Open(@"C:\Programs\ElaraInventario\Resources\EntradaDevolucion.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                Worksheet excelSheetPrint = (Worksheet)excelPrint.Worksheets[1];

                //Folio
                excel.Cells[8, 6] = _movimientoModel.UnidMovimiento.ToString();
                //Fecha
                excel.Cells[8, 23] = _movimientoModel.FechaMovimiento;

                //Empresa
                excel.Cells[11, 12] = _movimientoModel.EmpresaLectura.EMPRESA_NAME;
                //Solicitante y su área
                excel.Cells[13, 12] = _movimientoModel.SolicitanteLectura.SOLICITANTE_NAME;
                excel.Cells[15, 12] = _movimientoModel.DepartamentoLectura.DEPARTAMENTO_NAME;
                //Procedencia
                string p = "";


                try
                {
                    if (_movimientoModel.ProveedorProcedenciaLectura != null)
                    {
                        p = "Proveedor : " + _movimientoModel.ProveedorProcedenciaLectura.PROVEEDOR_NAME;
                    }
                    else
                    {
                        p = "Cliente: " + _movimientoModel.ClienteProcedenciaLectura.CLIENTE1;
                    }

                    excel.Cells[17, 12] = p.ToString();

                    //Destino
                    excel.Cells[19, 12] = "Almacén: " + _movimientoModel.AlmacenDestino.ALMACEN_NAME;
                    //Recibe
                    excel.Cells[21, 12] = _movimientoModel.Tecnico.TECNICO_NAME;
                }
                catch (Exception ex)
                {
                }
                //TT
                excel.Cells[23, 12] = _movimientoModel.Tt;
                //Transporte
                excel.Cells[25, 12] = _movimientoModel.Transporte.TRANSPORTE_NAME;
                //Contacto
                excel.Cells[27, 12] = _movimientoModel.Contacto;
                //Guia
                excel.Cells[29, 12] = _movimientoModel.Guia;

                int X = 37;
                Microsoft.Office.Interop.Excel.Borders borders;

                for (int i = 0; i < ItemModel.ItemModel.Count; i++)
                {
                    //for (int i = 0; i < 5; i++)  {

                    //No.
                    excel.Range[excel.Cells[X, 2], excel.Cells[X, 3]].Merge();
                    excel.Range[excel.Cells[X, 2], excel.Cells[X, 3]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 2] = (i + 1).ToString() + ".-";
                    borders           = excel.Range[excel.Cells[X, 2], excel.Cells[X, 3]].Borders;
                    borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //DESCRIPCIÓN
                    excel.Range[excel.Cells[X, 4], excel.Cells[X, 22]].Merge();
                    excel.Range[excel.Cells[X, 4], excel.Cells[X, 22]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 4] = ItemModel.ItemModel[i].Articulo.ARTICULO1;
                    borders           = excel.Range[excel.Cells[X, 4], excel.Cells[X, 22]].Borders;
                    borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //N° DE SERIE
                    excel.Range[excel.Cells[X, 23], excel.Cells[X, 26]].Merge();
                    excel.Range[excel.Cells[X, 23], excel.Cells[X, 26]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 23] = ItemModel.ItemModel[i].NUMERO_SERIE;
                    borders            = excel.Range[excel.Cells[X, 23], excel.Cells[X, 26]].Borders;
                    borders.LineStyle  = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //SKU
                    excel.Range[excel.Cells[X, 27], excel.Cells[X, 30]].Merge();
                    excel.Range[excel.Cells[X, 27], excel.Cells[X, 30]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 27] = ItemModel.ItemModel[i].SKU;
                    borders            = excel.Range[excel.Cells[X, 27], excel.Cells[X, 30]].Borders;
                    borders.LineStyle  = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    //CANTIDAD
                    excel.Range[excel.Cells[X, 31], excel.Cells[X, 34]].Merge();
                    excel.Range[excel.Cells[X, 31], excel.Cells[X, 34]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    excel.Cells[X, 31] = ItemModel.ItemModel[i].CantidadMovimiento;
                    borders            = excel.Range[excel.Cells[X, 31], excel.Cells[X, 34]].Borders;
                    borders.LineStyle  = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                    X++;
                }

                X += 2;
                excel.Cells[X, 3] = "OBSERVACIONES:";
                excel.Range[excel.Cells[X, 9], excel.Cells[X + 2, 33]].Merge();
                borders           = excel.Range[excel.Cells[X, 9], excel.Cells[X + 2, 33]].Borders;
                borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                X += 4;
                excel.Range[excel.Cells[X, 2], excel.Cells[X, 17]].Merge();
                excel.Range[excel.Cells[X, 2], excel.Cells[X, 17]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                excel.Cells[X, 2]           = "ENTREGADO POR:";
                excel.Cells[X, 2].Font.Bold = true;
                excel.Range[excel.Cells[X, 18], excel.Cells[X, 34]].Merge();
                excel.Range[excel.Cells[X, 18], excel.Cells[X, 34]].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                excel.Cells[X, 18]           = "RECIBIDO POR:";
                excel.Cells[X, 18].Font.Bold = true;
                X += 1;
                excel.Range[excel.Cells[X, 2], excel.Cells[X + 2, 17]].Merge();
                borders           = excel.Range[excel.Cells[X, 2], excel.Cells[X + 2, 17]].Borders;
                borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
                excel.Range[excel.Cells[X, 18], excel.Cells[X + 2, 34]].Merge();
                borders           = excel.Range[excel.Cells[X, 18], excel.Cells[X + 2, 34]].Borders;
                borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;



                excelSheetPrint.SaveAs(filename, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                excel.Visible = true;
            }
        }
Esempio n. 53
0
        private void WriteSourceFile(string filename_full, string data)
        {
            try
            {
                _bDialogVisible = true;
                bool   continueSave   = false;
                string selected_fname = "";
                if (_chkPromptToSave.IsChecked == true)
                {
                    string directory = System.IO.Path.GetDirectoryName(filename_full);
                    string filename  = System.IO.Path.GetFileName(filename_full);

                    string ext = System.IO.Path.GetExtension(filename);
                    Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                    dlg.FileName         = filename;                               // Default file name
                    dlg.InitialDirectory = directory;
                    dlg.DefaultExt       = ext;                                    // Default file extension
                    dlg.Filter           = "Text documents (" + ext + ")|*" + ext; // Filter files by extension

                    // Show save file dialog box
                    continueSave = (dlg.ShowDialog() == true);
                    if (continueSave)
                    {
                        selected_fname = dlg.FileName;
                    }
                }
                else
                {
                    selected_fname = filename_full;
                    if (_chkAutoOverwrite.IsChecked == false)
                    {
                        if (System.IO.File.Exists(filename_full) == false)
                        {
                            //We could add to "overwrite file" here, if we want.
                            continueSave = true;
                        }
                        else
                        {
                            if (_chkPromptOverwrite.IsChecked == true)
                            {
                                MessageBoxResult mr = MessageBox.Show("Overwrite '" + selected_fname + "'?", "Confirm Overwrite",
                                                                      MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                                if (mr == MessageBoxResult.Yes)
                                {
                                    continueSave = true;
                                }
                            }
                            else
                            {
                                Globals.LogError("File '" + filename_full + "' already exists.");
                            }
                        }
                    }
                    else
                    {
                        Globals.Log("Overwriting '" + filename_full + "'.");
                        continueSave = true;
                    }
                }

                // Process save file dialog box results
                if (continueSave == true)
                {
                    //Try to create file directory
                    string dir = System.IO.Path.GetDirectoryName(selected_fname);
                    try
                    {
                        if (!System.IO.Directory.Exists(dir))
                        {
                            System.IO.Directory.CreateDirectory(dir);
                        }
                    }
                    catch (Exception ex)
                    {
                        Globals.LogError("Could not create directory '" + dir + "': " + ex.ToString());
                    }


                    using (var fs = new System.IO.FileStream(selected_fname, System.IO.FileMode.Create, System.IO.FileAccess.Write))
                    {
                        using (System.IO.StreamWriter bw = new System.IO.StreamWriter(fs))
                        {
                            bw.Write(data);
                        }
                    }
                    _lstGeneratedFiles.Add(selected_fname);
                    Globals.Log("Generated Filename = " + selected_fname);
                }
            }
            catch (Exception ex)
            {
                Globals.LogError("Error writing file: " + ex.ToString());
            }
            finally
            {
                _bDialogVisible = false;
            }
        }
Esempio n. 54
0
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            if (pwA.Password != pwB.Password)
            {
                MessageBox.Show("Passwords unequal", "Error");
                return;
            }
            if (pwA.Password.Length == 0)
            {
                MessageBox.Show("No Password given", "Error");
                return;
            }
            if (string.IsNullOrWhiteSpace(serverFilePath))
            {
                MessageBox.Show("No Server DLL Specified", "Error");
                return;
            }
            status[1]          = true;
            pb.IsIndeterminate = true;
            var dlg = new Microsoft.Win32.SaveFileDialog()
            {
                RestoreDirectory = true,
                AddExtension     = true,
                DefaultExt       = "*.edll",
                FileName         = Path.GetFileNameWithoutExtension(serverFilePath),
                DereferenceLinks = true,
                Title            = "Save as",
                ValidateNames    = true,
                Filter           = "Encrypted Server *.edll|*.edll"
            };

            if (dlg.ShowDialog() == false)
            {
                pb.IsIndeterminate = false;
                return;
            }
            switch (encryptionType)
            {
            case EncryptedServerConfig.EncryptionType.AES:
                crypto = new ServerCryptoAES();
                break;
            }
            cfg.Encryption = encryptionType;
            var enc     = new CryptoWrapper <IServerCrypto>(crypto);
            var mutated = enc.KeyMutation(pwA.SecurePassword);
            var dat     = new Dictionary <string, byte[]>();

            try {
                foreach (var f in localFiles)
                {
                    var sh = Path.GetFileName(f);
                    dat.Add(sh, enc.Encrypt(File.ReadAllBytes(f), mutated));
                    cfg.EncryptedFiles.Add(sh);
                }
                dat.Add(cfg.ServerFileName, enc.Encrypt(File.ReadAllBytes(serverFilePath), mutated));
                if (encryptionType == EncryptedServerConfig.EncryptionType.CUSTOM)
                {
                    cfg.CryptoFileName = Path.GetFileName(cryptoPath);
                    dat.Add(cfg.CryptoFileName, File.ReadAllBytes(cryptoPath));
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.ToString(), "ERROR reading and encrypting files");
                pb.IsIndeterminate = false;
                return;
            }
            try {
                if (File.Exists(dlg.FileName))
                {
                    File.Delete(dlg.FileName);
                }
                using (var fs = File.Open(dlg.FileName, FileMode.CreateNew)) {
                    using (var a = new ZipArchive(fs, ZipArchiveMode.Create)) {
                        foreach (var k in dat.Keys)
                        {
                            using (var eStream = a.CreateEntry(k).Open())
                                eStream.Write(dat[k], 0, dat[k].Length);
                        }
                        using (var configStream = a.CreateEntry(EncryptedServerConfig.ConfigFileName).Open())
                            cfg.Save(configStream);
                    }
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.ToString(), "ERROR compressing files");
                pb.IsIndeterminate = false;
                return;
            }
            status[5]          = true;
            pb.IsIndeterminate = false;
            ShowStatus();
        }
Esempio n. 55
0
        private void OnSave_Button_Clicked(object sender, RoutedEventArgs e)
        {
            foreach (var dealCfg in _dealCfgs)
            {
                int total = 13;
                if (dealCfg.IsBanker)
                {
                    total = 14;
                }

                if (dealCfg.TilesHand.Count != 0 && dealCfg.TilesHand.Count != total)
                {
                    DrawForDealCfg(dealCfg);
                }
            }

            foreach (var dealCfg in _dealCfgs)
            {
                int total = 13;
                if (dealCfg.IsBanker)
                {
                    total = 14;
                }

                if (dealCfg.TilesHand.Count != 0 && dealCfg.TilesHand.Count != total)
                {
                    MessageBox.Show($"The {dealCfg.Index} set config hand tiles must equal to {total}");
                    return;
                }
            }

            for (int i = 3; i > 0; i--)
            {
                if (_dealCfgs[i].TilesHand.Count > 0 && _dealCfgs[i - 1].TilesHand.Count == 0)
                {
                    MessageBox.Show("config must continuous");
                    return;
                }
            }

            if (_dealCfgs[0].TilesHand.Count < 1 || _dealCfgs[1].TilesHand.Count < 1)
            {
                MessageBox.Show("at least have 2 player config");
                return;
            }

            //名称	userID1	手牌	花牌	动作提示	userID2	手牌	花牌	动作提示	userID3	手牌	花牌	动作提示	userID4	手牌	花牌	动作提示	抽牌序列	庄家	风牌
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            var cfgName = "xyz";

            if (string.IsNullOrWhiteSpace(tbCfgName.Text) == false)
            {
                cfgName = tbCfgName.Text;
            }

            dlg.FileName = "user-new-" + cfgName;          // Default file name

            dlg.DefaultExt = ".csv";                       // Default file extension
            dlg.Filter     = "CSV documents (.csv)|*.csv"; // Filter files by extension

            // Show save file dialog box
            bool?dlgResult = dlg.ShowDialog();

            // Process save file dialog box results
            if (dlgResult == true)
            {
                try
                {
                    // Save document
                    string filename = dlg.FileName;
                    using (var textWriter =
                               new StreamWriter(new FileStream(filename, FileMode.Create, FileAccess.ReadWrite),
                                                Encoding.Default))
                    {
                        var expectedHeaders = MyCsvHeaders.GetHeaders(_gameType);
                        // 第一行
                        var csv = new CsvWriter(textWriter);
                        foreach (var header in expectedHeaders)
                        {
                            csv.WriteField(header);
                        }
                        csv.NextRecord();

                        // 第二行
                        csv.WriteField(cfgName); // 名字
                        csv.WriteField(MyCsvHeaders.GetRoomTypeName(_gameType));

                        foreach (var dealCfg in _dealCfgs)
                        {
                            dealCfg.WriteCsv(csv);
                        }

                        csv.WriteField(_drawCfg.ToTilesString()); // 抽牌序列
                        csv.WriteField("");                       // 风牌/加价局
                        csv.WriteField(0);                        // 强制一致
                        csv.WriteField("");                       // 房间配置ID
                        if (_gameType == RoomType.DafengMJ)
                        {
                            csv.WriteField("0"); // 是否连庄
                            csv.WriteField("0"); // 家家庄
                        }
                        else if (_gameType == RoomType.DongTaiMJ)
                        {
                            csv.WriteField("0"); // 是否连庄
                        }

                        csv.NextRecord();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
        //closes tab-dataset from 'X' icon
        void b_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement fe    = sender as FrameworkElement;
            FrameworkElement tag   = fe.Tag as FrameworkElement;
            TabItem          panel = tag as TabItem;
            string           fullpathdatasetname = (panel.Tag as DataSource).FileName;

            if (System.Windows.MessageBox.Show("Do you want to close " + fullpathdatasetname + " Dataset?",
                                               "Do you want to close Dataset?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                //Close Dataset in R first
                IUnityContainer container  = LifetimeService.Instance.Container;
                IDataService    service    = container.Resolve <IDataService>();
                IUIController   controller = container.Resolve <IUIController>();
                DataSource      actds      = controller.GetActiveDocument();//06Nov2012
                if (actds == null)
                {
                    return;
                }
                /////Save Prompt////13Mar2014
                bool   cancel    = false;
                string extension = controller.GetActiveDocument().Extension;
                string filename  = controller.GetActiveDocument().FileName;
                if (controller.GetActiveDocument().Changed)//Changes has been done. Do you want to save or Discard
                {
                    System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show("Do you want to save changes?",
                                                                                                    "Save Changes?",
                                                                                                    System.Windows.Forms.MessageBoxButtons.YesNoCancel,
                                                                                                    System.Windows.Forms.MessageBoxIcon.Question);
                    if (result == System.Windows.Forms.DialogResult.Yes)//save
                    {
                        //If filetype=SPSS then save in RDATA format
                        //For other filetypes data grid can be saved but not the variable grid.
                        // For saving data grid and var grid only save in RDATA format
                        if (extension.Trim().Length < 1 || extension.Equals("sav")) //if no extension or if sav file. no extension in case of new dataset created.
                        {
                            Microsoft.Win32.SaveFileDialog saveasFileDialog = new Microsoft.Win32.SaveFileDialog();
                            saveasFileDialog.Filter = "R Obj (*.RData)|*.RData";
                            bool?output = saveasFileDialog.ShowDialog(System.Windows.Application.Current.MainWindow);
                            if (output.HasValue && output.Value)
                            {
                                service.SaveAs(saveasFileDialog.FileName, controller.GetActiveDocument());// #0
                            }
                        }
                        else
                        {
                            service.SaveAs(filename, controller.GetActiveDocument());// #0
                        }
                    }
                    else if (result == System.Windows.Forms.DialogResult.No)//Dont save
                    {
                        //Do nothing
                    }
                    else // Dont close the dataset/tab
                    {
                        cancel = true;
                    }

                    //Sort icon fix
                    controller.sortasccolnames  = null; //These 2 lines will make sure this is reset. Fix for issue with sort icon
                    controller.sortdesccolnames = null; // Sort dataset col. Close it. Reopen it and you still see sort icons.
                }

                if (!cancel)
                {
                    //// Dataset Closing in UI //////
                    service.Close(controller.GetActiveDocument());
                    // Close the Tab
                    docGroup.Items.Remove(tag);//OR//closeTab(panel);
                    ////13Feb2013 Also remove related dialogs from sessiondialog list
                    RemoveSessionDialogs(panel);
                }
            }
        }
Esempio n. 57
0
        public async Task OutputResultsAsync(IQueryRunner runner, IQueryTextProvider textProvider)
        {
            var dlg = new Microsoft.Win32.SaveFileDialog
            {
                DefaultExt = ".csv",
                Filter     = "Comma separated text file - UTF8|*.csv|Tab separated text file|*.txt|Comma separated text file - Unicode|*.csv|Custom Export Format (Configure in Options)|*.csv"
            };

            string fileName   = "";
            long   durationMs = 0;
            // Show save file dialog box
            var result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Save document
                fileName = dlg.FileName;
                await Task.Run(() =>
                {
                    try
                    {
                        runner.OutputMessage("Query Started");

                        var sw = Stopwatch.StartNew();

                        string sep = "\t";
                        bool shouldQuoteStrings = true; //default to quoting all string fields
                        string decimalSep       = System.Globalization.CultureInfo.CurrentUICulture.NumberFormat.CurrencyDecimalSeparator;
                        string isoDateFormat    = string.Format(Constants.IsoDateMask, decimalSep);
                        Encoding enc            = new UTF8Encoding(false);

                        switch (dlg.FilterIndex)
                        {
                        case 1:     // utf-8 csv
                            sep = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
                            break;

                        case 2:     // tab separated
                            sep = "\t";
                            break;

                        case 3:     // unicode csv
                            enc = new UnicodeEncoding();
                            sep = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
                            break;

                        case 4:    // custom export format
                            sep = runner.Options.GetCustomCsvDelimiter();
                            shouldQuoteStrings = runner.Options.CustomCsvQuoteStringFields;
                            break;
                        }

                        var daxQuery = textProvider.QueryText;
                        var reader   = runner.ExecuteDataReaderQuery(daxQuery, textProvider.ParameterCollection);

                        using (var statusProgress = runner.NewStatusBarMessage("Starting Export"))
                        {
                            try
                            {
                                if (reader != null)
                                {
                                    int iFileCnt = 1;


                                    runner.OutputMessage("Command Complete, writing output file");

                                    bool moreResults = true;

                                    while (moreResults)
                                    {
                                        var outputFilename = fileName;
                                        int iRowCnt        = 0;
                                        if (iFileCnt > 1)
                                        {
                                            outputFilename = AddFileCntSuffix(fileName, iFileCnt);
                                        }
                                        using (var textWriter = new System.IO.StreamWriter(outputFilename, false, enc))
                                        {
                                            iRowCnt = reader.WriteToStream(textWriter, sep, shouldQuoteStrings, isoDateFormat, statusProgress);
                                        }
                                        runner.OutputMessage(
                                            string.Format("Query {2} Completed ({0:N0} row{1} returned)"
                                                          , iRowCnt
                                                          , iRowCnt == 1 ? "" : "s", iFileCnt)
                                            );

                                        runner.RowCount = iRowCnt;

                                        moreResults = reader.NextResult();

                                        iFileCnt++;
                                    }

                                    sw.Stop();
                                    durationMs = sw.ElapsedMilliseconds;

                                    runner.SetResultsMessage("Query results written to file", OutputTarget.File);
                                    runner.ActivateOutput();
                                }
                                else
                                {
                                    runner.OutputError("Query Batch Completed with errors listed above (you may need to scroll up)", durationMs);
                                }
                            }
                            finally
                            {
                                if (reader != null)
                                {
                                    reader.Dispose();
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, Common.Constants.LogMessageTemplate, nameof(ResultsTargetTextFile), nameof(OutputResultsAsync), ex.Message);
                        runner.ActivateOutput();
                        runner.OutputError(ex.Message);
#if DEBUG
                        runner.OutputError(ex.StackTrace);
#endif
                    }
                    finally
                    {
                        runner.OutputMessage("Query Batch Completed", durationMs);
                        runner.QueryCompleted();
                    }
                });
            }
            // else dialog was cancelled so return an empty task.
            await Task.Run(() => { });
        }
Esempio n. 58
0
            /// <summary>
            /// The export products.
            /// </summary>
            /// <param name="prodLists">
            /// The prod lists.
            /// </param>
            /// <param name="location">
            /// The location.
            /// </param>
            /// <param name="principal">
            /// The principal.
            /// </param>
            /// <param name="category">
            /// The category.
            /// </param>
            public static void ExportProducts(List <Product> prodLists, string location, string principal, string category)
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName   = DateTime.Now.ToString("MMMMM dd yyyy") + " - Product Inventory Report"; // Default file name
                dlg.DefaultExt = ".xlsx";                                                                // Default file extension
                dlg.Filter     = "Excel Document (.xlsx)|*.xlsx";                                        // Filter files by extension
                Nullable <bool> result = dlg.ShowDialog();

                if (result == true)
                {
                    string   filename     = dlg.FileName;
                    FileInfo templateFile = new FileInfo(@"Product Template.xlsx");
                    FileInfo newFile      = new FileInfo(filename);
                    if (newFile.Exists)
                    {
                        try
                        {
                            newFile.Delete();
                            newFile = new FileInfo(filename);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show(
                                "The file is currently being used, close the file or choose a different name.",
                                "Error",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                            return;
                        }
                    }

                    var config        = StockbookWindows.OpenConfig();
                    var currencyStyle = string.Empty;
                    var currency      = string.Empty;
                    switch (config.Currency)
                    {
                    case "PHP - ₱":
                        currencyStyle = "₱#,###,##0.00";
                        currency      = "Peso";
                        break;

                    case "USD - $":
                        currencyStyle = "$#,###,##0.00";
                        currency      = "Dollar";
                        break;

                    case "YEN - ¥":
                        currencyStyle = "¥#,###,##0.00";
                        currency      = "Yen";
                        break;
                    }


                    using (ExcelPackage package = new ExcelPackage(newFile, templateFile))
                    {
                        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                        worksheet.Cells["A1"].Value = config.CompanyName;
                        worksheet.Cells["A3"].Value = "As of " + DateTime.Now.ToString("MMMM dd, yyyy");
                        worksheet.Cells["A4"].Value = "Location: " + location;
                        worksheet.Cells["A5"].Value = "Principal: " + principal;
                        worksheet.Cells["A6"].Value = "Category: " + category;
                        worksheet.Cells["G8"].Value = currency + " Value";
                        int     i            = 10;
                        decimal grandTotal   = 0;
                        decimal subTotal     = 0;
                        string  tempCategory = string.Empty;
                        var     categories   = prodLists.Select(q => q.Category).Distinct().OrderBy(q => q);
                        foreach (var cat in categories)
                        {
                            foreach (var prod in prodLists.Where(q => q.Category == cat))
                            {
                                var caseVal  = prod.CaseValue * prod.CaseBalance;
                                var packVal  = prod.PackValue * prod.PackBalance;
                                var pieceVal = prod.PieceValue * prod.PieceBalance;
                                if (tempCategory == string.Empty || tempCategory != prod.Category)
                                {
                                    worksheet.Cells["A" + i].Value = prod.Category;
                                    tempCategory = prod.Category;
                                }
                                worksheet.Cells["B" + i].Value = prod.Name;
                                worksheet.Cells["C" + i].Value = prod.ProdCode;
                                worksheet.Cells["D" + i].Value = prod.CaseBalance;
                                worksheet.Cells["E" + i].Value = prod.PackBalance;
                                worksheet.Cells["F" + i].Value = prod.PieceBalance;
                                worksheet.Cells["G" + i].Value = caseVal;
                                worksheet.Cells["H" + i].Value = packVal;
                                worksheet.Cells["I" + i].Value = pieceVal;
                                worksheet.Cells["J" + i].Value = caseVal + packVal + pieceVal;
                                subTotal += caseVal + packVal + pieceVal;
                                i++;
                            }
                            worksheet.Cells["I" + i].Value = "Subtotal:";
                            worksheet.Cells["J" + i].Value = subTotal;

                            i++;
                            grandTotal  += subTotal;
                            subTotal     = 0;
                            tempCategory = cat;
                        }
                        i++;
                        worksheet.Cells["I" + i].Value           = "Grandtotal:";
                        worksheet.Cells["J" + i].Value           = grandTotal;
                        worksheet.Cells["J" + i].Style.Font.Bold = true;
                        worksheet.Cells["J" + i].Style.Font.Size = 16;

                        worksheet.Cells["J" + 10 + ":J" + i].Style.Numberformat.Format = currencyStyle;

                        worksheet.View.PageLayoutView = false;
                        package.Save();
                    }
                }
            }
Esempio n. 59
0
            /// <summary>
            /// The export transactions.
            /// </summary>
            /// <param name="orderList">
            /// The order list.
            /// </param>
            /// <param name="dateFrom">
            /// The date from.
            /// </param>
            /// <param name="dateTo">
            /// The date to.
            /// </param>
            public static void ExportTransactions(List <TransactionOrder> orderList, DateTime dateFrom, DateTime dateTo)
            {
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                dlg.FileName   = DateTime.Now.ToString("MMMMM dd yyyy") + " - Stock Cards"; // Default file name
                dlg.DefaultExt = ".xlsx";                                                   // Default file extension
                dlg.Filter     = "Excel Document (.xlsx)|*.xlsx";                           // Filter files by extension
                Nullable <bool> result = dlg.ShowDialog();

                if (result == true)
                {
                    string   filename     = dlg.FileName;
                    FileInfo templateFile = new FileInfo(@"Transaction Template.xlsx");
                    FileInfo newFile      = new FileInfo(filename);
                    if (newFile.Exists)
                    {
                        try
                        {
                            newFile.Delete();
                            newFile = new FileInfo(filename);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show(
                                "The file is currently being used, close the file or choose a different name.",
                                "Error",
                                MessageBoxButton.OK,
                                MessageBoxImage.Error);
                            return;
                        }
                    }
                    using (ExcelPackage package = new ExcelPackage(newFile, templateFile))
                    {
                        var            listStock    = OrderListToStockCard(orderList, dateFrom, dateTo);
                        int            worksheetNum = 1;
                        ExcelWorksheet worksheet    = null;
                        foreach (var list in listStock)
                        {
                            worksheet = package.Workbook.Worksheets.Copy("Sheet1", list.Description);
                            worksheet.Cells["A3"].Value = "LOCATION: " + list.Location;
                            worksheet.Cells["A4"].Value = "DATE: " + list.DateFrom.ToString("MMMM dd, yyyy") + " - " + list.DateTo.ToString("MMMM dd, yyyy");
                            worksheet.Cells["B5"].Value = list.Description;
                            worksheet.Cells["B6"].Value = list.Category;
                            worksheet.Cells["B7"].Value = list.ProdCode;
                            int cellNumber = 9;
                            foreach (var trans in list.ListTransactions)
                            {
                                worksheet.Cells["A" + cellNumber].Value = trans.Date.ToString("MMMM dd, yyyy");
                                worksheet.Cells["B" + cellNumber].Value = trans.RefNo;
                                worksheet.Cells["C" + cellNumber].Value = trans.Transaction;
                                worksheet.Cells["D" + cellNumber].Value = trans.Case;
                                worksheet.Cells["E" + cellNumber].Value = trans.Pack;
                                worksheet.Cells["F" + cellNumber].Value = trans.Piece;
                                worksheet.Cells["G" + cellNumber].Value = trans.CaseBalance;
                                worksheet.Cells["H" + cellNumber].Value = trans.PackBalance;
                                worksheet.Cells["I" + cellNumber].Value = trans.PieceBalance;
                                worksheet.Cells["J" + cellNumber].Value = trans.Particular;
                                cellNumber++;
                            }

                            worksheetNum++;
                        }
                        package.Workbook.Worksheets.Delete("Sheet1");
                        worksheet.View.PageLayoutView = false;

                        package.Save();
                    }
                }
            }
Esempio n. 60
0
        private void buttonExportAsPng_Click(object sender, RoutedEventArgs e)
        {
            this.StatusText = "Starting export.";

            if (this.IsRunning)
            {
                this.StatusText = "Please wait until current process is completed.";
                return;
            }

            if (!System.IO.File.Exists(this.Settings.MapFilePath))
            {
                this.StatusText = "Please select a map file first.";
                return;
            }

            var dlgresult = m_SaveFileDialog.ShowDialog();

            if (dlgresult.Value == true)
            {
                string imagefilename = this.m_SaveFileDialog.FileName;
                this.Settings.ImageFilePath = imagefilename;
                if (this.SelectedSaveGame != null)
                {
                    this.SelectedSaveGame.ImageFilePath = imagefilename;
                }

                // Ausgabedatei prüfen, ob Ordner existiert und Dateiname mit .png endet
                string outputFolder = System.IO.Path.GetDirectoryName(imagefilename);
                if (!Directory.Exists(outputFolder))
                {
                    Directory.CreateDirectory(outputFolder);
                }

                if (!imagefilename.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                {
                    imagefilename += ".png";
                }


                this.m_Stopwatch.Restart();
                this.IsRunning = true;
                var bw = new BackgroundWorker();
                bw.DoWork += (s, a) =>
                {
                    var pois = POI.FromCsvFile(this.Settings.PoiFilePath);

                    //var waypoints = Util.GetPOIsFromSavegame(this.Settings.MapFilePath);
                    string directory   = System.IO.Path.GetDirectoryName(this.Settings.MapFilePath);
                    string ttpfilename = System.IO.Path.GetFileNameWithoutExtension(this.Settings.MapFilePath) + ".ttp";
                    ttpfilename = System.IO.Path.Combine(directory, ttpfilename);
                    var waypoints = POI.FromTtpFile(ttpfilename);
                    pois = pois.Concat(waypoints);

                    var map = new MapRenderer();
                    map.TileSize         = (int)this.Settings.SelectedTileSize;
                    map.RenderBackground = this.Settings.RenderBackground;
                    map.RenderGrid       = this.Settings.RenderGrid;
                    map.GridSize         = this.Settings.GridSize;
                    map.GridColor        = System.Drawing.Color.FromArgb(this.Settings.AlphaValue,
                                                                         System.Drawing.Color.FromName(this.Settings.SelectedGridColorName));
                    map.RenderRegionNumbers = this.Settings.RenderRegionNumbers;
                    map.RegionFontName      = this.Settings.RegionFontName;
                    map.RegionFontEmSize    = this.Settings.RegionFontEmSize;
                    map.RenderWaypoints     = this.Settings.RenderWaypoints;
                    map.WaypointFontColor   = System.Drawing.Color.FromName(this.Settings.SelectedWaypointFontColorName);
                    map.WaypointFontName    = this.Settings.WaypointFontName;
                    map.WaypointFontEmSize  = this.Settings.WaypointFontEmSize;
                    map.UseDataStore        = this.Settings.UseDataStore;

                    map.RenderWholeMap(this.Settings.MapFilePath, imagefilename, pois, (IProgressService)this);
                };
                bw.RunWorkerCompleted += (s, a) =>
                {
                    this.m_Stopwatch.Stop();
                    this.IsRunning = false;
                    if (a.Error != null)
                    {
                        this.StatusText = a.Error.GetType().ToString() + ": " + a.Error.Message.ToString();
                    }
                    else
                    {
                        this.StatusText = String.Format("Done in {0}.", this.m_Stopwatch.Elapsed);
                    }
                };
                bw.RunWorkerAsync();

                this.m_SaveFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(this.m_SaveFileDialog.FileName);
            }
            else
            {
                this.StatusText = "Export aborted.";
            }
        }