public static void 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();
            }
    }
        public bool OpenSaveFileDialog(string title, string defaultFileName, string initialDirectory, string filter, bool overwritePrompt,
                                       out string selectedFilePath, out int selectedFilterIndex)
        {
            var dialog = new SaveFileDialog
                         {
                             OverwritePrompt = overwritePrompt,
                             Title = title,
                             Filter = filter,
                             FileName = defaultFileName,
                             ValidateNames = true,
                             InitialDirectory = initialDirectory
                         };

            bool? result = dialog.ShowDialog();
            if (result ?? false)
            {
                selectedFilePath = dialog.FileName;
                selectedFilterIndex = dialog.FilterIndex;
                return true;
            }
            else
            {
                selectedFilePath = null;
                selectedFilterIndex = -1;
                return false;
            }
        }
        public bool? ShowDialog()
        {
            var dialog = new SaveFileDialog();
            if (AddExtension != null)
            {
                dialog.AddExtension = AddExtension.Value;
            }

            if (DefaultExt != null)
            {
                dialog.DefaultExt = DefaultExt;
            }

            if (InitialDirectory != null)
            {
                dialog.InitialDirectory = InitialDirectory;
            }

            if (Filter != null)
            {
                dialog.Filter = Filter;
            }

            bool? result = dialog.ShowDialog(Application.Current.MainWindow);
            FileName = dialog.FileName;
            return result;
        }
        public void Execute(object parameter)
        {
            var fileName = Path.GetFileName(LogSource.Instance.LogFileLocation);
            var saveLocation = new SaveFileDialog
            {
                AddExtension = true,
                Filter = ".json | JSON File",
                FileName = fileName,
                Title = "Export log config to..."
            };

            var result = saveLocation.ShowDialog();
            if (!result.HasValue || !result.Value || string.IsNullOrEmpty(saveLocation.FileName))
                return;

            // save the file
            File.Copy(LogSource.Instance.LogFileLocation, saveLocation.FileName);

            // browse to it in explorer
            var args = $"/e, /select, \"{saveLocation.FileName}\"";

            var info = new ProcessStartInfo
            {
                FileName = "explorer.exe",
                Arguments = args
            };
            Process.Start(info);
        }
示例#5
0
        void Save()
        {
            try
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.AddExtension = true;
                saveFile.Filter = "Text documents (.txt)|*.txt";
                saveFile.DefaultExt = ".txt";
                saveFile.FileName = "Folder_Rename_Save " + date;
                bool? result = saveFile.ShowDialog();
                
                if (result == true)
                {
                    string contents = "";
                    foreach (string ligne in listeAvancement)
                    {
                        contents += ligne + "\r\n";
                    }

                    File.WriteAllText(saveFile.FileName, contents);
                }
            }
            catch { }
        }
示例#6
0
        private void btnExtractImage_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                _blf = new PureBLF(_blfLocation);
                var sfd = new SaveFileDialog
                {
                    Title = "Save the extracted BLF Image",
                    Filter = "JPEG Image (*.jpg)|*.jpg",
                    FileName = lblBLFname.Text.Replace(".blf", "")
                };

                if (!((bool)sfd.ShowDialog()))
                {
                    Close();
                    return;
                }
                var imageToExtract = new List<byte>(_blf.BLFChunks[1].ChunkData);
                imageToExtract.RemoveRange(0, 0x08);

                File.WriteAllBytes(sfd.FileName, imageToExtract.ToArray<byte>());

                MetroMessageBox.Show("Exracted!", "The BLF Image has been extracted.");
                Close();
            }
            catch (Exception ex)
            {
                Close();
                MetroMessageBox.Show("Extraction Failed!", "The BLF Image failed to be extracted: \n " + ex.Message);
            }
        }
示例#7
0
        public string SaveGame(IClearMine game, string path = null)
        {
            if (game == null)
                throw new ArgumentNullException("game");

            if (String.IsNullOrWhiteSpace(path))
            {
                var savePathDialog = new SaveFileDialog();
                savePathDialog.DefaultExt = Settings.Default.SavedGameExt;
                savePathDialog.Filter = ResourceHelper.FindText("SavedGameFilter", Settings.Default.SavedGameExt);
                if (savePathDialog.ShowDialog() == true)
                {
                    path = savePathDialog.FileName;
                }
                else
                {
                    return null;
                }
            }

            // Pause game to make sure the timestamp correct.
            game.PauseGame();
            var gameSaver = new XmlSerializer(game.GetType());
            using (var file = File.Open(path, FileMode.Create, FileAccess.Write))
            {
                gameSaver.Serialize(file, game);
            }
            game.ResumeGame();

            return path;
        }
示例#8
0
        public void Execute(ICSharpCode.TreeView.SharpTreeNode[] selectedNodes)
        {
            //Gets the loaded assembly
            var loadedAssembly = ((AssemblyTreeNode)selectedNodes[0]).LoadedAssembly;

            //Shows the dialog
            var dialog = new SaveFileDialog()
            {
                AddExtension = false,
                Filter = "Patched version of " + loadedAssembly.AssemblyDefinition.Name.Name + "|*.*",
                FileName = Path.GetFileName(Path.ChangeExtension(loadedAssembly.FileName, ".Patched" + Path.GetExtension(loadedAssembly.FileName))),
                InitialDirectory = Path.GetDirectoryName(loadedAssembly.FileName),
                OverwritePrompt = true,
                Title = "Save patched assembly"
            };
            if (dialog.ShowDialog().GetValueOrDefault(false))
            {
                //Writes the assembly
                loadedAssembly.AssemblyDefinition.Write(dialog.FileName);

                //Clears the coloring of the nodes
                foreach (var x in Helpers.PreOrder(selectedNodes[0], x => x.Children))
                    x.Foreground = GlobalContainer.NormalNodesBrush;
                var normalColor = ((SolidColorBrush)GlobalContainer.NormalNodesBrush).Color;
                MainWindow.Instance.RootNode.Foreground =
                    MainWindow.Instance.RootNode.Children.All(x => x.Foreground is SolidColorBrush && ((SolidColorBrush)x.Foreground).Color == normalColor)
                    ? GlobalContainer.NormalNodesBrush
                    : GlobalContainer.ModifiedNodesBrush;
            }
        }
        public override void Execute(object parameter)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Database file (*.db3) |*.db3";
            if (sfd.ShowDialog() == true)
            {
                SqliteDataProvider dataProvider = new SqliteDataProvider();
                dataProvider.Open(sfd.FileName);

               // string sql = "CREATE TABLE Fossils (id INTEGER PRIMARY KEY AUTOINCREMENT, fossilname TEXT, Descrip TEXT, area REAL, circularity REAL, elongation REAL, perimeter REAL, irregularity REAL , bitmap BLOB)";
                string sql = "CREATE TABLE Authors (Author_id INTEGER PRIMARY KEY AUTOINCREMENT, Author_name TEXT)";
                dataProvider.ExecuteNonQuery(sql);
                string sql1 = "CREATE TABLE Description (Description_id INTEGER PRIMARY KEY AUTOINCREMENT, synonymy TEXT, shell TEXT, init_shell TEXT, crop TEXT, key_edge TEXT, front_end TEXT, rear_end TEXT, ventral_margin TEXT, growth_lines TEXT, sculpture TEXT, compare TEXT)";
                dataProvider.ExecuteNonQuery(sql1);
                string sql2 = "CREATE TABLE Genus (genus_id INTEGER PRIMARY KEY AUTOINCREMENT, genus_name TEXT)";
                dataProvider.ExecuteNonQuery(sql2);
                string sql3 = "CREATE TABLE GenusToAuthor (genus_id INTEGER, author_id INTEGER)";
                dataProvider.ExecuteNonQuery(sql3);
                string sql4 = "CREATE TABLE Parameters (parameters_id INTEGER PRIMARY KEY AUTOINCREMENT, init_shell TEXT, front_rear_end TEXT, age TEXT, length TEXT, sculpture TEXT, h_l REAL)";
                dataProvider.ExecuteNonQuery(sql4);
                string sql5 = "CREATE TABLE Photo (id INTEGER PRIMARY KEY AUTOINCREMENT, square REAL, vertex_x REAL, vertex_y REAL, furrow REAL, bitmap BLOB)";
                dataProvider.ExecuteNonQuery(sql5);
                string sql6 = "CREATE TABLE Species (species_id INTEGER PRIMARY KEY AUTOINCREMENT,species_name TEXT, genus_id INTEGER, description_id INTEGER)";
                dataProvider.ExecuteNonQuery(sql6);
                string sql7 = "CREATE TABLE SpeciesToAuthor (species_id INTEGER, author_id INTEGER)";
                dataProvider.ExecuteNonQuery(sql7);
                string sql8 = "CREATE TABLE Mollusk (mollusk_id INTEGER PRIMARY KEY AUTOINCREMENT, species_id INTEGER, photo_id INTEGER, parameters_id INTEGER)";
                dataProvider.ExecuteNonQuery(sql8);
                UIManager.man.Provider = dataProvider;
            }
        }
示例#10
0
        /// <summary>
        /// Initializes a new instance of the IntroductionViewModel class.
        /// </summary>
        public HomeViewModel(IConfigurationService configurationService)
        {
            _configurationService = configurationService;

            selectedFile = _configurationService.IsFileLoaded() ? "hi" : "";

            CreateNewFileCommand = new RelayCommand(() => {
                var saveFileDialog = new SaveFileDialog();
                saveFileDialog.AddExtension = true;
                saveFileDialog.DefaultExt = "pktd";
                saveFileDialog.Filter = "Parakeet File|*.pktd;*.pkd";
                saveFileDialog.FileOk += SaveFileDialog_FileOk;
                saveFileDialog.ShowDialog();
            }, () => string.IsNullOrEmpty(SelectedFile));

            OpenExistingFileCommand = new RelayCommand(() => {
                var openFileDialog = new OpenFileDialog();
                openFileDialog.AddExtension = true;
                openFileDialog.DefaultExt = "pktd";
                openFileDialog.Filter = "Parakeet File|*.pktd;*.pkd";
                openFileDialog.Multiselect = false;
                openFileDialog.FileOk += OpenFileDialog_FileOk;
                openFileDialog.ShowDialog();
            }, () => string.IsNullOrEmpty(SelectedFile));
        }
        // yuehan start: 保存 baml 到 xaml 文件
        public override bool Save(DecompilerTextView textView)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = Path.GetFileName(DecompilerTextView.CleanUpName(base.Text as string));
            dlg.FileName = Regex.Replace(dlg.FileName, @"\.baml$", ".xaml", RegexOptions.IgnoreCase);
            if (dlg.ShowDialog() == true)
            {
                // 反编译 baml 文件
                var baml = this.Data;
                var asm = this.Ancestors().OfType<AssemblyTreeNode>().FirstOrDefault().LoadedAssembly;
                baml.Position = 0;
                var doc = LoadIntoDocument(asm.GetAssemblyResolver(), asm.AssemblyDefinition, baml);
                var xaml = doc.ToString();

                // 保存 xaml
                FileInfo fi = new FileInfo(dlg.FileName);
                if (fi.Exists) fi.Delete();

                using (var fs = fi.OpenWrite())
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);
                    sw.Write(xaml);
                    sw.Flush();
                    sw.Close();
                }
            }
            return true;
        }
示例#12
0
        public void SaveProject()
        {
            string fileToSave = null;

            if (string.IsNullOrEmpty(ArrowState.Self.CurrentGluxFileLocation))
            {
                SaveFileDialog fileDialog = new SaveFileDialog();
                fileDialog.Filter = "*.arox|*.arox";

                var result = fileDialog.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    fileToSave = fileDialog.FileName;
                    ArrowState.Self.CurrentGluxFileLocation = fileToSave;
                }

            }
            else
            {
                fileToSave = ArrowState.Self.CurrentGluxFileLocation;
            }

            if (!string.IsNullOrEmpty(fileToSave))
            {
                FileManager.XmlSerialize(ArrowState.Self.CurrentArrowProject, fileToSave);
            }
        }
示例#13
0
		/// <summary>Stores the image in the specified type under the specified folder, with the <paramref name="filename" />.</summary>
		public static FileInfo SaveAsFileDialog(this BitmapSource image, string filename = null)
		{
			var dlg = new SaveFileDialog
			{
				FileName = filename ?? "Abbildung",
				DefaultExt = ".png",
				Filter = "PNG|*.png|JPG|*.jpg|GIF|*.gif|BMP|*.bmp|TIFF|*.tiff|WMP|*.wmp"
			};
			var result = dlg.ShowDialog();

			if (result == true)
			{
				var fileInfo = new FileInfo(dlg.FileName);
				fileInfo.CreateDirectory_IfNotExists();
				fileInfo.AppendIndexToFile_IfExists();

				var le = fileInfo.Extension.ToLower();
				if (le == ".png")
					image.SaveAs_PngFile(fileInfo);
				if (le == ".jpg")
					image.SaveAs_JpgFile(fileInfo);
				if (le == ".gif")
					image.SaveAs_GifFile(fileInfo);
				if (le == ".bmp")
					image.SaveAs_BmpFile(fileInfo);
				if (le == ".tiff")
					image.SaveAs_TiffFile(fileInfo);
				if (le == ".wmp")
					image.SaveAs_WmpFile(fileInfo);
				return fileInfo;
			}
			return null;
		}
        private void CreatePuzzleButton_OnClick(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(_filename))
            {
                MessageBox.Show("Image does not selected!");
                return;
            }

            var filePath = _filename;
            var x = XBlocksCount;
            var y = YBlocksCount;
            var generator = new PuzzleCreator(filePath);
            var images = generator.GetMixedPartsOfImage(x, y);
            Bitmap bitmap = generator.GenerateBitmap(images, x, y);

            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = "puzzle";
            saveFileDialog.DefaultExt = ".jpg";
            saveFileDialog.Filter = "Image files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png";

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

            if (result.HasValue && result.Value)
            {
                bitmap.Save(saveFileDialog.FileName);
            }
            else
            {
                MessageBox.Show("Puzzle does not saved!");
            }
        }
        private void Export(object param)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = String.Format("{0} files|*.{1}|{2} files|*.{3}", "Pdf", "pdf", "Text", "txt");

            if (dialog.ShowDialog() == true)
            {
                using (var stream = dialog.OpenFile())
                {
                    RadFixedDocument document = this.CreateDocument();
                    switch (dialog.FilterIndex)
                    {
                        case 1:
                            PdfFormatProvider pdfFormatProvider = new PdfFormatProvider();
                            pdfFormatProvider.Export(document, stream);
                            break;
                        case 2:
                            using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
                            {
                                TextFormatProvider textFormatProvider = new TextFormatProvider();
                                writer.Write(textFormatProvider.Export(document));
                            }
                            break;
                    }
                }
            }
        }
示例#16
0
        //Exports the data from the output window to a csv file
        public void ExportToCSV()
        {
            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "CSV|*.csv";
                saveFileDialog1.Title = "Export to CSV";

                string currentDateTime = DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss");
                saveFileDialog1.FileName = currentDateTime;
                Nullable<bool> saveFileResult = saveFileDialog1.ShowDialog();
                //If saveFileResut is null (user clicked cancel) then do nothing
                if (saveFileResult == false)
                {
                    return;
                }
                //Copy the temporary file with the ping data to a csv file
                else
                {
                    File.Copy(_temporaryPingDataFile, saveFileDialog1.FileName);
                }
            }
            catch (Exception er)
            {
                MessageBox.Show("Error with filename" + Environment.NewLine + Environment.NewLine + er);
                return;
            }
        }
示例#17
0
        public static bool SaveDocument(Document document)
        {
            if (document.IsTemporal)
            {
                var dialog = new SaveFileDialog { DefaultExt = "md", AddExtension = true };
                dialog.Filter = "Markdown files (*.md)|*.md|All files (*.*)|*.*";
                if (dialog.ShowDialog().Value)
                {
                    string destinationFolder = string.Empty;
                    destinationFolder = new FileInfo(dialog.FileName).DirectoryName;
                    try
                    {
                        var sourceFolder = new FileInfo(document.FullFilename).DirectoryName;
                        DirectoryCopy(sourceFolder, destinationFolder, true);
                        document.FolderPath = destinationFolder;
                        File.Move(document.FullFilename, Path.Combine(document.FolderPath, dialog.FileName));
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }
                else
                {
                    return false;
                }
            }
            else
            {
            }

            document.HasChanges = false;
            return true;
        }
示例#18
0
 private void OnSaveCommand(string obj)
 {
     var sf = new SaveFileDialog();
     var fn = sf.FileName;
     if (!string.IsNullOrEmpty(fn))
         SaveReportToFile(fn);
 }
示例#19
0
 public void Execute(object parameter)
 {
     var exportObject = new ExportData();
     using (var irep=_itemsRepos())
     {
         exportObject.EveItems = irep.GetAll().ToArray();
     }
     using (var brep=_blueprintsRepos())
     {
         exportObject.Blueprints = brep.GetAll().ToArray();
     }
     using (var prep=_prodinfoRepos())
     {
         exportObject.ProductionInfos = prep.GetAll().ToArray();
     }
     var res = JsonConvert.SerializeObject(exportObject,Formatting.Indented);
     var dlg = new SaveFileDialog()
         {
             Title = "Экспорт БД",
             Filter = "Data File *.dat|*.dat"
         };
     if (dlg.ShowDialog() == true)
     {
         using (var writer=File.CreateText(dlg.FileName))
         {
             writer.Write(res);
             writer.Close();
         }
     }
 }
        private void snapshotClicked(object sender, RoutedEventArgs e)
        {
            e.Handled = true;

            var imageSource = GridZoomControl.SnapshotToBitmapSource();

            if (imageSource == null)
            {
                MessageBox.Show("Failed to snapshot image");
                return;
            }

            var dialog = new SaveFileDialog
            {
                FileName = "Snapshot.png", Filter = "PNG File (*.png)|*.png"
            };

            if (dialog.ShowDialog(this) == true)
            {
                using (var fs = new FileStream(dialog.FileName, FileMode.Create))
                {
                    var encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(imageSource));
                    encoder.Save(fs);
                }
            }
        }
 private void button3_Click(object sender, RoutedEventArgs e)
 {
     Directory.SetCurrentDirectory("C:/tmp/soundpcker");
     using (ZipFile zip = new ZipFile())
     {
         // add this map file into the "images" directory in the zip archive
         zip.AddFile("pack.mcmeta");
         // add the report into a different directory in the archive
         zip.AddItem("assets");
         zip.AddFile("lcrm");
         zip.Save("CustomSoundInjector_ResourcePack.zip");
     }
         SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.DefaultExt = ".zip";
     saveFileDialog.Filter = "Minecraft ResourcePack (with Bytecode)|*.zip";
     if (saveFileDialog.ShowDialog() == true)
     {
         exportpath = saveFileDialog.FileName;
     }
     else
     {
         MessageBox.Show("Operation Cancelled.", "Cancelled", MessageBoxButton.OK, MessageBoxImage.Error);
     }
     string originExport = "C:/tmp/soundpcker/CustomSoundInjector_ResourcePack.zip";
     File.Copy(originExport, exportpath, true);
     MessageBox.Show("Saved.", "Saved", MessageBoxButton.OK, MessageBoxImage.Information);
 }
示例#22
0
        private static void Export()
        {
            var saveFileDialog = new SaveFileDialog { Filter = "CSV files (*.csv)|*.csv" };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    using (Stream stream = new FileStream(saveFileDialog.FileName, FileMode.Create))
                    {
                        _grid.Export(stream, new GridViewCsvExportOptions
                            {
                                ColumnDelimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator,
                                ShowColumnHeaders = true,
                                ShowColumnFooters = false,
                                ShowGroupFooters = false,
                                Culture = CultureInfo.CurrentCulture,
                                Encoding = Encoding.UTF8,
                                Items = (IEnumerable)_grid.ItemsSource
                            });
                    }
                }

                catch (IOException)
                {
                    MessageBox.Show(String.Format(
                            "Export to file {0} was failed. File used by another process. End process and try again.",
                            saveFileDialog.FileName), "Error");
                }
            }
        }
示例#23
0
        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            var pageSize = this.pager.PageSize;
            var pageIndex = this.pager.PageIndex;

            this.pager.PageIndex = 0;
            this.pager.PageSize = 0;

            string extension = "xlsx";

            SaveFileDialog dialog = new SaveFileDialog()
            {
                DefaultExt = extension,
                Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", extension, "Excel"),
                FilterIndex = 1
            };

            if (dialog.ShowDialog() == true)
            {
                using (Stream stream = dialog.OpenFile())
                {
                    this.clubsGrid.ExportToXlsx(stream);
                }
            }

            this.pager.PageSize = pageSize;
            this.pager.PageIndex = pageIndex;
        }
示例#24
0
        public static void ExportToFile(BitmapSource graphBitmap)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            const int FilterIndexJpeg = 1;
            const int FilterIndexPng = 2;
            saveDialog.Filter = "JPEG|*.jpg|PNG|*.png";
            saveDialog.Title = "Save Graph As";
            saveDialog.AddExtension = true;
            saveDialog.ShowDialog();

            if (string.IsNullOrEmpty(saveDialog.FileName))
            {
                return;
            }

            using (FileStream fileStream = (FileStream)saveDialog.OpenFile())
            {
                BitmapEncoder bitmapEncoder;

                switch (saveDialog.FilterIndex)
                {
                    case FilterIndexJpeg:
                        bitmapEncoder = new JpegBitmapEncoder();
                        break;
                    case FilterIndexPng:
                        bitmapEncoder = new PngBitmapEncoder();
                        break;
                    default:
                        throw new ArgumentException("Invalid file save type");
                }

                bitmapEncoder.Frames.Add(BitmapFrame.Create(graphBitmap));
                bitmapEncoder.Save(fileStream);
            }
        }
示例#25
0
 // Exports statistics to csv file
 private void ExportStatistics()
 {
     SaveFileDialog exportDialog = new SaveFileDialog();
     exportDialog.DefaultExt = "csv";
     if (exportDialog.ShowDialog() == true)
         StatisticsManager.Instance.ExportStatistics(exportDialog.FileName);
 }
示例#26
0
        public static void ExportPivotToExcel(RadPivotGrid pivot)
        {        
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = "xlsx";
          //  dialog.Filter = "CSV files (*.csv)|*.csv |All Files (*.*) | *.*";

            var result = dialog.ShowDialog();
            if ((bool)result)
            {
                try
                {
                    using (var stream = dialog.OpenFile())
                    {
                        var workbook = GenerateWorkbook(pivot);

                      //  IWorkbookFormatProvider formatProvider = new CsvFormatProvider();
                        //formatProvider.Export(workbook, stream);
                        XlsxFormatProvider provider = new XlsxFormatProvider();
                        provider.Export(workbook, stream);
                    }
                }
                catch (IOException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
          
        }
示例#27
0
 public static string FileNameFromSaveFileDialog(string fileFilter)
 {
     var saveFileDialog = new SaveFileDialog();
     saveFileDialog.Filter = fileFilter;
     var dialogResult = saveFileDialog.ShowDialog();
     return dialogResult.Value == true ? saveFileDialog.FileName : string.Empty;
 }
示例#28
0
 /// <summary>
 /// Invoked when the window is initialized.
 /// </summary>
 /// <param name="e">Empty EventArgs instance.</param>
 protected override void OnInitialized(EventArgs e)
 {
     this.importDialog = (OpenFileDialog)this.Resources["importDialog"];
     this.saveDialog = (SaveFileDialog)this.Resources["saveDialog"];
     this.imageList.ItemsSource = this.currentIcon.Images;
     base.OnInitialized(e);
 }
示例#29
0
文件: PDFExport.cs 项目: ORRNY66/GS
        public string CreatePDFFile(Stone stone)
        {
            string filename = stone.FullFilePath+".pdf";

            Document document = this.CreateDocument();

            DefineStyles();
            PlaceImage(stone);

            PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(true);

            // Set the MigraDoc document
            pdfRenderer.Document = document;

            // Create the PDF document
            pdfRenderer.RenderDocument();

            SaveFileDialog savedlg = new SaveFileDialog();
            savedlg.DefaultExt = ".pdf";

               // Save the PDF document...
            if (savedlg.ShowDialog() == true)
            {
                filename = savedlg.FileName;
                pdfRenderer.Save(filename);
                Process.Start(filename);
                return filename;
            }
            else
            {
                return "";
            }

                    // ...and start a viewer.
        }
示例#30
0
        private void Trajet_Export_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

            dlg.DefaultExt = ".csv";
            dlg.Filter     = "CSV Files (*.csv)|*.csv";

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

            if (result == true)
            {
                string filename = dlg.FileName;

                StreamWriter sw = new StreamWriter(filename, false);

                foreach (CartoObj o in userData.Liste)
                {
                    if (o is POI)
                    {
                        POI poi = o as POI;
                        sw.WriteLine(poi.Y + ";" + poi.X + ";" + poi.Description + ";");
                    }

                    if (o is Polyline)
                    {
                        Polyline line = o as Polyline;

                        foreach (Coordonnees coord in line.GetCoordonnees())
                        {
                            sw.WriteLine(coord.Y + ";" + coord.X + ";");
                        }
                    }
                }
                sw.Close();
            }
        }
示例#31
0
 public static bool SaveProjectToFile(bool InNewFile)
 {
     try
     {
         win32.SaveFileDialog saveFileDialog = new win32.SaveFileDialog();
         saveFileDialog.Filter = "XML file (*.xml)|*.xml";
         if (FilePath == "" || FilePath == null || InNewFile)
         {
             if (saveFileDialog.ShowDialog() == true)
             {
                 FilePath = saveFileDialog.FileName;
             }
             else
             {
                 return(false);
             }
         }
         XmlTextWriter textWritter = new XmlTextWriter(FilePath, Encoding.UTF8);
         textWritter.WriteStartDocument();
         textWritter.WriteStartElement("Project");
         textWritter.Close();
         XmlDocument xmlDocument = new XmlDocument();
         xmlDocument.Load(FilePath);
         XmlElement xmlRoot = xmlDocument.DocumentElement;
         XmlElement xmlSite = BuildingSite.SaveToXMLNode(xmlDocument);
         xmlRoot.AppendChild(xmlSite);
         xmlDocument.Save(FilePath);
         IsDataChanged = false;
         return(true);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Ошибка сохранения: " + ex.Message);
         return(false);
     }
 }
示例#32
0
        private void exButton_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog saveThing = new Microsoft.Win32.SaveFileDialog();

            if (saveThing.ShowDialog() == true)
            {
                int total2 = 0;

                var spriteSheetImage = BitmapFactory.New(1024, 1024);

                for (int i = 0; i < images.Count; i++)
                {
                    spriteSheetImage.Blit(new Rect(total2, 0, images[i].images2.Width, images[i].images2.Height),
                                          new WriteableBitmap(images[i].images2),
                                          new Rect(0, 0, images[i].images2.Width, images[i].images2.Height));

                    total2 += (int)images[i].images2.Width;
                }

                var frame = BitmapFrame.Create(spriteSheetImage);

                PngBitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(frame);

                try
                {
                    System.IO.FileStream SaveFile = new System.IO.FileStream(saveThing.FileName, System.IO.FileMode.Create);
                    encoder.Save(SaveFile);
                    SaveFile.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
        }
示例#33
0
        /// <summary>
        /// Browse button pressed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // Create a "Save As" dialog for selecting a directory (HACK)
            var dialog = new Microsoft.Win32.SaveFileDialog();

            dialog.InitialDirectory = txtName.Text;                 // Use current value for initial dir
            dialog.Title            = "Select a Directory";         // instead of default "Save As"
            dialog.Filter           = "Directory|*.this.directory"; // Prevents displaying files
            dialog.FileName         = "select";                     // Filename will then be "select.this.directory"
            if (dialog.ShowDialog() == true)
            {
                string path = dialog.FileName;
                // Remove fake filename from resulting path
                path = path.Replace("\\select.this.directory", "");
                path = path.Replace(".this.directory", "");
                // If user has changed the filename, create the new directory
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                // Our final value is in path
                txtName.Text = path;
            }
        }
示例#34
0
        }// end:CloseXrML
        #endregion File|Rights...

        #region File|Publish...
        // ---------------------------- OnPublish -----------------------------
        /// <summary>
        ///   Handles the File|Publish... menu selection to
        ///   write a digital rights encrypted document package.</summary>
        private void OnPublish(object sender, EventArgs e)
        {
            // Create a "File Save" dialog positioned to the
            // "Content\" folder to write the encrypted content file to.
            WinForms.SaveFileDialog dialog = new WinForms.SaveFileDialog();
            dialog.InitialDirectory = GetContentFolder();
            dialog.Title  = "Publish Rights Managed Content As";
            dialog.Filter = "Rights Managed content (*.protected)|*.protected";

            // Create a new content ".protected" file extension.
            dialog.FileName = _contentFilepath.Insert(
                                _contentFilepath.Length, ".protected" );

            // Show the "Save As" dialog. If the user clicks "Cancel", return.
            if (dialog.ShowDialog() != true)  return;

            // Extract the filename without path.
            _rmContentFilepath = dialog.FileName;
            _rmContentFilename = FilenameOnly(_rmContentFilepath);

            WriteStatus("Publishing '" + _rmContentFilename + "'.");
            PublishRMContent(_contentFilepath, _xrmlFilepath, dialog.FileName);

        }// end:OnPublish()
        /*! --FUNCTION HADER COMMENT--
         *	Function Name	:	Save
         *	Parameters		:   NONE
         *	Description		:   this function is used to save the current file in which user was typing and this function will open a save file dialog box and ask user that where they want to store this file
         *	Return Value	:   None
         */
        private void Save()
        {
            // Configure dialog box
            Microsoft.Win32.SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName   = currentFileName;               // Default file name
            dlg.DefaultExt = ".txt";                        // Default file extension
            dlg.Filter     = "Text documents (.txt)|*.txt"; // Filter files by extension

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

            // Process open file dialog box results
            if (result == true)
            {
                // Save document
                currentFilePath = dlg.FileName;
                using (TextWriter tr = new StreamWriter(currentFilePath))
                {
                    tr.Write(TextArea.Text);
                }
                UpdateWindowInfo();
                UpdateCharacterCounter();
            }
        }
示例#36
0
        private bool saveShoppingListToFile()
        {
            SaveFileDialog saveDialog = new Microsoft.Win32.SaveFileDialog();

            saveDialog.FileName   = "Lista zakupów";
            saveDialog.DefaultExt = ".txt";
            saveDialog.Filter     = "Text documents (.txt)|*.txt";

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

            if (result == true)
            {
                string textContent = Utils.shoppingListToString(shoppingList.Items, priceSum);
                Stream fileStream  = saveDialog.OpenFile();

                StreamWriter writer = new StreamWriter(fileStream);
                writer.Write(textContent);
                writer.Close();

                return(true);
            }

            return(false);
        }
示例#37
0
 private void explorerButton_Click(object sender, RoutedEventArgs e)
 {
     if (comboBox.SelectedIndex == 0)
     {
         FolderBrowserDialog folderBrowseDialog = new FolderBrowserDialog();
         DialogResult        result             = folderBrowseDialog.ShowDialog();
         if (result == System.Windows.Forms.DialogResult.OK)
         {
             filePathTextBox.Text = folderBrowseDialog.SelectedPath;
         }
     }
     else
     {
         Microsoft.Win32.SaveFileDialog saveDileDialog = new Microsoft.Win32.SaveFileDialog();
         saveDileDialog.FileName   = infoType[comboBox.SelectedIndex - 1];
         saveDileDialog.DefaultExt = ".xls";
         saveDileDialog.Filter     = "Excel File|*.xls";
         Nullable <bool> result = saveDileDialog.ShowDialog();
         if (result == true)
         {
             filePathTextBox.Text = saveDileDialog.FileName;
         }
     }
 }
示例#38
0
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlgSave = new Microsoft.Win32.SaveFileDialog();
            dlgSave.FileName   = "MultitoolPaintImage";    // Имя файла по умолчанию
            dlgSave.DefaultExt = ".jpg";                   // Формат файса по умолчанию
            dlgSave.Filter     = "Image (.jpg)|*.jpg";     // Фильтр доступных расширений

            Nullable <bool> result = dlgSave.ShowDialog(); // Вывод окна сохранения на экран

            if (result == true)
            {
                // Save document
                string filename = dlgSave.FileName;// Сохранение файла
                //Получаем размеры элемента InkCanvas
                int margin = (int)this.PaintCanvas.Margin.Left;
                int width  = (int)this.PaintCanvas.Width - margin;
                int height = (int)this.PaintCanvas.Height - margin;
                //Переводим содержимое InkCanvas в растровое изображение
                RenderTargetBitmap rtb           = new RenderTargetBitmap(width, height, 96d, 96d, PixelFormats.Default);
                DrawingVisual      drawingVisual = new DrawingVisual();
                using (DrawingContext drawingContext = drawingVisual.RenderOpen())
                {
                    VisualBrush visualBrush = new VisualBrush(PaintCanvas);
                    drawingContext.DrawRectangle(visualBrush, null,
                                                 new Rect(new Point(0, 0), new Size(width, height)));
                }
                rtb.Render(drawingVisual);
                //Сохраняем изображение
                using (FileStream savestream = new FileStream(filename, FileMode.Create))
                {
                    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(rtb));
                    encoder.Save(savestream);
                }
            }
        }
示例#39
0
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

            dlg.DefaultExt = ".xml";
            dlg.Filter     = "XML Files (*.xml)|*.xml";
            bool?result = dlg.ShowDialog();

            if (result.HasValue && result.Value)
            {
                string filetype = System.IO.Path.GetExtension(dlg.FileName);
                if (filetype != ".xml")
                {
                    MessageBox.Show("Error!", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection <productInfo>));
                using (StreamWriter wr = new StreamWriter(dlg.FileName))
                {
                    xs.Serialize(wr, productNames);
                }
            }
        }
示例#40
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (this.reportWord.IsChecked == true)
            {
                sfd        = new Microsoft.Win32.SaveFileDialog();
                sfd.Filter = "Word文件(*.doc)|*.doc";
                sfd.ShowDialog();

                this.pathText.Text = sfd.FileName;
            }
            else if (this.reportExcel.IsChecked == true)
            {
                sfd        = new Microsoft.Win32.SaveFileDialog();
                sfd.Filter = "Excel文件(*.xls)|*.xls";
                sfd.ShowDialog();
                this.pathText.Text = sfd.FileName;
            }
            else if (this.reportPdf.IsChecked == true)
            {
                sfd        = new Microsoft.Win32.SaveFileDialog();
                sfd.Filter = "PDF文件(*.pdf)|*.pdf";
                sfd.ShowDialog();
                this.pathText.Text = sfd.FileName;
            }
            else if (this.reportHtml.IsChecked == true)
            {
                sfd        = new Microsoft.Win32.SaveFileDialog();
                sfd.Filter = "Html文件(*.Html)|*.Html";
                sfd.ShowDialog();
                this.pathText.Text = sfd.FileName;
            }
            else
            {
                JXMessageBox.Show(this, "请选择导出文件格式!", MsgImage.Error);
            }
        }
示例#41
0
 private void MenuItem_Click_SaveAs(object sender, RoutedEventArgs e)
 {
     Microsoft.Win32.SaveFileDialog save = new Microsoft.Win32.SaveFileDialog();
     save.Filter = "RTF files (*.rtf)|*.rtf|All Files (*.*)|*.*";
     if (save.ShowDialog() == true)
     {
         TextRange doc = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
         using (FileStream fs = File.Create(save.FileName))
         {
             if (System.IO.Path.GetExtension(save.FileName).ToLower() == ".rtf")
             {
                 doc.Save(fs, System.Windows.DataFormats.Rtf);
             }
             else if (System.IO.Path.GetExtension(save.FileName).ToLower() == ".txt")
             {
                 doc.Save(fs, System.Windows.DataFormats.Text);
             }
             else
             {
                 doc.Save(fs, System.Windows.DataFormats.Xaml);
             }
         }
     }
 }
示例#42
0
        private void MyExportDataGrid(DataGrid dg)
        {
            if (dg.HasItems)//判断datagrid中是否有数据
            {
                try
                {
                    string strPath = Environment.CurrentDirectory;
                    Microsoft.Win32.SaveFileDialog dialogOpenFile = new Microsoft.Win32.SaveFileDialog();
                    dialogOpenFile.DefaultExt      = "csv"; //默认扩展名
                    dialogOpenFile.AddExtension    = true;  //是否自动添加扩展名
                    dialogOpenFile.Filter          = "*.csv|.csv";
                    dialogOpenFile.OverwritePrompt = true;  //文件已存在是否提示覆盖
                    dialogOpenFile.FileName        = "文件名"; //默认文件名
                    dialogOpenFile.CheckPathExists = true;  //提示输入的文件名无效
                    dialogOpenFile.Title           = "对话框标题";
                    //显示对话框
                    bool?b = dialogOpenFile.ShowDialog();
                    if (b == true)//点击保存
                    {
                        using (Stream stream = dialogOpenFile.OpenFile())
                        {
                            string c = "";
                            //DataTable dt = (DataTable)dg.DataContext;
                            DataTable dt = ((DataView)dg.ItemsSource).Table;
                            for (int k = 0; k < dt.Columns.Count; k++)
                            {
                                string strcolumns;
                                switch (dt.Columns[k].Caption)
                                {
                                case "CarID":
                                    strcolumns = "小车编号";
                                    break;

                                case "ExTimer":
                                    strcolumns = "报警时间";
                                    break;

                                case "ExType":
                                    strcolumns = "报警类别";
                                    break;

                                case "ExWorkLine":
                                    strcolumns = "报警生产区";
                                    break;

                                case "ExRouteNum":
                                    strcolumns = "报警路线";
                                    break;

                                case "ExMarkNum":
                                    strcolumns = "报警地标";
                                    break;

                                default:
                                    strcolumns = dt.Columns[k].Caption;
                                    break;
                                }
                                c += strcolumns + ",";
                            }
                            c = c.Substring(0, c.Length - 1) + "\r\n";
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                for (int j = 0; j < dt.Columns.Count; j++)
                                {
                                    c += dt.Rows[i][j].ToString() + ",";
                                }
                                c = c.Substring(0, c.Length - 1) + "\r\n";
                            }
                            Byte[] fileContent = System.Text.Encoding.GetEncoding("gb2312").GetBytes(c);
                            stream.Write(fileContent, 0, fileContent.Length);
                            stream.Close();
                        }
                    }
                    //恢复系统路径-涉及不到的可以去掉
                    Environment.CurrentDirectory = strPath;
                }
                catch (Exception msg)
                {
                    MessageBox.Show(msg.ToString());
                }
                finally
                { MessageBox.Show("导出成功!", "系统提示"); }
            }
            else
            {
                MessageBox.Show("没有可以输出的数据!", "系统提示");
            }
        }
示例#43
0
        private void SaveImageFromTabs(IEnumerable <DisplayTab> tabs)
        {
            foreach (var dt in tabs)
            {
                if (dt.xDim != 0 || dt.yDim != 0)
                {
                    if (dt.Tab.IsSelected == true)
                    {
                        // File saving dialog
                        var saveDialog = new Microsoft.Win32.SaveFileDialog
                        {
                            Title      = "Save Output Image",
                            DefaultExt = ".tiff",
                            Filter     = "TIFF (*.tiff)|*.tiff|PNG (*.png)|*.png|JPEG (*.jpeg)|*.jpeg"
                        };

                        var result   = saveDialog.ShowDialog();
                        var filename = saveDialog.FileName;

                        if (result == false)
                        {
                            return;
                        }

                        if (filename.EndsWith(".tiff"))
                        {
                            using (var output = Tiff.Open(filename, "w"))
                            {
                                output.SetField(TiffTag.IMAGEWIDTH, dt.xDim);
                                output.SetField(TiffTag.IMAGELENGTH, dt.yDim);
                                output.SetField(TiffTag.SAMPLESPERPIXEL, 1);
                                output.SetField(TiffTag.SAMPLEFORMAT, 3);
                                output.SetField(TiffTag.BITSPERSAMPLE, 32);
                                output.SetField(TiffTag.ORIENTATION, BitMiracle.LibTiff.Classic.Orientation.TOPLEFT);
                                output.SetField(TiffTag.ROWSPERSTRIP, dt.yDim);
                                output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                                output.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISBLACK);
                                output.SetField(TiffTag.COMPRESSION, Compression.NONE);
                                output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB);

                                for (var i = 0; i < dt.yDim; ++i)
                                {
                                    var buf  = new float[dt.xDim];
                                    var buf2 = new byte[4 * dt.xDim];

                                    for (var j = 0; j < dt.yDim; ++j)
                                    {
                                        buf[j] = dt.ImageData[j + dt.xDim * i];
                                    }

                                    Buffer.BlockCopy(buf, 0, buf2, 0, buf2.Length);
                                    output.WriteScanline(buf2, i);
                                }
                            }
                        }
                        else if (filename.EndsWith(".png"))
                        {
                            using (var stream = new FileStream(filename, FileMode.Create))
                            {
                                var encoder = new PngBitmapEncoder();
                                encoder.Frames.Add(BitmapFrame.Create(dt.ImgBmp.Clone()));
                                encoder.Save(stream);
                                stream.Close();
                            }
                        }
                        else if (filename.EndsWith(".jpeg"))
                        {
                            using (var stream = new FileStream(filename, FileMode.Create))
                            {
                                var encoder = new JpegBitmapEncoder();
                                encoder.Frames.Add(BitmapFrame.Create(dt.ImgBmp.Clone()));
                                encoder.Save(stream);
                                stream.Close();
                            }
                        }
                    }
                }
            }
        }
示例#44
0
        private void SaveProject(object o)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog
            {
                FileName   = "Nart_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".nart",
                DefaultExt = ".nart",
                Filter     = "Nart Project Files (.nart)|*.nart"
            };
            bool?result = dlg.ShowDialog();

            if (result == true)
            {
                Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
                // 建立暫存目錄
                string fullFilePath = dlg.FileName;//完整路徑+副檔名
                if (File.Exists(fullFilePath))
                {
                    System.IO.File.Delete(fullFilePath);
                }

                string projectName   = System.IO.Path.GetFileNameWithoutExtension(fullFilePath); //檔名不包含副檔名
                string filePath      = System.IO.Path.GetDirectoryName(fullFilePath);            //路徑
                string tempDirectory = System.IO.Path.Combine(filePath, projectName);            //路徑+檔名(不包含副檔名)

                if (File.Exists(filePath))
                {
                    System.IO.Directory.Delete(filePath);
                }

                //先創建一個資料夾
                if (System.IO.Directory.Exists(tempDirectory) == true)
                {
                    System.IO.Directory.Delete(tempDirectory);
                }
                else
                {
                    System.IO.Directory.CreateDirectory(tempDirectory);
                }

                // 專案檔輸出
                string xmlFilePah = System.IO.Path.Combine(tempDirectory, projectName) + ".xml";

                using (FileStream myFileStream = new FileStream(xmlFilePah, FileMode.Create))
                {
                    SoapFormatter soapFormatter = new SoapFormatter();
                    soapFormatter.Serialize(myFileStream, MainViewModel.ProjData);
                    myFileStream.Close();
                }

                foreach (BoneModel boneModel in MainViewModel.ProjData.BoneCollection)
                {
                    boneModel.SaveModel(tempDirectory, false);
                    if (!boneModel.ModelType.Equals(ModelType.Head))
                    {
                        boneModel.SaveModel(tempDirectory, true);
                    }
                }

                SaveTransformMatrix(tempDirectory);



                ZipFile.CreateFromDirectory(tempDirectory, fullFilePath);
                System.IO.Directory.Delete(tempDirectory, true);
                Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
            }
        }
    void UpdateTransaction(bool loadNonce)
    {
        m_paragraphTransaction.Inlines.Clear();

        // Password / Private key
        BigInteger privateKey;

        if (EllipticCurve.HexToPrivateKey(m_passwordBoxPP.Password, out privateKey))
        {
            m_passwordBoxPP.Background = Brushes.LightSkyBlue;
        }
        else
        {
            m_passwordBoxPP.Background = Brushes.White;

            if (Password.GetKeySpace(m_passwordBoxPP.Password) < BigInteger.Pow(2, m_passwordStrengthBit))
            {
                return;
            }

            privateKey = Password.PasswordToPrivateKey(m_passwordBoxPP.Password);
        }

        BigInteger publicKeyX;
        BigInteger publicKeyY;

        BouncyCastle.ECPrivateKeyToPublicKey(privateKey, out publicKeyX, out publicKeyY);

        byte[] publicKey = EllipticCurve.PublicKeyToBytes(publicKeyX, publicKeyY);
        byte[] address   = ETHAddress.PublicKeyToETHAddress(publicKey);

        PrintAddressAndBlockExplorer("From", address);

        // Nonce
        if (loadNonce)
        {
            string text = "";
            if (m_dAddressNonce.ContainsKey(Encode.BytesToHex(address)))
            {
                text = m_dAddressNonce[Encode.BytesToHex(address)];
            }

            Dispatcher.BeginInvoke(new Action(() => m_comboBoxNonce.Text = text));
        }

        if (!BigInteger.TryParse(m_comboBoxNonce.Text, out m_tx.m_nonce))
        {
            m_paragraphTransaction.Inlines.Add("Nonce: <Invalid>\n"); return;
        }
        if (m_tx.m_nonce < 0)
        {
            m_paragraphTransaction.Inlines.Add("Nonce: <Invalid>\n"); return;
        }

        m_paragraphTransaction.Inlines.Add("Nonce: " + m_tx.m_nonce + "\n");

        // To
        string to    = m_comboBoxTo.Text.Trim();
        int    index = to.IndexOf(" ");

        if (index != -1)
        {
            to = to.Substring(0, index);
        }
        m_tx.m_to = Encode.HexToBytes(to);

        if (m_tx.m_to == null)
        {
            m_paragraphTransaction.Inlines.Add("To: <Invalid>\n");       return;
        }
        else if (m_tx.m_to.Length == 0)
        {
            m_paragraphTransaction.Inlines.Add("To: Empty\n");
        }
        else if (m_tx.m_to.Length == 20)
        {
            PrintAddressAndBlockExplorer("To", m_tx.m_to);
        }
        else
        {
            m_paragraphTransaction.Inlines.Add("To: <Invalid>\n");       return;
        }

        // Value
        if (Encode.DecimalToBigInteger(m_comboBoxValue.Text, 18, out m_tx.m_value))
        {
            m_paragraphTransaction.Inlines.Add("Value: " + Encode.BigIntegerToDecimal(m_tx.m_value, 18) + " " + GetCurrency() + "\n");
        }
        else
        {
            m_paragraphTransaction.Inlines.Add("Value: <Invalid>\n");
            return;
        }

        // Init / Data
        if (m_tx.m_initOrData.Length > 0)
        {
            m_paragraphTransaction.Inlines.Add("Init / Data: " + m_tx.m_initOrData.Length + " bytes\n");
        }

        // Gas price
        if (!Encode.DecimalToBigInteger(m_comboBoxGasPrice.Text, 18, out m_tx.m_gasPrice))
        {
            m_paragraphTransaction.Inlines.Add("Gas price: <Invalid>\n");
            return;
        }

//		m_paragraphTransaction.Inlines.Add("Gas price: " + Encode.BigIntegerToDecimal(m_tx.m_gasPrice, 18) + " " + GetCurrency() + "\n");

        // Gas limit
        if (!BigInteger.TryParse(m_comboBoxGasLimit.Text, out m_tx.m_gasLimit))
        {
            m_paragraphTransaction.Inlines.Add("Gas limit: <Invalid>\n");   return;
        }
        if (m_tx.m_gasLimit < 0)
        {
            m_paragraphTransaction.Inlines.Add("Gas limit: <Invalid>\n");   return;
        }

//		m_paragraphTransaction.Inlines.Add("Gas limit: " + m_tx.m_gasLimit + "\n");

        BigInteger gasLimitMin = m_tx.GetGasLimitMin();

        if (m_tx.m_gasLimit < gasLimitMin)
        {
            m_paragraphTransaction.Inlines.Add(new Run("Minimal gas limit is " + gasLimitMin + ".\n")
            {
                Foreground = Brushes.Red
            });
        }

        // calculation
        m_paragraphTransaction.Inlines.Add(new Run("Fee: " + Encode.BigIntegerToDecimal(m_tx.m_gasPrice * m_tx.m_gasLimit, 18) + " " + GetCurrency() + "\n")
        {
            ToolTip = "Fee = Gas price * Gas limit"
        });
        m_paragraphTransaction.Inlines.Add(new Run("Value + Fee: " + Encode.BigIntegerToDecimal(m_tx.m_value + m_tx.m_gasPrice * m_tx.m_gasLimit, 18) + " " + GetCurrency() + "\n")
        {
            ToolTip = "Fee = Gas price * Gas limit"
        });

        // additional check
        if (m_tx.m_to.Length == 0 && m_tx.m_initOrData.Length == 0)
        {
            return;
        }

        // tx
        m_tx.ECDsaSign(GetCurrency(), privateKey);
        byte[] tx   = m_tx.EncodeRLP();
        byte[] hash = BouncyCastle.Keccak(tx);

        // button
        foreach (string node in m_lNode)
        {
            Button buttonSend = new Button()
            {
                Margin = new Thickness(2), Content = "Send to " + node, ToolTip = "Send raw transaction to " + node
            };
            buttonSend.Click += (sender, e) =>
            {
                // save
                string file = GetCurrency() + "_tx_" + DateTime.Now.ToString("yyMMdd_HHmmss") + "_0x" + Encode.BytesToHex(hash);
                File.WriteAllBytes(file, tx);

                // nonce read
                m_dAddressNonce.Clear();

                foreach (var entry in ConfigFile.ReadAddressInfo(GetCurrency() + "_nonce"))
                {
                    m_dAddressNonce[entry.Item1] = entry.Item2;
                }

                // nonce update
                m_dAddressNonce[Encode.BytesToHex(address)] = m_tx.m_nonce.ToString();

                // nonce write
                List <string> lLine = new List <string>();
                foreach (var entry in m_dAddressNonce)
                {
                    lLine.Add("0x" + entry.Key + " " + entry.Value);
                }
                File.WriteAllLines(GetCurrency() + "_nonce", lLine);

                // send
                System.Diagnostics.Process.Start("send_transaction.exe", file + " " + node + " -pause");
            };
            m_paragraphTransaction.Inlines.Add(buttonSend);
        }

        Button buttonCopy = new Button()
        {
            Margin = new Thickness(2), Content = "Copy", ToolTip = "Copy raw transaction to clipboard"
        };
        Button buttonSave = new Button()
        {
            Margin = new Thickness(2), Content = "Save", ToolTip = "Save raw transaction to file"
        };

        buttonCopy.Click += (sender, e) => Clipboard.SetText(Encode.BytesToHex(tx));
        buttonSave.Click += (sender, e) =>
        {
            var dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName = GetCurrency() + "_tx_0x" + Encode.BytesToHex(hash);
            if (dlg.ShowDialog() == true)
            {
                File.WriteAllBytes(dlg.FileName, tx);
            }
        };

        m_paragraphTransaction.Inlines.Add(buttonCopy);
        m_paragraphTransaction.Inlines.Add(buttonSave);
    }
示例#46
0
    /// <summary>
    /// Call the cmd line tool. The sample just use -i that goes on the file extensions.
    /// Use the conversion_parameters for more advanced conversions.
    /// </summary>
    public void Concat(string out_file, string conversion_parameters)
    {
        string tool_path     = GetFFMPEGPath();
        string tmp_file_path = System.IO.Path.GetTempFileName();

        m_FilesToDelete.Add(tmp_file_path);

        var stream_writer = System.IO.File.CreateText(tmp_file_path);

        if (stream_writer == null)
        {
            System.Windows.MessageBox.Show(tool_path, "Failed to write temporary text file");
            return;
        }

        ISelection selection    = m_scripting.GetSelection();
        IUtilities utilities    = m_scripting.GetUtilities();
        var        catalog      = m_scripting.GetVideoCatalogService();
        string     extension    = null;
        string     video_format = null;
        string     video_width  = null;
        string     video_height = null;
        string     audio_format = null;
        var        playlist     = selection.GetSelectedPlaylist();

        int[] all_clip_ids = catalog.GetPlaylistClipIDs(playlist.ID);

        int  part = 1;
        bool can_do_pure_concat = true;

        foreach (int clip_id in all_clip_ids)
        {
            var    clip        = catalog.GetVideoClip(clip_id);
            var    video_entry = catalog.GetVideoFileEntry(clip.VideoFileID);
            string video_path  = utilities.ConvertToLocalPath(video_entry.FilePath);

            var extended = catalog.GetVideoFileExtendedProperty((int)clip.VideoFileID);
            foreach (var prop in extended)
            {
                if (prop.Property == "video_Format")
                {
                    if (video_format == null)
                    {
                        video_format = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Video format is " + video_format);
                    }
                    else if (video_format != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same video format.\n'";
                        msg += video_path + "' is in " + prop.Value + "\n";
                        msg += " previous was in " + video_format + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
                else if (prop.Property == "video_Width")
                {
                    if (video_width == null)
                    {
                        video_width = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Video width is " + video_width);
                    }
                    else if (video_width != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same dimension.\n'";
                        msg += video_path + "' width is " + prop.Value + "\n";
                        msg += " previous was in " + video_width + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
                if (prop.Property == "video_Height")
                {
                    if (video_height == null)
                    {
                        video_height = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Video height is " + video_height);
                    }
                    else if (video_height != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same dimension.\n'";
                        msg += video_path + "' height is " + prop.Value + "\n";
                        msg += " previous was in " + video_height + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
                if (prop.Property == "audio_Format")
                {
                    if (audio_format == null)
                    {
                        audio_format = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Audio format is " + audio_format);
                    }
                    else if (audio_format != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same audio format.\n";
                        msg += video_path + "is in " + prop.Value + "\n";
                        msg += " previous was in " + audio_format + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
            }

            if (extension == null)
            {
                int extension_start = video_path.LastIndexOf(".");
                extension = video_path.Substring(extension_start);
            }

            if (can_do_pure_concat)
            {
                string out_path = GetTempFolder() + "clip_" + part + extension;
                part = part + 1;
                SaveClip(video_path, clip.StartTime, clip.EndTime, out_path);

                stream_writer.Write("file '" + out_path + "'");
                stream_writer.WriteLine();
            }
            else
            {
                selection.SetSelectedPlaylistClip(clip_id); // select the offending clip
                // if we can not do a pure concat we abort here. To continue we would need to re-encode the file and that
                // takes a bit more care and user intervention
                return;
            }
        }
        stream_writer.Close();

        if (out_file == null)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName   = "concat" + extension;
            dlg.DefaultExt = extension;
            dlg.Filter     = "All files|*.*";
            Nullable <bool> result = dlg.ShowDialog();
            if (result == false)
            {
                return;
            }
            out_file = dlg.FileName;
        }

        RunFFMPEG("-f concat - safe 0 - i " + tmp_file_path + conversion_parameters + " - c copy \"" + out_file + "\"");

        PlayVideo(out_file);
    }
示例#47
0
文件: concat_videos.cs 项目: Rp70/fvc
    /// <summary>
    /// Call the cmd line tool. The sample just use -i that goes on the file extensions.
    /// Use the conversion_parameters for more advanced conversions.
    /// </summary>
    private void Concat(string out_file, string conversion_parameters)
    {
        string tool_path     = GetFFMPEGPath();
        string tmp_file_path = System.IO.Path.GetTempFileName();

        var stream_writer = System.IO.File.CreateText(tmp_file_path);

        if (stream_writer == null)
        {
            System.Windows.MessageBox.Show(tool_path, "Failed to write temporary text file");
            return;
        }

        ISelection  selection          = m_scripting.GetSelection();
        IUtilities  utilities          = m_scripting.GetUtilities();
        var         catalog            = m_scripting.GetVideoCatalogService();
        string      extension          = null;
        string      video_format       = null;
        string      video_width        = null;
        string      video_height       = null;
        string      audio_format       = null;
        List <long> selected           = selection.GetSelectedVideos();
        bool        can_do_pure_concat = true;

        foreach (long video_id in selected)
        {
            var    entry      = catalog.GetVideoFileEntry(video_id);
            string video_path = utilities.ConvertToLocalPath(entry.FilePath);

            var extended = catalog.GetVideoFileExtendedProperty((int)video_id);
            foreach (var prop in extended)
            {
                if (prop.Property == "video_Format")
                {
                    if (video_format == null)
                    {
                        video_format = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Video format is " + video_format);
                    }
                    else if (video_format != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same video format.\n'";
                        msg += video_path + "' is in " + prop.Value + "\n";
                        msg += " previous was in " + video_format + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
                else if (prop.Property == "video_Width")
                {
                    if (video_width == null)
                    {
                        video_width = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Video width is " + video_width);
                    }
                    else if (video_width != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same dimension.\n'";
                        msg += video_path + "' width is " + prop.Value + "\n";
                        msg += " previous was in " + video_width + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
                if (prop.Property == "video_Height")
                {
                    if (video_height == null)
                    {
                        video_height = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Video height is " + video_height);
                    }
                    else if (video_height != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same dimension.\n'";
                        msg += video_path + "' height is " + prop.Value + "\n";
                        msg += " previous was in " + video_height + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
                if (prop.Property == "audio_Format")
                {
                    if (audio_format == null)
                    {
                        audio_format = prop.Value;
                        m_scripting.GetConsole().WriteLine(video_path + " - Audio format is " + audio_format);
                    }
                    else if (audio_format != prop.Value)
                    {
                        string msg = "Aborting. All videos must be in the same audio format.\n";
                        msg += video_path + "is in " + prop.Value + "\n";
                        msg += " previous was in " + audio_format + "\n";
                        m_scripting.GetConsole().WriteLine(msg);
                        can_do_pure_concat = false;
                    }
                }
            }
            stream_writer.Write("file '" + video_path + "'");
            stream_writer.WriteLine();

            // if we can not do a pure concat we abort here. To continue we would need to re-encode the file and that
            // takes a bit more care and user intervention
            if (!can_do_pure_concat)
            {
                return;
            }
            if (extension == null)
            {
                int extension_start = video_path.LastIndexOf(".");
                extension = video_path.Substring(extension_start);
            }
        }
        stream_writer.Close();

        if (out_file == null)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName   = "concat" + extension;
            dlg.DefaultExt = extension;
            dlg.Filter     = "All files|*.*";
            Nullable <bool> result = dlg.ShowDialog();
            if (result == false)
            {
                return;
            }
            out_file = dlg.FileName;
        }

        //
        // do concatination
        //
        System.Diagnostics.Process          process   = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.FileName = "cmd.exe";
        string cmd_line = " -f concat -safe 0 -i " + tmp_file_path + conversion_parameters + " -c copy \"" + out_file + "\"";

        startInfo.Arguments = "/C " + tool_path + " " + cmd_line; // use /K instead of /C to keep the cmd window up
        process.StartInfo   = startInfo;

        m_scripting.GetConsole().WriteLine("Running " + startInfo.Arguments);

        process.Start();
        process.WaitForExit();

        File.Delete(tmp_file_path);

        //
        // Show video in shell player
        //
        System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
        {
            FileName        = out_file,
            UseShellExecute = true,
            Verb            = "open"
        });
    }
示例#48
0
        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            TargetSet tset = new TargetSet {
                file = this.favFileName, Name = this.txtTargetSetName.Text, Parameters = this.favParameters, Strapper = this.favStrapper, Targets = this.favTargets
            };

            if (this.listBoxExistingFavorites.SelectedIndex >= 0)
            {
                FavoriteFile   f            = this.listBoxExistingFavorites.SelectedItem as FavoriteFile;
                XmlSerializer  deserializer = new XmlSerializer(typeof(FavoriteEntity));
                FavoriteEntity foundFavorite;
                using (FileStream favStream = new FileStream(f.FullPath, FileMode.Open, FileAccess.Read))
                {
                    foundFavorite = (FavoriteEntity)deserializer.Deserialize(favStream);
                }

                TargetSet[] temp = new TargetSet[foundFavorite.TargetSet.Length + 1];
                int         i    = 0;
                foreach (TargetSet t in foundFavorite.TargetSet)
                {
                    temp[i] = t;
                    i++;
                }

                temp[i] = tset;
                foundFavorite.TargetSet = temp;

                XmlSerializer serializer = new XmlSerializer(typeof(FavoriteEntity));
                using (FileStream fs = new FileStream(f.FullPath, FileMode.Create))
                {
                    TextWriter writer = new StreamWriter(fs, new UTF8Encoding());
                    serializer.Serialize(writer, foundFavorite);
                }

                this.Close();
                return;
            }

            SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog {
                DefaultExt = ".msbef", Filter = "MSBuild Explorer Favorite (.msbef)|*.msbef"
            };

            if (dlg.ShowDialog() == true)
            {
                FavoriteEntity fe = new FavoriteEntity();
                fe.groupName = this.txtFavoriteGroupName.Text;
                TargetSet[] tsetcol = new TargetSet[1];
                tsetcol[0]      = tset;
                fe.TargetSet    = tsetcol;
                fe.file         = this.favFileName;
                fe.friendlyName = this.txtFavoriteName.Text;

                XmlSerializer serializer = new XmlSerializer(typeof(FavoriteEntity));
                using (FileStream fs = new FileStream(dlg.FileName, FileMode.Create))
                {
                    TextWriter writer = new StreamWriter(fs, new UTF8Encoding());
                    serializer.Serialize(writer, fe);
                }

                StringCollection favs = new StringCollection();
                foreach (string s in from string s in Settings.Default.Favorites where !favs.Contains(s) select s)
                {
                    favs.Add(s);
                }

                if (!favs.Contains(dlg.FileName))
                {
                    favs.Add(dlg.FileName);
                }

                Settings.Default.Favorites = favs;

                Settings.Default.Save();

                this.Close();
            }
        }
示例#49
0
        public void NewProject(winForms.RichTextBox htmlTextBox, winForms.RichTextBox csstextBox, MenuItem SaveProject, MainWindow mw)
        {
            if (SaveProject.IsEnabled == true)
            {
                MessageBoxResult msgBoxRes = MessageBox.Show("Do you want to save content or not?", "Save File", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (msgBoxRes == MessageBoxResult.Yes)
                {
                    Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                    sfd.DefaultExt = ".html";
                    sfd.Filter     = "HTML File (.html)|*.html";
                    if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)
                    {
                        File.WriteAllText(sfd.FileName, htmlTextBox.Text);
                        savepath = sfd.FileName.ToString();
                        save     = true;



                        //Saving auto main.css
                        int    temp       = sfd.FileName.ToString().LastIndexOf("\\");
                        String cssdestDir = sfd.FileName.Substring(0, temp) + "\\main.css";



                        //creating main.css
                        var cssFile = File.Create(cssdestDir);
                        cssFile.Close();
                        File.WriteAllText(cssdestDir, csstextBox.Text);
                        csssavepath = cssdestDir;
                        save        = true;



                        //moving images videos and bootstrap stuff
                        String destDir = sfd.FileName.Substring(0, temp) + "\\media";

                        /*if (!Directory.Exists(destDir))
                         *  {
                         *  Directory.CreateDirectory(destDir);
                         * }
                         */



                        string srcDir = winForms.Application.StartupPath + @"\dnd\media";



                        DirectoryCopy(srcDir, destDir, true);



                        //Deleting Eveything from the directory
                        System.IO.DirectoryInfo di = new DirectoryInfo(srcDir + "\\images");



                        foreach (FileInfo file in di.GetFiles())
                        {
                            file.Delete();
                        }



                        di = new DirectoryInfo(srcDir + "\\videos");



                        foreach (FileInfo file in di.GetFiles())
                        {
                            file.Delete();
                        }



                        //moving bootstrap related files
                        String bootstrapDest = sfd.FileName.Substring(0, temp) + "\\bootstrap";
                        string bootstrapSrc  = winForms.Application.StartupPath + @"\dnd\bootstrap";
                        DirectoryCopy(bootstrapSrc, bootstrapDest, true);
                    }
                }
            }

            //////////////////////////////////////////////////////
            ///Not using this because we will show startup here///
            //////////////////////////////////////////////////////

            /*//Need to use System.Windows.Forms to get open folder dialog
             * // Show the FolderBrowserDialog.
             * winForms.FolderBrowserDialog folderDialog = new winForms.FolderBrowserDialog();
             * folderDialog.SelectedPath = System.AppDomain.CurrentDomain.BaseDirectory;
             * winForms.DialogResult fdr = folderDialog.ShowDialog();
             *
             * if (fdr == winForms.DialogResult.OK)
             * {
             *  String folderPath = folderDialog.SelectedPath;
             *  String htmlfilename = "index.html";
             *  String cssfilename = "main.css";
             *  htmlpathString = System.IO.Path.Combine(folderPath, htmlfilename);
             *  csspathString = System.IO.Path.Combine(folderPath, cssfilename);
             *  if (!System.IO.File.Exists(htmlpathString))
             *  {
             *      try
             *      {
             *          using (StreamWriter writer = new StreamWriter(htmlpathString))
             *          {
             *              writer.WriteLine("<html>");
             *              writer.WriteLine("  <head>");
             *              writer.WriteLine("    <!-- Required meta tags -->");
             *              writer.WriteLine("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">");
             *              writer.WriteLine("");
             *              writer.WriteLine("    <!-- Bootstrap CSS -->");
             *              writer.WriteLine("    <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\">");
             *              writer.WriteLine("    <link rel=\"stylesheet\" href=\"main.css\">");
             *              writer.WriteLine("");
             *              writer.WriteLine("    <title>Hello, world!</title>");
             *              writer.WriteLine("  </head>");
             *              writer.WriteLine("  <body>");
             *              writer.WriteLine("    <ul class=\"nav\">");
             *              writer.WriteLine("      <li class=\"nav-item\">");
             *              writer.WriteLine("        <a class=\"nav-link active\" href=\"#\">Active</a>");
             *              writer.WriteLine("      </li>");
             *              writer.WriteLine("      <li class=\"nav-item\">");
             *              writer.WriteLine("        <a class=\"nav-link\" href=\"#\">Link</a>");
             *              writer.WriteLine("      </li>");
             *              writer.WriteLine("    </ul>");
             *              writer.WriteLine("    <h1>Hello World!</h1>");
             *              writer.WriteLine("");
             *              writer.WriteLine("    <!-- Optional JavaScript -->");
             *              writer.WriteLine("    <!-- jQuery first, then Popper.js, then Bootstrap JS -->");
             *              writer.WriteLine("    <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script>");
             *              writer.WriteLine("    <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\" integrity=\"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1\" crossorigin=\"anonymous\"></script>");
             *              writer.WriteLine("    <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM\" crossorigin=\"anonymous\"></script>");
             *              writer.WriteLine("  </body>");
             *              writer.WriteLine("</html>");
             *          }
             *          //After html success, For CSS file creation
             *          if (!System.IO.File.Exists(csspathString))
             *          {
             *              using (StreamWriter writer = new StreamWriter(csspathString))
             *              {
             *                  writer.WriteLine("body{");
             *                  writer.WriteLine("\tbackground-color:black;");
             *                  writer.WriteLine("}");
             *                  writer.WriteLine("h1{");
             *                  writer.WriteLine("\tcolor:white;");
             *                  writer.WriteLine("}");
             *              }
             *          }
             *          else
             *          {
             *              System.Windows.MessageBox.Show("Error! File already exists.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
             *              return;
             *          }
             *      }
             *      catch (Exception e)
             *      {
             *          winForms.MessageBox.Show("There seems to be some error creating a directory");
             *          return;
             *      }
             *
             *      save = true;
             *      savepath = htmlpathString;
             *      csssavepath = csspathString;
             *  }
             *  else
             *  {
             *      System.Windows.MessageBox.Show("Error! File already exists.", "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
             *      return;
             *  }
             *
             *
             *
             *
             *
             *
             *  StreamReader sr1 = new StreamReader(htmlpathString, Encoding.Default);
             *  htmlTextBox.Text = sr1.ReadToEnd();
             *
             *  StreamReader sr2 = new StreamReader(csspathString, Encoding.Default);
             *  csstextBox.Text = sr2.ReadToEnd();
             *
             *  sr1.Dispose();
             *  sr2.Dispose();
             *
             *  //stop single line grammercheck firing
             *  MainWindow.htmlfire = false;
             *  MainWindow.fire = false;
             *  //creating objects to simulate validation
             *  htmltextBoxClass htb = new htmltextBoxClass();
             *  csstextBoxClass ctb = new csstextBoxClass();
             *
             *
             *  //Overriding Paste Functionality
             *  //Showing busy work with mouse
             *  Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
             *  try
             *  {
             *      htb.ValidateTags(htmlTextBox);
             *      ctb.clipboardGrammerCheck(csstextBox);
             *
             *  }
             *  finally
             *  {
             *      Mouse.OverrideCursor = null;
             *  }
             *  MainWindow.htmlfire = true;
             *  MainWindow.fire = true;
             *
             * }*/

            startup su = new startup();

            su.Show();
            MainWindow.newProjectcheck = true;
            mw.Close();
            SaveProject.IsEnabled = false;
        }
示例#50
0
        public int SaveProject(winForms.RichTextBox htmlTextBox, winForms.RichTextBox csstextBox)
        {
            int check = 0;

            if (save == false)
            {
                Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();

                sfd.DefaultExt = ".html";
                sfd.Filter     = "HTML File (.html)|*.html";
                if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)
                {
                    File.WriteAllText(sfd.FileName, htmlTextBox.Text);
                    savepath = sfd.FileName.ToString();
                    save     = true;
                    check    = 1;

                    //Saving auto main.css
                    int    temp       = sfd.FileName.ToString().LastIndexOf("\\");
                    String cssdestDir = sfd.FileName.Substring(0, temp) + "\\main.css";



                    //creating main.css
                    var cssFile = File.Create(cssdestDir);
                    cssFile.Close();
                    File.WriteAllText(cssdestDir, csstextBox.Text);
                    csssavepath = cssdestDir;
                    //winForms.MessageBox.Show(csssavepath);
                    save = true;



                    //moving images videos and bootstrap stuff
                    String destDir = sfd.FileName.Substring(0, temp) + "\\media";

                    /*if (!Directory.Exists(destDir))
                     *  {
                     *  Directory.CreateDirectory(destDir);
                     * }
                     */



                    string srcDir = winForms.Application.StartupPath + @"\dnd\media";



                    DirectoryCopy(srcDir, destDir, true);



                    //Deleting Eveything from the directory
                    System.IO.DirectoryInfo di = new DirectoryInfo(srcDir + "\\images");



                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }



                    di = new DirectoryInfo(srcDir + "\\videos");



                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }



                    //moving bootstrap related files
                    String bootstrapDest = sfd.FileName.Substring(0, temp) + "\\bootstrap";
                    string bootstrapSrc  = winForms.Application.StartupPath + @"\dnd\bootstrap";
                    DirectoryCopy(bootstrapSrc, bootstrapDest, true);
                }



                //sfd.DefaultExt = ".css";
                //sfd.Filter = "CSS File (.css)|*.css";
                //sfd.FileName = "";

                //if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)
                //{
                //    File.WriteAllText(sfd.FileName, csstextBox.Text);
                //    csssavepath = sfd.FileName.ToString();
                //    save = true;

                //    int temp = sfd.FileName.ToString().LastIndexOf("\\");
                //    String destDir = sfd.FileName.Substring(0, temp) + "\\media";
                //    /*if (!Directory.Exists(destDir))
                //    {
                //        Directory.CreateDirectory(destDir);
                //    }*/
                //    //winForms.MessageBox.Show(destDir);

                //    string srcDir = winForms.Application.StartupPath + @"\dnd\media";

                //    DirectoryCopy(srcDir, destDir, true);

                //    //Deleting Eveything from the directory
                //    System.IO.DirectoryInfo di = new DirectoryInfo(srcDir + "\\images");

                //    foreach (FileInfo file in di.GetFiles())
                //    {
                //        file.Delete();
                //    }

                //    di = new DirectoryInfo(srcDir + "\\videos");

                //    foreach (FileInfo file in di.GetFiles())
                //    {
                //        file.Delete();
                //    }
                //}


                ///*string newpath = savepath.LastIndexOf("/");
                //Console.WriteLine(savepath + "\n" + newpath);
                ////copying media folder to dest file
                ////CloneDirectory(winForms.Application.StartupPath + @"\dnd\media\", sfd.Get);*/

                ////trying to find if there are images and moving them\
                ///
            }
            else
            {
                if (savepath != "")
                {
                    File.WriteAllText(savepath, htmlTextBox.Text);
                    check = 2;
                }
                if (csssavepath != "")
                {
                    File.WriteAllText(csssavepath, csstextBox.Text);



                    int temp = savepath.ToString().LastIndexOf("\\");



                    //moving images videos and bootstrap stuff
                    String destDir = savepath.Substring(0, temp) + "\\media";

                    /*if (!Directory.Exists(destDir))
                     *  {
                     *  Directory.CreateDirectory(destDir);
                     * }
                     */



                    string srcDir = winForms.Application.StartupPath + @"\dnd\media";



                    DirectoryCopy(srcDir, destDir, true);



                    //Deleting Eveything from the directory
                    System.IO.DirectoryInfo di = new DirectoryInfo(srcDir + "\\images");



                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }



                    di = new DirectoryInfo(srcDir + "\\videos");



                    foreach (FileInfo file in di.GetFiles())
                    {
                        file.Delete();
                    }



                    //moving bootstrap related files
                    String bootstrapDest = savepath.Substring(0, temp) + "\\bootstrap";
                    string bootstrapSrc  = winForms.Application.StartupPath + @"\dnd\bootstrap";
                    DirectoryCopy(bootstrapSrc, bootstrapDest, true);
                }
            }

            //validation
            //stop single line grammercheck firing
            MainWindow.htmlfire = false;
            MainWindow.fire     = false;
            //creating objects to simulate validation
            htmltextBoxClass htb = new htmltextBoxClass();
            csstextBoxClass  ctb = new csstextBoxClass();


            //Overriding Paste Functionality
            //Showing busy work with mouse
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            try
            {
                htb.ValidateTags(htmlTextBox);
                ctb.clipboardGrammerCheck(csstextBox);
            }
            finally
            {
                Mouse.OverrideCursor = null;
            }
            MainWindow.htmlfire = true;
            MainWindow.fire     = true;

            return(check);
        }
示例#51
0
        private void Button_Click5(object sender, RoutedEventArgs e)
        {
            List <SecurityRisk>        secRisk        = new List <SecurityRisk>();
            List <SecurityRiskToTable> secRiskToTable = new List <SecurityRiskToTable>();

            try
            {
                secRisk        = EnumerateSecurityRisk();
                secRiskToTable = EnumerateSecurityRiskToTable();
                var book  = new XLWorkbook();
                var sheet = book.Worksheets.Add("Sheet1");
                sheet.Cell(1, "A").Value = "Идентификатор угрозы";
                sheet.Cell(1, "B").Value = "Наименование угрозы";
                sheet.Cell(1, "C").Value = "Описание угрозы";
                sheet.Cell(1, "D").Value = "Источник угрозы";
                sheet.Cell(1, "E").Value = "Объект воздействия угрозы";
                sheet.Cell(1, "F").Value = "Нарушение конфиденциальности";
                sheet.Cell(1, "G").Value = "Нарушение целостности";
                sheet.Cell(1, "H").Value = "Нарушение доступности";
                for (int row = 0; row < secRisk.Count; row++)
                {
                    sheet.Cell(row + 2, "A").Value = secRisk[row].Id;
                    sheet.Cell(row + 2, "B").Value = secRisk[row].Name;
                    sheet.Cell(row + 2, "C").Value = secRisk[row].Description;
                    sheet.Cell(row + 2, "D").Value = secRisk[row].SourceOfThreat;
                    sheet.Cell(row + 2, "E").Value = secRisk[row].ObjectOfImpact;
                    sheet.Cell(row + 2, "F").Value = secRisk[row].ConfidentialityViolation;
                    sheet.Cell(row + 2, "G").Value = secRisk[row].IntegrityViolation;
                    sheet.Cell(row + 2, "H").Value = secRisk[row].AvailabilityViolation;
                }
                var table1 = sheet.Range("A1:H" + (secRisk.Count + 1));
                var sheet2 = book.Worksheets.Add("Sheet2");
                sheet2.Cell(1, "A").Value = "Идентификатор угрозы";
                sheet2.Cell(1, "B").Value = "Наименование угрозы";
                for (int row = 0; row < secRiskToTable.Count; row++)
                {
                    sheet2.Cell(row + 2, "A").Value = secRiskToTable[row].ID;
                    sheet2.Cell(row + 2, "B").Value = secRiskToTable[row].Name;
                }
                var table2 = sheet2.Range("A1:b" + (secRiskToTable.Count + 1));
                sheet.Columns().AdjustToContents();
                sheet2.Columns().AdjustToContents();
                var dialog = new Microsoft.Win32.SaveFileDialog()
                {
                    Filter           = "Книга Excel (*.xlsx)|*.xlsx",
                    InitialDirectory = @"c:\"
                };
                if (dialog.ShowDialog() == true)
                {
                    book.SaveAs(dialog.FileName);
                }
            }
            catch (Exception ex)
            {
                File.Delete(DataBase);
                Update.IsEnabled             = false;
                Create.IsEnabled             = true;
                Save.IsEnabled               = false;
                ShowAll.IsEnabled            = false;
                ShowAllInformation.IsEnabled = false;
                listOfRisks.Clear();
                listOfRisksToTable.Clear();
                System.Windows.MessageBox.Show("Ошибка: " + ex.Message);
            }
        }
        private void SaveProxyClick(object sender, RoutedEventArgs e)
        {
            string[] lines = tb_newproxy.Text.Split('\n');
            var      csv   = new StringBuilder();
            bool     f     = false;

            foreach (string line in lines)
            {
                if (line.Equals("") || line.Equals("\r"))
                {
                    break;
                }
                string[] data = line.Split(':');
                if (data.Length < 2)
                {
                    f = true;
                    break;
                }

                string ip = "", port = "", username = "", password = "", status = "1";
                int    i = 0;
                foreach (string temp in data)
                {
                    string temp1 = temp.Replace("\r", "");
                    switch (i)
                    {
                    case 0: ip = temp1; break;

                    case 1: port = temp1; break;

                    case 2: username = temp1; break;

                    case 3: password = temp1; break;

                    default: break;
                    }
                    i++;
                }
                var newLine = string.Format("{0},{1},{2},{3},{4}", ip, port, username, password, status);
                csv.AppendLine(newLine);
            }
            if (f)
            {
                MessageBox.Show("Proxy data wrong!\n Please check it", "Wrong");
            }
            else
            {
                var filename = "";
                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                // Set filter for file extension and default file extension
                dlg.DefaultExt       = ".txt";
                dlg.Filter           = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
                dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                // 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;
                    File.WriteAllText(filename, csv.ToString());
                    this.proxyCsvFilePath = filename;
                }
            }
        }
示例#53
0
        private void NewGroupBtn_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();

            // Set filter for file extension and default file extension
            dlg.DefaultExt = ".txt";
            //dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
            dlg.Filter = "INI Files (*.ini)|*.ini";

            string ch = string.Format("ch{0:d2}", m_nCh);

            string initPath = AppDomain.CurrentDomain.BaseDirectory + ch;

            dlg.InitialDirectory = initPath;

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

            // Get the selected file name and display in a TextBox
            if (result == true)
            {
                string selectedFilePathName = dlg.FileName;

                //불러온경로를 저장

                m_presetChInfoIni.presetPathName = selectedFilePathName;
                m_presetChInfoIni.WriteIni(m_nCh);


                //파일 이름만 추출
                int index1 = dlg.FileName.LastIndexOf('\\');
                int index2 = dlg.FileName.LastIndexOf('.');
                FileNameLabel.Content = dlg.FileName.Substring(index1 + 1, (index2 - 1) - index1);//불러온 파일이름을 화면에 보여준다.


                //저장

                //이미 존재 하는 파일이면 삭제
                // Delete a file by using File class static method...
                if (System.IO.File.Exists(selectedFilePathName))
                {
                    // Use a try block to catch IOExceptions, to
                    // handle the case of the file already being
                    // opened by another process.
                    try
                    {
                        System.IO.File.Delete(selectedFilePathName);
                    }
                    catch (System.IO.IOException ee)
                    {
                        Console.WriteLine(ee.Message);
                        return;
                    }
                }
                /////////////////////////////////////////////////

                //파일 만듬
                int nIndex = m_nCh - 1;
                m_arrPresetListReadWrite[nIndex].CreateNewFile(dlg.FileName);

                //리스트를 초기화 한다.
                PresetListView.ItemsSource = m_arrPresetListReadWrite[nIndex].GetPresetList();
            }
        }
示例#54
0
        private void Plane_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            PlaneVM vm = e.NewValue as PlaneVM;

            if (vm != null)
            {
                vm.DragReferenceElem = AnnoGrid.LowerGrid;
                vm.SaveImageCommand  = new DelegateCommand(() =>
                {
                    var dialog        = new Microsoft.Win32.SaveFileDialog();
                    dialog.DefaultExt = "svg";
                    dialog.Filter     = "Scalable Vector Graphics (.svg)|*.svg";
                    var res           = dialog.ShowDialog();
                    if (res.HasValue && res.Value)
                    {
                        string filepath = dialog.FileName;

                        List <Reports.SVG.ISvgRenderableColumn> columnRenderers = new List <Reports.SVG.ISvgRenderableColumn>();

                        int idx = 0;

                        List <Tuple <Reports.SVG.LegendItemKey, Reports.SVG.ILegendItem> > foundLegendItems = new List <Tuple <Reports.SVG.LegendItemKey, Reports.SVG.ILegendItem> >();

                        foreach (UIElement elem in AnnoGrid.HeadersGrid.Children)
                        {
                            var colVm = vm.AnnoGridVM.Columns[idx];
                            //gathering column SVG representation ...
                            columnRenderers.Add(Reports.SVG.ColumnPainterFactory.Create(elem, AnnoGrid.ColumnsGrid.Children[idx] as ColumnView, colVm));
                            //... and possible appearence in the legend
                            if (colVm is ILayerColumn)
                            {
                                ILayerColumn lcVM = colVm as ILayerColumn;
                                foundLegendItems.AddRange(lcVM.Layers.SelectMany(l => Reports.SVG.LegendFactory.GetLegendItemsForLayer(l)));
                            }
                            if (colVm is Columns.VisualColumnVM)
                            {
                                Columns.VisualColumnVM vcVM = (Columns.VisualColumnVM)colVm;
                                foundLegendItems.AddRange(vcVM.Layers.SelectMany(l => Reports.SVG.LegendFactory.GetLegendItemsForVisualLayer(l)));
                            }
                            idx++;
                        }

                        //the legend items are split into groups
                        Dictionary <Tuple <string, Reports.SVG.PropertyRepresentation>, List <Reports.SVG.ILegendItem> > groupsData
                            = new Dictionary <Tuple <string, Reports.SVG.PropertyRepresentation>, List <Reports.SVG.ILegendItem> >();
                        foreach (var item in foundLegendItems)
                        {
                            Tuple <string, Reports.SVG.PropertyRepresentation> key = Tuple.Create(item.Item1.PropID, item.Item1.Representation);
                            if (!groupsData.ContainsKey(key))
                            {
                                groupsData.Add(key, new List <Reports.SVG.ILegendItem>());
                            }
                            groupsData[key].Add(item.Item2);
                        }

                        //groups are transformed into ILegnedGroups
                        List <Reports.SVG.ILegendGroup> legendGroups = new List <Reports.SVG.ILegendGroup>();
                        foreach (var kvp in groupsData)
                        {
                            Reports.SVG.ILegendGroup group = new Reports.SVG.LegendGroup(
                                kvp.Key.Item1,
                                kvp.Value.ToArray());
                            legendGroups.Add(group);
                        }



                        var svg = Reports.SVG.Report.Generate(columnRenderers.ToArray(), legendGroups.ToArray());
                        using (XmlTextWriter writer = new XmlTextWriter(filepath, Encoding.UTF8))
                        {
                            svg.Write(writer);
                        }

                        MessageBox.Show(string.Format("SVG отчет успешно сохранен в файл {0}", filepath), "Успешно", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                });
            }
        }
示例#55
0
        public override void ExecuteWithResourceItems(System.Collections.Generic.IEnumerable <ResourceEditor.ViewModels.ResourceItem> resourceItems)
        {
            var firstSelectedItem = resourceItems.First();

            var sdialog = new Microsoft.Win32.SaveFileDialog();

            sdialog.AddExtension = true;
            sdialog.FileName     = firstSelectedItem.Name;

            if (firstSelectedItem.ResourceValue is System.Drawing.Bitmap)
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.ImageFiles} (*.png)|*.png");
                sdialog.DefaultExt = ".png";
            }
            else if (firstSelectedItem.ResourceValue is System.Drawing.Icon)
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.Icons}|*.ico");
                sdialog.DefaultExt = ".ico";
            }
            else if (firstSelectedItem.ResourceValue is System.Windows.Forms.Cursor)
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.CursorFiles} (*.cur)|*.cur");
                sdialog.DefaultExt = ".cur";
            }
            else if (firstSelectedItem.ResourceValue is byte[])
            {
                sdialog.Filter     = StringParser.Parse("${res:SharpDevelop.FileFilter.BinaryFiles} (*.*)|*.*");
                sdialog.DefaultExt = ".bin";
            }
            else
            {
                return;
            }

            bool?dr = sdialog.ShowDialog();

            if (!dr.HasValue || !dr.Value)
            {
                return;
            }

            try {
                if (firstSelectedItem.ResourceValue is Icon)
                {
                    FileStream fstr = new FileStream(sdialog.FileName, FileMode.Create);
                    ((Icon)firstSelectedItem.ResourceValue).Save(fstr);
                    fstr.Close();
                }
                else if (firstSelectedItem.ResourceValue is Image)
                {
                    Image img = (Image)firstSelectedItem.ResourceValue;
                    img.Save(sdialog.FileName);
                }
                else
                {
                    FileStream   fstr = new FileStream(sdialog.FileName, FileMode.Create);
                    BinaryWriter wr   = new BinaryWriter(fstr);
                    wr.Write((byte[])firstSelectedItem.ResourceValue);
                    fstr.Close();
                }
            } catch (Exception ex) {
                SD.MessageService.ShowWarning("Can't save resource to " + sdialog.FileName + ": " + ex.Message);
            }
        }
 private void GenerateSchedule_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         _sw.Reset();
         _sw.Start();
         string[] files     = Directory.GetFiles(_outputPath, "*.xml", SearchOption.TopDirectoryOnly);
         string   str       = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<body>\r\n";
         int      num       = 0;
         string[] array     = files;
         var      pause     = Settings.Default.NextProjectPause;
         var      waitEvent = Settings.Default.NoWaitForThreads ? "6" : "5";
         var      waitParam = Settings.Default.NoWaitForThreads ? "" : "0";
         foreach (string text in array)
         {
             string text2 = Path.GetFileNameWithoutExtension(text)?.Replace('.', '_');
             File.Copy(text, Path.Combine(_xrumerPath, "Projects", text2 + ".xml"), overwrite: true);
             string str2 = $"  <Schedule{num}>\r\n" +
                           $"    <PerformedTime></PerformedTime>\r\n" +
                           $"    <EventNum>{waitEvent}</EventNum>\r\n" +
                           $"    <EventParameter>{waitParam}</EventParameter>\r\n" +
                           $"    <JobNum>4</JobNum>\r\n" +
                           $"    <JobParameter>{text2}</JobParameter>\r\n" +
                           $"  </Schedule{num++}>\r\n" +
                           $"  <Schedule{num}>\r\n" +
                           $"    <PerformedTime></PerformedTime>\r\n" +
                           $"    <EventNum>6</EventNum>\r\n" +
                           $"    <EventParameter></EventParameter>\r\n" +
                           $"    <JobNum>24</JobNum>\r\n" +
                           $"    <JobParameter>00:01:00</JobParameter>\r\n" +
                           $"  </Schedule{num++}>\r\n" +
                           $"  <Schedule{num}>\r\n" +
                           $"    <PerformedTime></PerformedTime>\r\n" +
                           $"    <EventNum>6</EventNum>\r\n" +
                           $"    <EventParameter></EventParameter>\r\n" +
                           $"    <JobNum>1</JobNum>\r\n" +
                           $"    <JobParameter></JobParameter>\r\n" +
                           $"  </Schedule{num++}>\r\n" +
                           $"  <Schedule{num}>\r\n" +
                           $"    <PerformedTime></PerformedTime>\r\n" +
                           $"    <EventNum>0</EventNum>\r\n" +
                           $"    <EventParameter></EventParameter>\r\n" +
                           $"    <JobNum>24</JobNum>\r\n" +
                           $@"    <JobParameter>{pause:hh\:mm\:ss}</JobParameter>\r\n" +
                           $"  </Schedule{num++}>";
             str += str2;
         }
         _sw.Stop();
         MessageBoxResult messageBoxResult = System.Windows.MessageBox.Show($@"Job's done in {_sw.Elapsed:hh\:mm\:ss\.fff}" + Environment.NewLine + $"Projects scheduled: <{files.Count()}>" + Environment.NewLine + "Add loop from the beginnig?", "Finished", MessageBoxButton.YesNo);
         if (messageBoxResult == MessageBoxResult.Yes)
         {
             str += $"\r\n  <Schedule{num}>\r\n    <PerformedTime></PerformedTime>\r\n    <EventNum>5</EventNum>\r\n    <EventParameter>0</EventParameter>\r\n    <JobNum>23</JobNum>\r\n    <JobParameter>0</JobParameter>\r\n  </Schedule{num++}>";
         }
         str += "\r\n</body>";
         Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog
         {
             DefaultExt   = "xml",
             AddExtension = true,
             CustomPlaces = new List <Microsoft.Win32.FileDialogCustomPlace>
             {
                 new Microsoft.Win32.FileDialogCustomPlace(Path.Combine(_xrumerPath, "Schedules"))
             }
         };
         if (saveFileDialog.ShowDialog() ?? false)
         {
             File.WriteAllText(saveFileDialog.FileName, str);
         }
     }
     catch (Exception ex)
     {
         System.Windows.MessageBox.Show(ex.Message);
     }
 }
示例#57
0
        private bool SaveFile(bool forceDialog = false)
        {
            string   filePath = "";
            FileType fileType = FileType.None;

            // check if our filepath is currently set (meaning we've saved before)
            if (string.IsNullOrEmpty(FileManager.CurrentFile.FilePath) || forceDialog)
            {
                // open the dialog to save
                Nullable <bool> result = false;

                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
                //dlg.FileName = "Document"; // Default file name
                dlg.DefaultExt = ".md";  // Default file extension
                dlg.Filter     = FILTER; // Filter files by extension

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

                if (!result.Value)
                {
                    // operation was cancelled
                    return(false);
                }

                if ((FileType)dlg.FilterIndex != FileType.None)
                {
                    fileType = (FileType)dlg.FilterIndex;
                    filePath = dlg.FileName;

                    FileManager.CurrentFile.FilePath = dlg.FileName;
                    FileManager.CurrentFile.Name     = System.IO.Path.GetFileName(dlg.FileName);
                }
            }
            // our file has been saved before, so we have a location for it.
            else
            {
                filePath = FileManager.CurrentFile.FilePath;
                fileType = FileManager.CurrentFile.FileType;
            }



            // Process save file dialog box results
            var document = new TextRange(FileManager.CurrentFile.Page.editorDocument.ContentStart, FileManager.CurrentFile.Page.editorDocument.ContentEnd).Text;

            // the string we'll eventually write
            string saveFile = "";

            // find what extension we saved as
            if (fileType == FileType.Markdown)
            {
                saveFile = document;
            }
            else if (fileType == FileType.HTML)
            {
                saveFile = TextHandler.Convert(document, FileType.HTML, FileType.Markdown);
            }

            // Write to the file
            File.WriteAllText(filePath, saveFile);

            // let our file know that we're all up to date
            FileManager.CurrentFile.IsSaved = true;
            MarkFileAsSaved();

            return(true);
        }
示例#58
0
    // since inheritance of Window does not work, the eventhandler have to be static methods and added after generation of the Window object

    // keyboard is pressed
    private static void InkCanvas_KeyDown(object sender, KeyEventArgs e)
    {
        Key Taste = e.Key;
        // the sender object is the object that generated the event
        InkCanvas objInkCanvas = (InkCanvas)sender;

        if (Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftCtrl))
// the following line only works with .Net 4.x
//		if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
        {         // if Ctrl is pressed
            switch (Taste)
            {
            case Key.C:                     // copy marked area
                objInkCanvas.CopySelection();
                break;

            case Key.O:                     // open ink drawing
                Microsoft.Win32.OpenFileDialog objOpenDialog = new Microsoft.Win32.OpenFileDialog();
                objOpenDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objOpenDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objOpenDialog.FileName, FileMode.Open);
                    objInkCanvas.Strokes.Add(new StrokeCollection(objFileStream));
                    objFileStream.Dispose();
                }
                break;

            case Key.P:                     // save grafic as PNG file
                Microsoft.Win32.SaveFileDialog objPNGDialog = new Microsoft.Win32.SaveFileDialog();
                objPNGDialog.Filter = "png files (*.png)|*.png";
                if ((bool)objPNGDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objPNGDialog.FileName, FileMode.Create);
                    System.Windows.Media.Imaging.RenderTargetBitmap objRenderBitmap = new System.Windows.Media.Imaging.RenderTargetBitmap((int)objInkCanvas.ActualWidth, (int)objInkCanvas.ActualHeight, 96.0, 96.0, System.Windows.Media.PixelFormats.Default);
                    objRenderBitmap.Render(objInkCanvas);
                    System.Windows.Media.Imaging.BitmapFrame      objBitmapFrame = System.Windows.Media.Imaging.BitmapFrame.Create(objRenderBitmap);
                    System.Windows.Media.Imaging.PngBitmapEncoder objImgEncoder  = new System.Windows.Media.Imaging.PngBitmapEncoder();
// alternative for JPG:								System.Windows.Media.Imaging.JpegBitmapEncoder objImgEncoder = new System.Windows.Media.Imaging.JpegBitmapEncoder();
                    objImgEncoder.Frames.Add(objBitmapFrame);
                    objImgEncoder.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.S:                             // save ink drawing
                Microsoft.Win32.SaveFileDialog objSaveDialog = new Microsoft.Win32.SaveFileDialog();
                objSaveDialog.Filter = "isf files (*.isf)|*.isf";
                if ((bool)objSaveDialog.ShowDialog())
                {
                    FileStream objFileStream = new FileStream(objSaveDialog.FileName, FileMode.Create);
                    objInkCanvas.Strokes.Save(objFileStream);
                    objFileStream.Dispose();
                }
                break;

            case Key.V:                     // paste marked area
                objInkCanvas.Paste();
                break;

            case Key.X:                     // cut marked area
                objInkCanvas.CutSelection();
                break;
            }
        }
        else
        {         // no Ctrl key is pressed
            if (Keyboard.Modifiers == ModifierKeys.None)
            {     // only when no other modifier keys are pressed
                switch (Taste)
                {
                case Key.B:                         // next background color
                    Brush ActualBackColor = (Brush)BrushQueue.Dequeue();
                    BrushQueue.Enqueue(ActualBackColor);
                    objInkCanvas.Background = ActualBackColor;
                    break;

                case Key.C:                         // clear window content
                    objInkCanvas.Strokes.Clear();
                    break;

                case Key.D:                         // switch to draw mode
                    if (objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreHighLightSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreHighLightSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreHighLightColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Ellipse;
                        objInkCanvas.DefaultDrawingAttributes.IsHighlighter = false;
                        objInkCanvas.DefaultDrawingAttributes.Color         = StoreInkColor;
                        objInkCanvas.DefaultDrawingAttributes.Height        = StoreInkSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width         = StoreInkSizeWidth;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    break;

                case Key.E:                         // // switch to erase mode (and toggle it)
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByStroke:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;

                    case InkCanvasEditingMode.EraseByPoint:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByStroke;
                        break;

                    case InkCanvasEditingMode.Ink:
                        objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        break;
                    }
                    break;

                case Key.H:                         // switch to highlight mode
                    if (!objInkCanvas.DefaultDrawingAttributes.IsHighlighter)
                    {
                        StoreInkSizeWidth  = objInkCanvas.DefaultDrawingAttributes.Width;
                        StoreInkSizeHeight = objInkCanvas.DefaultDrawingAttributes.Height;
                        StoreInkColor      = objInkCanvas.DefaultDrawingAttributes.Color;
                        objInkCanvas.DefaultDrawingAttributes.Color = StoreHighLightColor;
                    }
                    objInkCanvas.EditingMode = InkCanvasEditingMode.Ink;
                    objInkCanvas.DefaultDrawingAttributes.IsHighlighter = true;
                    objInkCanvas.DefaultDrawingAttributes.StylusTip     = StylusTip.Rectangle;
                    if (StoreHighLightSizeWidth > 0.0)
                    {
                        objInkCanvas.DefaultDrawingAttributes.Height = StoreHighLightSizeHeight;
                        objInkCanvas.DefaultDrawingAttributes.Width  = StoreHighLightSizeWidth;
                    }
                    break;

                case Key.N:                         // next foreground color
                    Color ActualFrontColor = (Color)ColorQueue.Dequeue();
                    ColorQueue.Enqueue(ActualFrontColor);
                    objInkCanvas.DefaultDrawingAttributes.Color = ActualFrontColor;
                    break;

                case Key.Q:                         // close window
                    // event is handled now
                    e.Handled = true;
                    // parent object is Window
                    ((Window)(objInkCanvas).Parent).Close();
                    break;

                case Key.S:                         // start marking
                    objInkCanvas.Select(new System.Windows.Ink.StrokeCollection());
                    break;

                case Key.OemMinus:                         // shrink brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width > 3.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width - 2.0, objInkCanvas.EraserShape.Height - 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height > 3.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height - 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width - 2.0;
                        }
                        break;
                    }
                    break;

                case Key.OemPlus:                         // enlarge brush
                    switch (objInkCanvas.EditingMode)
                    {
                    case InkCanvasEditingMode.EraseByPoint:
                        if (objInkCanvas.EraserShape.Width < 50.0)
                        {
                            objInkCanvas.EraserShape = new RectangleStylusShape(objInkCanvas.EraserShape.Width + 2.0, objInkCanvas.EraserShape.Height + 2.0);
                            // size change needs refresh to display
                            objInkCanvas.EditingMode = InkCanvasEditingMode.None;
                            objInkCanvas.EditingMode = InkCanvasEditingMode.EraseByPoint;
                        }
                        break;

                    case InkCanvasEditingMode.Ink:
                        if (objInkCanvas.DefaultDrawingAttributes.Height < 50.0)
                        {
                            objInkCanvas.DefaultDrawingAttributes.Height = objInkCanvas.DefaultDrawingAttributes.Height + 2.0;
                            objInkCanvas.DefaultDrawingAttributes.Width  = objInkCanvas.DefaultDrawingAttributes.Width + 2.0;
                        }
                        break;
                    }
                    break;
                }
            }
        }
    }
示例#59
0
        public void OpenProject(winForms.RichTextBox htmlTextBox, winForms.RichTextBox csstextBox, MenuItem SaveProject, CefSharp.Wpf.ChromiumWebBrowser mwb)
        {
            if (SaveProject.IsEnabled == true)
            {
                MessageBoxResult msgBoxRes = MessageBox.Show("Do you want to save content or not?", "Save File", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (msgBoxRes == MessageBoxResult.Yes)
                {
                    Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
                    sfd.DefaultExt = ".html";
                    sfd.Filter     = "HTML File (.html)|*.html";
                    if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)
                    {
                        File.WriteAllText(sfd.FileName, htmlTextBox.Text);
                        savepath = sfd.FileName.ToString();
                        save     = true;
                    }

                    //Open the respective css file
                    sfd.DefaultExt = ".css";
                    sfd.Filter     = "CSS File (.css)|*.css";
                    if (sfd.ShowDialog() == true && sfd.FileName.Length > 0)
                    {
                        File.WriteAllText(sfd.FileName, csstextBox.Text);
                        csssavepath = sfd.FileName.ToString();
                        save        = true;
                    }
                }
            }
            Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
            ofd.DefaultExt = ".html";
            ofd.Filter     = "HTML File (.html)|*.html|ALL Files (.)|*.*";
            if (ofd.ShowDialog() == true && ofd.CheckFileExists)
            {
                StreamReader sr1 = new StreamReader(ofd.FileName, Encoding.Default);
                htmlTextBox.Text = sr1.ReadToEnd();
                save             = true;
                savepath         = ofd.FileName.ToString();
            }

            ofd.Title      = "Open CSS file";
            ofd.DefaultExt = ".css";
            ofd.Filter     = "CSS File (.css)|*.css|ALL Files (.)|*.*";
            if (ofd.ShowDialog() == true && ofd.CheckFileExists)
            {
                StreamReader sr1 = new StreamReader(ofd.FileName, Encoding.Default);
                csstextBox.Text = sr1.ReadToEnd();
                save            = true;
                csssavepath     = ofd.FileName.ToString();
            }


            //validation
            //stop single line grammercheck firing
            MainWindow.htmlfire = false;
            MainWindow.fire     = false;
            //creating objects to simulate validation
            htmltextBoxClass htb = new htmltextBoxClass();
            csstextBoxClass  ctb = new csstextBoxClass();


            //Overriding Paste Functionality
            //Showing busy work with mouse
            Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
            try
            {
                htb.ValidateTags(htmlTextBox);
                ctb.clipboardGrammerCheck(csstextBox);

                this.mw.Dispatcher.Invoke(() =>
                {
                    Regex singlelinepattern = new Regex(@"\s*?(\r\n|\n|\r)\s*");
                    String htmlH            = htmlTextBox.Text;
                    String singleLineString = singlelinepattern.Replace(htmlH, "");
                    //winForms.MessageBox.Show(singleLineString);
                    IFrame frame = mwb.GetMainFrame();
                    frame.ExecuteJavaScriptAsync(String.Format("testFunc(`{0}`)", htmlH));
                });
            }
            finally
            {
                Mouse.OverrideCursor = null;
            }
            MainWindow.htmlfire = true;
            MainWindow.fire     = true;


            SaveProject.IsEnabled = false;
            save = true;
        }