private void RegisterCommands(ImagePresentationViewModel viewModel)
        {
            viewModel.SaveCommand = UICommand.Regular(() =>
            {
                var dialog = new SaveFileDialog
                {
                    Filter = "PNG Image|*.png|Bitmap Image|*.bmp",
                    InitialDirectory = Settings.Instance.DefaultPath
                };
                var dialogResult = dialog.ShowDialog();
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    var tmp = viewModel.Image;
                    using (var bmp = new Bitmap(tmp))
                    {
                        if (File.Exists(dialog.FileName))
                        {
                            File.Delete(dialog.FileName);
                        }

                        switch (dialog.FilterIndex)
                        {
                            case 0:
                                bmp.Save(dialog.FileName, ImageFormat.Png);
                                break;
                            case 1:
                                bmp.Save(dialog.FileName, ImageFormat.Bmp);
                                break;
                        }
                    }
                }
            });
        }
Ejemplo n.º 2
2
        static void Main(string[] args)
        {
            var xEngine = new Engine();

            DefaultEngineConfiguration.Apply(xEngine);

            var xOutputXml = new OutputHandlerXml();
            xEngine.OutputHandler = new MultiplexingOutputHandler(
                xOutputXml,
                new OutputHandlerFullConsole());

            xEngine.Execute();

            global::System.Console.WriteLine("Do you want to save test run details?");
            global::System.Console.Write("Type yes, or nothing to just exit: ");
            var xResult = global::System.Console.ReadLine();
            if (xResult != null && xResult.Equals("yes", StringComparison.OrdinalIgnoreCase))
            {
                var xSaveDialog = new SaveFileDialog();
                xSaveDialog.Filter = "XML documents|*.xml";
                if (xSaveDialog.ShowDialog() != DialogResult.OK)
                {
                    return;
                }

                xOutputXml.SaveToFile(xSaveDialog.FileName);
            }
        }
Ejemplo n.º 3
1
        private void ExportButton_Click(object sender, RoutedEventArgs e)
        {
            IDocumentFormatProvider provider = this.provider;
            SaveFileDialog dialog = new SaveFileDialog();

            if ((provider as DocxFormatProvider) != null)
            {
                dialog.DefaultExt = "docx";
                dialog.Filter = "Word document (docx) | *.docx |All Files (*.*) | *.*";
            }
            else if ((provider as PdfFormatProvider) != null)
            {
                dialog.DefaultExt = "pdf";
                dialog.Filter = "Pdf document (pdf) | *.pdf |All Files (*.*) | *.*";
            }
            else if ((provider as HtmlFormatProvider) != null)
            {
                dialog.DefaultExt = "html";
                dialog.Filter = "Html document (html) | *.html |All Files (*.*) | *.*";
            }
            else
            {
                MessageBox.Show("Unknown output format!");
                return;
            }

            SaveFile(dialog, provider, document);
            (this.Parent as RadWindow).Close();
        }
        private void ExportToExcel()
        {
            DgStats.SelectAllCells();
            DgStats.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
            ApplicationCommands.Copy.Execute(null, DgStats);
            var stats = (string) Clipboard.GetData(DataFormats.CommaSeparatedValue);
            //String result = (string)Clipboard.GetData(DataFormats..Text);
            DgStats.UnselectAllCells();

            DgUnmatched.SelectAllCells();
            DgUnmatched.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
            ApplicationCommands.Copy.Execute(null, DgUnmatched);
            var unmatched = (string) Clipboard.GetData(DataFormats.CommaSeparatedValue);
            DgUnmatched.UnselectAllCells();
            var saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = string.Format("{0}.Reconcile.csv", Path.GetFileName(_vm.BankFile.FilePath));
            if (saveFileDialog.ShowDialog() == true)
            {
                var file = new StreamWriter(saveFileDialog.FileName);
                file.WriteLine(stats);
                file.WriteLine("");
                file.WriteLine(unmatched);
                file.Close();
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SaveFileService"/> class.
        /// </summary>
        public SaveFileService() {
            saveFileDialog = new SaveFileDialog();
#if NET
            saveFileDialog.AddExtension = true;
            saveFileDialog.CheckPathExists = true;
#endif
        }
Ejemplo n.º 6
0
        private void BtnGenKey_OnClick(object sender, RoutedEventArgs e)
        {
            var dlg = new SaveFileDialog();
            dlg.Filter = "Key documents (.key)|*.key";

            var result = dlg.ShowDialog();
            if (result.HasValue && result.Value)
            {
                var key = string.Empty;

                using (var rsa = new RSACryptoServiceProvider())
                {
                    key = rsa.ToXmlString(true);
                }

                using (var writer = new StreamWriter(new FileStream(dlg.FileName, FileMode.Truncate)))
                {
                    writer.Write(key);
                }

                TbKey.Text = dlg.FileName;
                Application.Current.Properties["KeyPath"] = dlg.FileName;

                ValidateConfig();
            }
        }
Ejemplo n.º 7
0
        protected override void mergeTiffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = imageFolder;
            openFileDialog1.Title = Properties.Resources.Select + " Input Images";
            openFileDialog1.Filter = "Image Files (*.tif;*.tiff)|*.tif;*.tiff|Image Files (*.bmp)|*.bmp|Image Files (*.jpg;*.jpeg)|*.jpg;*.jpeg|Image Files (*.png)|*.png|All Image Files|*.tif;*.tiff;*.bmp;*.jpg;*.jpeg;*.png";
            openFileDialog1.FilterIndex = filterIndex;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filterIndex = openFileDialog1.FilterIndex;
                imageFolder = Path.GetDirectoryName(openFileDialog1.FileName);
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.InitialDirectory = imageFolder;
                saveFileDialog1.Title = Properties.Resources.Save + " Multi-page TIFF Image";
                saveFileDialog1.Filter = "Image Files (*.tif;*.tiff)|*.tif;*.tiff";
                saveFileDialog1.RestoreDirectory = true;

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    File.Delete(saveFileDialog1.FileName);

                    ImageIOHelper.MergeTiff(openFileDialog1.FileNames, saveFileDialog1.FileName);
                    MessageBox.Show(this, Properties.Resources.Mergecompleted + Path.GetFileName(saveFileDialog1.FileName) + Properties.Resources.created, strProgName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Ejemplo n.º 8
0
    public static void ExportDataGrid(DataGrid dGrid, String author, String companyName, String mergeCells, int boldHeaderRows, string fileName)
    {
        if (Application.Current.HasElevatedPermissions)
        {

            var filePath ="C:" + Path.DirectorySeparatorChar +"Nithesh"+Path.DirectorySeparatorChar +fileName + ".XML";

            File.Create(filePath);
            Stream outputStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite);

            ExportToExcel(dGrid, author, companyName, mergeCells, boldHeaderRows, "XML", outputStream);
        }
        else
        {
            SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "xml", Filter = FILE_FILTER, FilterIndex = 2, DefaultFileName = fileName };

            if (objSFD.ShowDialog() == true)
            {
                string strFormat = objSFD.SafeFileName.Substring(objSFD.SafeFileName.IndexOf('.') + 1).ToUpper();
                Stream outputStream = objSFD.OpenFile();

                ExportToExcel(dGrid, author, companyName, mergeCells, boldHeaderRows, strFormat, outputStream);
            }
        }
    }
Ejemplo n.º 9
0
        private void Save_Click( object sender, RoutedEventArgs e )
        {
            if ( Texture == null )
                return;

            try
            {
                SaveFileDialog dialog = new SaveFileDialog();

                if ( Texture.Data == null )
                    dialog.Filter = "PNG Files|*.png|JPG Files|*.jpg|BMP Files|*.bmp";
                else
                    dialog.Filter = "DDS Files|*.dds|PNG Files|*.png|JPG Files|*.jpg|BMP Files|*.bmp";

                dialog.CheckPathExists = true;
                dialog.Title = "Save File";
                dialog.FileName = Texture.Name;

                if ( dialog.ShowDialog() == true )
                {
                    int filter = dialog.FilterIndex;

                    if ( Texture.Data == null )
                        filter += 1;

                    if ( dialog.FilterIndex == 0 )
                    {
                        using ( FileStream stream = File.OpenWrite( dialog.FileName ) )
                        {
                            stream.Write( Texture.Data, 0, Texture.Data.Length );
                        }
                    }
                    else
                    {
                        BitmapEncoder encoder = null;

                        switch ( dialog.FilterIndex )
                        {
                            case 1: encoder = new PngBitmapEncoder(); break;
                            case 2: encoder = new JpegBitmapEncoder(); break;
                            case 3: encoder = new BmpBitmapEncoder(); break;
                        }

                        if ( encoder != null )
                        {
                            encoder.Frames.Add( BitmapFrame.Create( Texture.Image ) );

                            using ( FileStream file = File.OpenWrite( dialog.FileName ) )
                            {
                                encoder.Save( file );
                            }
                        }
                    }
                }
            }
            catch ( Exception ex )
            {
                App.Window.ShowNotification( NotificationType.Error, ex );
            }
        }
Ejemplo n.º 10
0
 private void DownloadVideo(object sender, RoutedEventArgs e)
 {
     var url = textBox.Text;
     Settings.Default.LastURL = url;
     Settings.Default.Save();
     IDownload download = null;
     var dialog = new SaveFileDialog()
     {
         CheckFileExists = false,AddExtension = true,OverwritePrompt = true,CreatePrompt = false,CheckPathExists = false,DefaultExt = ".flv",
         Filter = "Flash 视频|*.flv" // Filter files by extension
     };
     if (dialog.ShowDialog(this) != true)
     {
         return;
     }
     
     if (url.StartsWith("rtmp://"))
     {
         download = new RtmpDownload();
         download.Start(url, dialog.FileName);
     }
     else if (url.StartsWith("rtmfp://"))
     {
         download = new DownloadProtocol();
         download.Start(url,dialog.FileName);
     }
     
     Settings.Default.DowloadHistory.Add(url);
     Settings.Default.Save();
     DownloadList.Add(download);
     listBox.SelectedItem = download;
 }
Ejemplo n.º 11
0
        // Handles save image click
        private void OnSaveImageClick(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.Filter = "24-bit Bitmap (*.bmp)|*.bmp|JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF (*.gif)|*.gif|PNG (*.png)|*.png";
            dlg.FilterIndex = 4;
            bool? dlgResult = dlg.ShowDialog(Window.GetWindow(this));
            if(dlgResult.HasValue && dlgResult.Value)
            {
                Visualizer visualizer = Visualizer;
                RenderTargetBitmap bitmap = new RenderTargetBitmap((int)previewPage.PageWidth, (int)previewPage.PageHeight, 96, 96, PixelFormats.Pbgra32);

                visualizer.RenderTo(bitmap);

                BitmapEncoder encoder = null;
                string ext = System.IO.Path.GetExtension(dlg.FileName);
                if (ext == "bmp") encoder = new BmpBitmapEncoder();
                else if ((ext == "jpg") || (ext == "jpeg")) encoder = new JpegBitmapEncoder();
                else encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bitmap));
                using (FileStream stream = new FileStream(dlg.FileName, FileMode.Create, FileAccess.Write))
                {
                    encoder.Save(stream);
                    stream.Flush();
                }
            }
        }
Ejemplo n.º 12
0
        public void openSaveAs()
        {
            //Opens Save file dialog box
               SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            //Only allows .txt files to be saved
            saveFileDialog1.Filter = "Text Files|*.txt";

            //Users decision to act with SaveDialog
            bool? saveFileAs = saveFileDialog1.ShowDialog();

            //If user does press save
            if (saveFileAs == true)
            {
                //File Name of user choice
                string fileNameNew = saveFileDialog1.FileName;

                //Rename FileName
                fileName = fileNameNew;

                //Writes the text to the file
                File.WriteAllText(fileNameNew, TextBox_Editor.Text);

            }
            //If user decides not to save, do nothing.
            return;
        }
Ejemplo n.º 13
0
 private void CSV_Format(DataGridView x)
 {
     SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.Filter = "CSV Files (*.csv)|*.csv";
     if (saveFileDialog.ShowDialog() == DialogResult.OK)
     {
         string value = "\r\n";
         TextWriter textWriter = new StreamWriter(saveFileDialog.FileName);
         DataTable dataTable = x.DataSource as DataTable;
         foreach (DataColumn dataColumn in dataTable.Columns)
         {
             string value2 = dataColumn.ColumnName + ",";
             textWriter.Write(value2);
         }
         textWriter.Write(value);
         foreach (DataRow dataRow in dataTable.Rows)
         {
             foreach (DataColumn column in dataTable.Columns)
             {
                 string value3 = dataRow[column] + ",";
                 textWriter.Write(value3);
             }
             textWriter.Write(value);
         }
         textWriter.Close();
         MessageBox.Show(Path.GetFileName(saveFileDialog.FileName) + " saved sucessfully");
     }
 }
Ejemplo n.º 14
0
        private void MenuItem_New_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Do you want to save changes before starting a new file?", "Warning", MessageBoxButton.YesNo);

            switch (result)
            {
                case MessageBoxResult.Yes:
                    SaveFileDialog saveFile = new SaveFileDialog();

                    saveFile.OverwritePrompt = true;

                    saveFile.Filter = "Text File|*.txt";

                    saveFile.FileName = "NewFile";

                    if (saveFile.ShowDialog() == true)
                    {
                        System.IO.File.WriteAllText(saveFile.FileName, textBox_Editor.Text);
                    }
                    break;
                case MessageBoxResult.No:
                    textBox_Editor.Clear();
                    break;
            }
        }
Ejemplo n.º 15
0
 private void SelectPath_Click(object sender, RoutedEventArgs e)
 {
     if (_isInFileMode)
     {
         var sfd = new SaveFileDialog
         {
             Filter =
                 string.Format("{0}|{1}|MP3|*.mp3|AAC|*.aac|WMA|*.wma",
                     Application.Current.Resources["CopyFromOriginal"], "*" + _defaultExtension),
             FilterIndex = (int)(DownloadSettings.Format +1),
             FileName = Path.GetFileName(SelectedPath)
         };
         if (sfd.ShowDialog(this) == true)
         {
             SelectedPath = sfd.FileName;
             DownloadSettings.Format = (AudioFormat)(sfd.FilterIndex -1);
             if (sfd.FilterIndex > 1)
                 DownloadSettings.IsConverterEnabled = true;
             OnPropertyChanged("DownloadSettings");
             CheckIfFileExists();
         }
     }
     else
     {
         var fbd = new WPFFolderBrowserDialog {InitialDirectory = DownloadSettings.DownloadFolder};
         if (fbd.ShowDialog(this) == true)
             SelectedPath = fbd.FileName;
     }
 }
Ejemplo n.º 16
0
    //konstruktor wczytujący kalendarz z pliku
    public Aplikacja()
    {
        kalendarz = new Kalendarz();
        data = new Data_dzien();
        while (data.DzienTygodnia() != DniTygodnia.poniedziałek) { data--; }

        //inicjalizacja OpenFileDialog
        otwórz_plik = new OpenFileDialog();
        otwórz_plik.InitialDirectory = "c:\\";
        otwórz_plik.FileName = "";
        otwórz_plik.Filter = "pliki Kalendarza (*.kalen)|*.kalen|All files (*.*)|*.*";
        otwórz_plik.FilterIndex = 2;
        otwórz_plik.RestoreDirectory = true;
        //**************KONIEC INICJALIZACJI OpenFileDialog**************

        //inicjalizacja SaveFileDialog
        zapisz_plik = new SaveFileDialog();
        zapisz_plik.AddExtension = true;
        zapisz_plik.FileName = "";
        zapisz_plik.InitialDirectory = "c:\\";
        zapisz_plik.Filter = "pliki Kalendarza (*.kalen)|*.kalen|All files (*.*)|*.*";
        zapisz_plik.FilterIndex = 1;
        zapisz_plik.RestoreDirectory = true;
        //**************KONIEC INICJALIZACJI SaveFileDialog**************

        if (otwórz_plik.ShowDialog() == DialogResult.OK)
        {
            Stream plik = otwórz_plik.OpenFile();
            kalendarz.Wczytaj(plik);
            plik.Flush();
            plik.Close();
        }
    }
Ejemplo n.º 17
0
    // What to do when the user wants to export a SVG file
    private void exportHandler(object sender, EventArgs e)
    {
        Stream stream;
        SaveFileDialog saveFileDialog = new SaveFileDialog();

        saveFileDialog.Filter = "SVG files|(*.svg)";
        saveFileDialog.RestoreDirectory = true;

        if(saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            if((stream = saveFileDialog.OpenFile()) != null)
            {
                //import header from a file.
                string[] header = { @"<?xml version =""1.0"" standalone=""no""?>", @"<!DOCTYPE svg PUBLIC ""-//W3C//DTD SVG 1.1//EN"" ""http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"">", @"<svg xmlns=""http://www.w3.org/2000/svg"" version=""1.1"">" };
                //import the SVG shapes.

                using (StreamWriter writer = new StreamWriter(stream))
                {
                    foreach (string headerLine in header)
                    {
                        writer.WriteLine(headerLine);
                    }

                    foreach(Shape shape in shapes)
                    {
                        shape.drawTarget = new DrawSVG();
                        shape.Draw();
                        writer.WriteLine(shape.useShape);
                    }
                    writer.WriteLine("</svg>");
                }
            }
        }
    }
Ejemplo n.º 18
0
    // What to do when the user wants to export a TeX file
    private void exportHandler(object sender, EventArgs e)
    {
        Stream stream;
        SaveFileDialog saveFileDialog = new SaveFileDialog();

        saveFileDialog.Filter = "SVG files|(*.svg";
        saveFileDialog.RestoreDirectory = true;

        if(saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            if((stream = saveFileDialog.OpenFile()) != null)
            {
                // Insert code here that generates the string of LaTeX
                //   commands to draw the shapes
                using(StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write("<?xml version='1.0' standalone='no'?> <!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'> <svg xmlns='http://www.w3.org/2000/svg' version='1.1'> ");

                    Visual visual = new VisualSVG(writer);

                    //Draw all shapes
                    foreach (Shape shape in shapes)
                    {
                        shape.visual = visual;

                        shape.Draw();
                    }

                    writer.Write("</svg>");
                }
            }
        }
    }
Ejemplo n.º 19
0
        private void XBuild_OnClick(object sender, RoutedEventArgs e)
        {
            CPPFileAnalyzer analyzer;
            try
            {
                analyzer = new CPPFileAnalyzer(GetString(XSource));
            }
            catch
            {
                MessageBox.Show("Error parsing code! Please check your code before building chart!", "CChart error",
                                MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                Visualizer visualizer = new Visualizer(analyzer.Result);
                SaveFileDialog sfd=new SaveFileDialog();
                sfd.DefaultExt = ".png";
                sfd.Filter = "Images (.png)|*.png";
                if (sfd.ShowDialog().Value)
                {
                    visualizer.Image.Save(sfd.FileName);
                }

            }
            catch
            {
                MessageBox.Show("Error building chart!", "CChart error",
                                MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Ejemplo n.º 20
0
        public void SaveScreen(double x, double y, double width, double height)
        {
            int ix, iy, iw, ih;
            ix = Convert.ToInt32(x);
            iy = Convert.ToInt32(y);
            iw = Convert.ToInt32(width);
            ih = Convert.ToInt32(height);
            try
            {
                Bitmap myImage = new Bitmap(iw, ih);

                Graphics gr1 = Graphics.FromImage(myImage);
                IntPtr dc1 = gr1.GetHdc();
                IntPtr dc2 = NativeMethods.GetWindowDC(NativeMethods.GetForegroundWindow());
                NativeMethods.BitBlt(dc1, ix, iy, iw, ih, dc2, ix, iy, 13369376);
                gr1.ReleaseHdc(dc1);
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.DefaultExt = "png";
                dlg.Filter = "Png Files|*.png";
                DialogResult res = dlg.ShowDialog();
                if (res == System.Windows.Forms.DialogResult.OK)
                    myImage.Save(dlg.FileName, ImageFormat.Png);
            }
            catch { }
        }
    public void Function()
    {
        string strProjectpath =
            PathMap.SubstitutePath("$(PROJECTPATH)") + @"\";
        string strFilename = "Testdatei";

        SaveFileDialog sfd = new SaveFileDialog();
        sfd.DefaultExt = "txt";
        sfd.FileName = strFilename;
        sfd.Filter = "Textdatei (*.txt)|*.txt";
        sfd.InitialDirectory = strProjectpath;
        sfd.Title = "Speicherort für Testdatei wählen:";
        sfd.ValidateNames = true;

        if (sfd.ShowDialog() == DialogResult.OK)
        {
            File.Create(sfd.FileName);
            MessageBox.Show(
                "Datei wurde erfolgreich gespeichert:\n" + sfd.FileName,
                "Information",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information
                );
        }

        return;
    }
        public void Export(object parameter)
        {
            RadGridView grid = parameter as RadGridView;
            if (grid != null)
            {
                grid.ElementExporting -= this.ElementExporting;
                grid.ElementExporting += this.ElementExporting;

                grid.ElementExported -= this.ElementExported;
                grid.ElementExported += this.ElementExported;

                string extension = "xls";
                ExportFormat format = ExportFormat.Html;

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

                if (dialog.ShowDialog() == true)
                {
                    using (Stream stream = dialog.OpenFile())
                    {
                        GridViewExportOptions options = new GridViewExportOptions();
                        options.Format = format;
                        options.ShowColumnHeaders = true;
                        options.Encoding = System.Text.Encoding.UTF8;
                        grid.Export(stream, options);
                    }
                }
            }
        }
Ejemplo n.º 23
0
        private void ExportPdf(object sender, RoutedEventArgs e)
        {
            //export the combined PDF
            SaveFileDialog dialog = new SaveFileDialog()
            {
                DefaultExt = "pdf",
                Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", "pdf", "Pdf"),
                FilterIndex = 1
            };

            if (dialog.ShowDialog() == true)
            {
                //export the data from the two RadGridVies instances in separate documents
                RadFixedDocument playersDoc = this.playersGrid.ExportToRadFixedDocument();
                RadFixedDocument clubsDoc = this.clubsGrid.ExportToRadFixedDocument();

                //merge the second document into the first one
                playersDoc.Merge(clubsDoc);

                using (Stream stream = dialog.OpenFile())
                {
                    new PdfFormatProvider().Export(playersDoc, stream);
                }
            }
        }
Ejemplo n.º 24
0
        private void CreateNewPrinterSettingsFile()
        {
            printerSettings = new Settings
            {
                XAxis = new Axis { Minimum = 0, Maximum = 40, PointsPerMillimeter = 10},
                YAxis = new Axis { Minimum = 0, Maximum = 20, PointsPerMillimeter = 10 },
                ZAxis = new Axis { Minimum = 0, Maximum = 80, PointsPerMillimeter = 20 }
            };
            var json = JsonConvert.SerializeObject(printerSettings);

            var createNewSettingsFileDialog = new SaveFileDialog
            {
                InitialDirectory = SettingsFolder,
                DefaultExt = ".json",
                Filter = "Files (.json)|*.json|All files (*.*)|*.*",
                CheckPathExists = true
            };
            createNewSettingsFileDialog.ShowDialog();
            if (createNewSettingsFileDialog.FileName != "")
            {
                SettingsFolder = Path.GetDirectoryName(createNewSettingsFileDialog.FileName);
                SettingsFile = Path.GetFileName(createNewSettingsFileDialog.FileName);
                LabelSettingsFolder.Content = SettingsFolder;
                TextSettingsFileName.Text = SettingsFile;
                File.WriteAllText(createNewSettingsFileDialog.FileName, json);
            }
        }
Ejemplo n.º 25
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;

            if (_recorder.IsRecording)
            {
                _recorder.Stop();

                button.Content = "Start";

                SaveFileDialog dialog = new SaveFileDialog
                {
                    Filter = "Excel files|*.csv"
                };

                dialog.ShowDialog();

                if (!string.IsNullOrWhiteSpace(dialog.FileName))
                {
                    System.IO.File.Copy(_recorder.Result, dialog.FileName);
                }
            }
            else
            {
                _recorder.Start();

                button.Content = "Stop";
            }
        }
Ejemplo n.º 26
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            List<ExportRowHelper> ExportColumnNames = new List<ExportRowHelper>();

            foreach (var item in ufgMain.Children)
            {
                CheckBox cb = item as CheckBox;
                if (cb.IsChecked.Value)
                {
                    ExportColumnNames.Add(new ExportRowHelper() { ColumnName = cb.Tag.ToString(), ColumnValue = cb.Content.ToString() });
                }
            }
            if (ExportColumnNames.Count() <= 0)
            {
                Common.MessageBox.Show("请选择需要导出的列");
                return;
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = string.Format("GlassID导出列表.xls");
            if (sfd.ShowDialog() == true)
            {
                string filename = sfd.FileName;
                string ErrMsg = string.Empty;
                bool bSucc = false;

                bSucc = _export.ExportGlassIDToExcel(_lst, ExportColumnNames, filename, ref ErrMsg);
                if (bSucc)
                {
                    var process = System.Diagnostics.Process.Start(filename);
                }
                else
                    Common.MessageBox.Show(ErrMsg);
            }
            this.Close();
        }
Ejemplo n.º 27
0
    // What to do when the user wants to export a SVG file
    private void exportHandler(object sender, EventArgs e)
    {
        Stream stream;
        SaveFileDialog saveFileDialog = new SaveFileDialog();

        saveFileDialog.Filter = "SVG files|*.svg";
        saveFileDialog.RestoreDirectory = true;

        if(saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            if((stream = saveFileDialog.OpenFile()) != null)
            {
                // Insert code here that generates the string of SVG
                //   commands to draw the shapes

                String SVGtext = "<?xml version=\"1.0\" standalone=\"no\"?>" +
                    "\r\n<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"" +
                    "\r\n\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" +
                    "\r\n<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">";
                foreach (Shape shape in shapes)
                {
                    SVGtext = SVGtext + shape.Conversion("SVG");
                }
                SVGtext = SVGtext + "\r\n</svg>";
                    using (StreamWriter writer = new StreamWriter(stream))
                {
                        // Write strings to the file here using:
                        writer.WriteLine(SVGtext);
                }
            }
        }
    }
Ejemplo n.º 28
0
        private void ExportXlsx(object sender, RoutedEventArgs e)
        {
            //export the combined PDF
            SaveFileDialog dialog = new SaveFileDialog()
            {
                DefaultExt = "xlsx",
                Filter = String.Format("Workbooks (*.{0})|*.{0}|All files (*.*)|*.*", "xlsx"),
                FilterIndex = 1
            };

            if (dialog.ShowDialog() == true)
            {

                //export the data from the two RadGridVies instances in separate documents
                Workbook playersDoc = this.playersGrid.ExportToWorkbook();
                Workbook clubsDoc = this.clubsGrid.ExportToWorkbook();

                //merge the second document into the first one
                Worksheet clonedSheet = playersDoc.Worksheets.Add();
                clonedSheet.CopyFrom(clubsDoc.Sheets[0] as Worksheet);

                using (Stream stream = dialog.OpenFile())
                {
                    new XlsxFormatProvider().Export(playersDoc, stream);
                }
            }
        }
Ejemplo n.º 29
0
        private void ExportToExcel()
        {
            this.BusyIndicator.IsBusy = true;
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = "xlsx";
            dialog.Filter = "Excel Workbook (xlsx) | *.xlsx |All Files (*.*) | *.*";

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

                        XlsxFormatProvider provider = new XlsxFormatProvider();
                        provider.Export(workbook, stream);
                    }
                }
                catch (IOException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            this.BusyIndicator.IsBusy = false;
        }
Ejemplo n.º 30
0
 private void button1_Click(object sender, RoutedEventArgs e)
 {
     SaveFileDialog dialog = new SaveFileDialog();
     dialog.FileName = "result.csv";
     dialog.Filter = "CSVファイル(*.csv)|*.csv|全てのファイル(*.*)|*.*";
     dialog.OverwritePrompt = true;
     dialog.CheckPathExists = true;
     bool? res = dialog.ShowDialog();
     if (res.HasValue && res.Value)
     {
         try
         {
             if (mainWin.fileWriter != null) mainWin.fileWriter.Flush();
             System.IO.Stream fstream = dialog.OpenFile();
             System.IO.Stream fstreamAppend = new System.IO.FileStream(dialog.FileName+"-log.csv", System.IO.FileMode.OpenOrCreate);
             if (fstream != null && fstreamAppend != null)
             {
                 textBox1.Text = dialog.FileName;
                 mainWin.fileWriter = new System.IO.StreamWriter(fstream);
                 mainWin.logWriter = new System.IO.StreamWriter(fstreamAppend);
             }
         }
         catch (Exception exp)
         {
             MessageBox.Show(exp.ToString());
         }
     }
 }
Ejemplo n.º 31
0
        private void ExportResults()
        {
            //SS:01/03/2018:2018-R1:ABSEXCH-19796: When Running the ExchDVT.exe, SQL Admin Passwords are visible in dump file.
            ADODB.Connection conn = new ADODB.Connection();
            ADODB.Command    cmd  = new ADODB.Command();

            if (CompanyCode == null)
            {
                cmd.CommandText = "SELECT [IntegrityErrorNo]" +
                                  ", [IntegrityErrorCode]" +
                                  ", [Severity]" +
                                  ", [IntegrityErrorMessage]" +
                                  ", [IntegritySummaryDescription]" +
                                  ", [SchemaName]" +
                                  ", [TableName]" +
                                  ", [PositionId]" +
                                  "FROM [common].[SQLDataValidation] ";
            }
            else
            {
                cmd.CommandText = "SELECT [IntegrityErrorNo]" +
                                  ", [IntegrityErrorCode]" +
                                  ", [Severity]" +
                                  ", [IntegrityErrorMessage]" +
                                  ", [IntegritySummaryDescription]" +
                                  ", [SchemaName]" +
                                  ", [TableName]" +
                                  ", [PositionId] " +
                                  "FROM [common].[SQLDataValidation] " +
                                  "WHERE SchemaName = '" + CompanyCode + "'";
            }

            cmd.CommandTimeout = 10000;

            if (conn.State == 0)
            {
                if (ConnPassword.Trim() == "")
                {
                    conn.Open();
                }
                else
                {
                    conn.Open(ExchequerCommonSQLConnection, "", ConnPassword.Trim(),
                              (int)ADODB.ConnectModeEnum.adModeUnknown);
                }
            }
            conn.CursorLocation = ADODB.CursorLocationEnum.adUseClient;

            System.Data.DataTable dataTable = new System.Data.DataTable {
                TableName = "resultSet"
            };

            try
            {
                cmd.CommandType      = ADODB.CommandTypeEnum.adCmdText;
                cmd.ActiveConnection = conn;
                ADODB.Recordset recordSet = null;
                object          objRecAff;
                recordSet = (ADODB.Recordset)cmd.Execute(out objRecAff, Type.Missing, (int)ADODB.CommandTypeEnum.adCmdText);

                System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter();
                adapter.Fill(dataTable, recordSet);

                if (conn.State == 1)
                {
                    conn.Close();
                }
            }
            catch
            {
                throw;
            }

            Type officeType = Type.GetTypeFromProgID("Excel.Application");

            if (officeType == null)
            {
                //no Excel installed
                SaveFileDialog.Filter           = "XML File | *.xml";
                SaveFileDialog.InitialDirectory = ExchequerPath + "\\Logs";
                SaveFileDialog.DefaultExt       = "XML";
                SaveFileDialog.OverwritePrompt  = true;
                SaveFileDialog.FileName         = "ExchSQLDataValidationResults";
                if (CompanyCode != null)
                {
                    SaveFileDialog.FileName = SaveFileDialog.FileName + "-" + CompanyCode;
                }
                SaveFileDialog.ShowDialog();
                this.UseWaitCursor = true;

                txtCompanyName.Enabled  = false;
                txtContactName.Enabled  = false;
                txtEmailAddress.Enabled = false;
                btnSaveResults.Enabled  = false;
                System.Windows.Forms.Application.DoEvents();

                XmlTextWriter writer = new XmlTextWriter(@SaveFileDialog.FileName, null);
                writer.WriteStartDocument(true);
                writer.Formatting = Formatting.Indented;

                writer.WriteStartElement("SQLDataValidationResults");

                writer.WriteStartElement("CompanyName");
                writer.WriteString(txtCompanyName.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("ContactName");
                writer.WriteString(txtContactName.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("EmailAddress");
                writer.WriteString(txtEmailAddress.Text);
                writer.WriteEndElement();

                writer.WriteStartElement("VersionInfo");
                writer.WriteString(VersionInfo);
                writer.WriteEndElement();

                dataTable.WriteXml(writer);

                writer.WriteEndDocument();

                writer.Close();
            }
            else
            {
                //Excel installed
                SaveFileDialog.Filter           = "Excel File | *.xlsx";
                SaveFileDialog.InitialDirectory = ExchequerPath + "\\Logs";
                SaveFileDialog.DefaultExt       = "XLSX";
                SaveFileDialog.OverwritePrompt  = true;
                SaveFileDialog.FileName         = "ExchSQLDataValidationResults";
                if (CompanyCode != null)
                {
                    SaveFileDialog.FileName = SaveFileDialog.FileName + "-" + CompanyCode;
                }
                SaveFileDialog.ShowDialog();

                this.UseWaitCursor = true;

                txtCompanyName.Enabled  = false;
                txtContactName.Enabled  = false;
                txtEmailAddress.Enabled = false;
                btnSaveResults.Enabled  = false;
                System.Windows.Forms.Application.DoEvents();

                clsExcelUtlity obj = new Data_Integrity_Checker.clsExcelUtlity();

                obj.WriteDataTableToExcel(dataTable, "ExchSQL Data Validation Results", SaveFileDialog.FileName, txtCompanyName.Text, txtContactName.Text, txtEmailAddress.Text, VersionInfo);
            }

            this.UseWaitCursor = false;
            dataTable          = null;

            Close();
        }
Ejemplo n.º 32
0
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (Orderinfolist_Server != null)
            {
                dataGridView1.DataSource = Orderinfolist_Server;
            }

            if (this.dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("Sorry , No Data Output !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var saveFileDialog = new SaveFileDialog();

            saveFileDialog.DefaultExt = ".csv";
            saveFileDialog.Filter     = "csv|*.csv";
            string strFileName = " 贵州诚德清洁服务管理有限公司客户专员数据" + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");

            saveFileDialog.FileName = strFileName;
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                strFileName = saveFileDialog.FileName.ToString();
            }
            else
            {
                return;
            }
            FileStream   fa        = new FileStream(strFileName, FileMode.Create);
            StreamWriter sw        = new StreamWriter(fa, Encoding.Unicode);
            string       delimiter = "\t";
            string       strHeader = "";

            for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
            {
                strHeader += this.dataGridView1.Columns[i].HeaderText + delimiter;
            }
            sw.WriteLine(strHeader);

            //output rows data
            for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
            {
                string strRowValue = "";

                for (int k = 0; k < this.dataGridView1.Columns.Count; k++)
                {
                    if (this.dataGridView1.Rows[j].Cells[k].Value != null)
                    {
                        strRowValue += this.dataGridView1.Rows[j].Cells[k].Value.ToString().Replace("\r\n", " ").Replace("\n", "") + delimiter;
                        if (this.dataGridView1.Rows[j].Cells[k].Value.ToString() == "LIP201507-35")
                        {
                        }
                    }
                    else
                    {
                        strRowValue += this.dataGridView1.Rows[j].Cells[k].Value + delimiter;
                    }
                }
                sw.WriteLine(strRowValue);
            }
            sw.Close();
            fa.Close();
            MessageBox.Show("Dear User, Down File  Successful !", "System", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Ejemplo n.º 33
0
        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var box2 = new Processing();

            try
            {
                var box = new SaveFileDialog();
                box.Title  = "保存";
                box.Filter = "JPEG(.jpg)|*.jpg";
                box.ShowDialog();
                if (box.FileName == "")
                {
                    return;
                }

                var sq = new setjpgquality();
                sq.ShowDialog();

                Thread T;
                T = new Thread(new ThreadStart(new Action(() =>
                {
                    box2.ShowDialog();
                })));
                T.IsBackground = true;
                T.Start();

                while (!box2.IsHandleCreated)
                {
                    Thread.Sleep(100);
                }

                try
                {
                    int    copysize = 0;
                    byte[] write_this;
                    if (!sq.includes_exif)
                    {
                        write_this = invoke_dll.invoke_heif2jpg(heicfile, sq.value, "temp_bitstream.hevc", ref copysize, false);
                    }
                    else
                    {
                        write_this = invoke_dll.invoke_heif2jpg(heicfile, sq.value, "temp_bitstream.hevc", ref copysize, true);
                    }

                    FileStream   fs     = new FileStream(box.FileName, FileMode.Create);
                    BinaryWriter writer = new BinaryWriter(fs);
                    try
                    {
                        writer.Write(write_this, 0, copysize);
                        writer.Close();
                        fs.Close();
                    }
                    catch (Exception ex) {
                        try
                        {
                            writer.Close();
                            fs.Close();
                        }
                        catch (Exception) { }
                        throw ex;
                    }
                }
                catch (Exception)
                {
                    box2.Invoke(new Action(() =>
                    {
                        box2.Close();
                    }));
                    this.Focus();

                    var errorbox = new Error();
                    errorbox.maintext.Text  = "无法保存到 " + box.FileName;
                    errorbox.linklabel.Text = "转到在线帮助";
                    errorbox.link           = "https://liuziangexit.com/HEIF-Utility/Help/No2.html";
                    errorbox.ShowDialog();
                    return;
                }

                box2.Invoke(new Action(() =>
                {
                    box2.Close();
                }));
                this.Focus();

                MessageBox.Show("成功保存到 " + box.FileName);
                return;
            }
            catch (Exception)
            {
                box2.Invoke(new Action(() =>
                {
                    box2.Close();
                }));
                this.Focus();
                MessageBox.Show("发生未知错误。");
                return;
            }
        }
Ejemplo n.º 34
0
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
            case Key.A:
            {
                accueil ev = new accueil(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.M:
            {
                meteo_jour ev = new meteo_jour(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.P:
            {
                prevision ev = new prevision(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.E:
            {
                evolution ev = new evolution(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.T:
            {
                Contact ev = new Contact(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.R:
            {
                parametre ev = new parametre(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.O:
            {
                apropos ev = new apropos(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.D:
            {
                credit ev = new credit(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.Z:
            {
                connexion ev = new connexion(wilaya, output_out);
                ev.Show();
                this.Close();
            }
            break;

            case Key.S:
            {
                StreamReader sr  = new StreamReader(@"son.txt");
                string       str = sr.ReadLine();
                sr.Close();
                if (str == "Activé")
                {
                    MediaPlayer player = new MediaPlayer();
                    player.Open(new Uri(@"..\..\screen.mp3", UriKind.RelativeOrAbsolute));
                    player.Play();
                }
                //déclaration et instanciation de la fenêtre parcourir
                SaveFileDialog parcourir = new SaveFileDialog();
                parcourir.DefaultExt = "png";
                //je spécifie que seul les images .png sont selectionnables
                parcourir.Filter = " Fichier PNG (*.PNG)|*.png";
                //ouverture de la fenêtre parcourir
                parcourir.ShowDialog();
                CreateScreenShot(this, parcourir.FileName);
            }
            break;
            }
        }
Ejemplo n.º 35
0
        private void UpdateLootLog_Click(object sender, RoutedEventArgs e)
        {
            TextReader     lootLogReader  = null;
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title = "Old Loot Log";
            if (openFileDialog.ShowDialog() == true)
            {
                lootLogReader = new StreamReader(openFileDialog.FileName);
            }

            List <string[]> newResults = new List <string[]>();

            var lootlogParser = new CsvParser(lootLogReader, CultureInfo.InvariantCulture);

            string[] record = null;
            while ((record = lootlogParser.Read()) != null)
            {
                if (record.Length == 9)
                {
                    MessageBox.Show("Missing ItemRefID -- Loot Log too old");
                    return;
                }

                int itemId = int.Parse(record[0]);

                JObject newItem  = ItemDB.Instance.FindItem(itemId);
                string  itemName = newItem["UniqueName"].ToString();
                if (newItem.ContainsKey("LocalizedNames") && newItem["LocalizedNames"] != null)
                {
                    JObject localizedNames = (JObject)newItem["LocalizedNames"];
                    if (localizedNames.ContainsKey("EN-US"))
                    {
                        itemName += " - " + localizedNames["EN-US"].ToString();
                    }
                }

                string shortName = newItem["UniqueName"].ToString();
                string quality   = "0";
                if (shortName.Contains("@"))
                {
                    quality = shortName.Split('@')[1];
                }

                // 5,6,7
                record[5] = shortName;
                record[6] = itemName;
                record[7] = quality;

                newResults.Add(record);
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Title = "Save Location";
            if (saveFileDialog.ShowDialog() == true)
            {
                using (FileStream fs = saveFileDialog.OpenFile() as FileStream)
                    using (TextWriter sr = new StreamWriter(fs))
                        using (CsvWriter lootWriter = new CsvWriter(sr, CultureInfo.InvariantCulture))
                        {
                            foreach (string[] item in newResults)
                            {
                                foreach (string itemValue in item)
                                {
                                    lootWriter.WriteField(itemValue);
                                }
                                lootWriter.NextRecord();
                            }
                            //lootWriter.WriteRecords(newResults.AsEnumerable<string[]>());
                        }
            }

            MessageBox.Show("New log written to --> " + saveFileDialog.FileName);
        }
Ejemplo n.º 36
0
        private void SaveFile_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.ShowDialog();
        }
Ejemplo n.º 37
0
        public static bool existClassifier = true;                                                                                                      //rappresenta il flag che indica se esiste il classificatore per l'analisi corrente NB:E'statico!

        public async void ClassifiersAsync(MyTabAnalysis mytab2)
        {
            bool cyclebreak = false;

            System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
            customCulture.NumberFormat.NumberDecimalSeparator    = ".";
            System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

            //Dialog in cui si permette di scegliere il calssificatore all'utente
            Dialog choose = new Dialog {
                Title = "Scegli il Classificatore", ClientSize = new Size(450, 180), BackgroundColor = new Color(0, 0, 1, 1)
            };
            Button defaultclassifier;
            Button newclassifier;

            choose.Content = new TableLayout {
                Rows =
                {
                    new TableRow(new TableCell(new Label())),
                    new TableRow(new TableCell(new Label {
                        Text = "Quale classificatore vuoi utilizzare per la classificazione delle immagini ? ",TextColor                                                    = new Color(255 / 255, 255 / 255, 255 / 255, 1), TextAlignment   = TextAlignment.Center
                    })),
                    new TableRow(new TableCell(new Label())),
                    new TableRow(new TableCell(defaultclassifier = new Button {
                        Text = "Voglio utilizzare il classificatore di default",TextColor                                                    = new Color(0,                 0,         0, 1), BackgroundColor = new Color(192 / 155, 192 / 155, 192 / 155, 0.6f)
                    })),
                    new TableRow(new TableCell(new Label())),
                    new TableRow(new TableCell(newclassifier = new Button {
                        Text = "Voglio addestrare e creare un nuovo classificatore ",TextColor                                                    = new Color(0,                 0,         0, 1), BackgroundColor = new Color(192 / 155, 192 / 155, 192 / 155, 0.6f)
                    })),
                    new TableRow(new TableCell(new Label()))
                },
            };

            defaultclassifier.Click += (object sender, EventArgs e) =>                  //Caso in cui si utilizzi il classificatore standard
            {
                existClassifier           = true;                                       //Esiste il classificatore per l'analisi corrente
                ClassifierUsedForAnalysis = PathClassifierStandard;                     //Il classificatore usato è quello standard
                choose.Close();
            };

            newclassifier.Click += (object sender, EventArgs e) =>                      //Caso in cui si vuole creare classificatore
            {
                existClassifier = false;                                                //Non esiste ancora il classicatore che si vuole usare..occorre crearlo
                choose.Close();
            };

            choose.ShowModal();


            while (!cyclebreak)
            {
                if (!existClassifier)                   //Caso in cui il classificatore voglio creare un nuovo classificatore
                {
                    //Dialog che spiega come addestrare il classificatore
                    Dialog attention = new Dialog {
                        Title = "Attenzione!", Size = new Eto.Drawing.Size(888, 450)
                    };
                    Button okbutton;
                    attention.Content = new TableLayout {
                        Rows =
                        {
                            new TableRow(new TableCell(new ImageView {
                                Image = new Eto.Drawing.Bitmap(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("pedopornanalyzer.Properties.Resources.warning.png"))
                            }), new TableCell(new Label              {
                                Text = "Attenzione:si è scelto di creare un nuovo classificatore!\n\n" +
                                       "E' possibile addestrare il classificatore fornendogli degli esempi,da cui imparerà a riconoscere immagini simili.\n\n" +
                                       "Per addestrare il classificatore si dovrà:\n" +
                                       "- selezionare una cartella che contiene esclusivamente immagini positive (pornografiche/pedopornografiche) in formato .jpg\n" +
                                       "- selezionare una cartella che contiene esclusivamente immagini negative in formato .jpg\n" +
                                       "  Le due cartelle devono contenere,all'incirca, lo stesso numero di file.\n\n" +
                                       "Nota: Non rispondiamo dei risultati prodotti dal nuovo classificatore, se non \n" +
                                       "si sa come addestrarlo utilizzare quello standard.\n", VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center, TextColor = new Eto.Drawing.Color(1, 1, 1, 1), BackgroundColor = new Eto.Drawing.Color(0, 0, 1, 1), Font = Fonts.Monospace(15f, 0, 0)
                            })),
                            new TableRow(new TableCell(), new TableCell(okbutton = new Button{
                                Text = "Ho capito !"
                            }), new TableCell())
                        }
                    };

                    okbutton.Click += (object sender, EventArgs e) =>
                    {
                        attention.Close();
                    };

                    attention.ShowModal();

                    /* Training Phase */
                    Console.WriteLine("Classifier not detected.");
                    Console.WriteLine("Training new classifier from samples...");
                    string trainFolderPositive = "";
                    bool   presscancel         = true;
                    do                                                                                       //do-while per "costringere" l'utente a scegliere una cartella
                    {
                        var dlg = new SelectFolderDialog();
                        dlg.Title = "Seleziona la cartella che contiene file positive";
                        DialogResult folder = dlg.ShowDialog(null);
                        if (folder == DialogResult.Ok)
                        {
                            presscancel = false;
                            string pathDevice = dlg.Directory.ToString();
                            trainFolderPositive = pathDevice;
                        }
                        else
                        {
                            presscancel = true;
                            MessageBox.Show("Per favore,seleziona una cartella che contiene esclusivamente file positivi in formato .jpg", 0);
                        }
                    }while (presscancel);

                    List <string> files = Directory.EnumerateFiles(trainFolderPositive, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".jpg") || s.EndsWith(".JPG") || s.EndsWith(".jpeg") || s.EndsWith(".JPEG")).ToList();
                    int           numbpositiveimages = files.Count();
                    MessageBox.Show("Cartella selezionata correttamente", 0);


                    string trainFolderNegative = "";
                    presscancel = true;
                    do                                                                                                                                                          //do-while per "costringere" l'utente a scegliere una cartella
                    {
                        var dlg2 = new SelectFolderDialog();
                        dlg2.Title = "Seleziona la cartella che contiene file negativi";
                        DialogResult folder2 = dlg2.ShowDialog(null);
                        if (folder2 == DialogResult.Ok)
                        {
                            presscancel = false;
                            string pathDevice = dlg2.Directory.ToString();
                            trainFolderNegative = pathDevice;
                        }
                        else
                        {
                            presscancel = true;
                            MessageBox.Show("Per favore,seleziona una cartella che contiene esclusivamente file negativi in formato .jpg", 0);
                        }
                    }while (presscancel);

                    files.AddRange(Directory.EnumerateFiles(trainFolderNegative, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".jpg") || s.EndsWith(".JPG") || s.EndsWith(".jpeg") || s.EndsWith(".JPEG")).ToList());
                    populationSize = files.Count();
                    int numbnegativeimages = populationSize - numbpositiveimages;
                    MessageBox.Show("Cartella selezionata correttamente", 0);

                    int[]          labels      = new int[populationSize];
                    Matrix <float> trainingMat = new Matrix <float>(populationSize, 10);

                    Dialog waiting = new Dialog {
                        Title = "Addestramento in corso", Size = new Eto.Drawing.Size(750, 128), Content = new TableLayout {
                            Rows = { new TableRow(new TableCell(new ImageView {
                                    Image = new Eto.Drawing.Bitmap(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("pedopornanalyzer.Properties.Resources.warning.png"))
                                }), new TableCell(new Label                   {
                                    Text = "Classificatore non individuato.\n" +
                                           "Addestramento del classificatore dagli esempi in corso...\n", VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center, TextColor = new Eto.Drawing.Color(1, 1, 1, 1), BackgroundColor = new Eto.Drawing.Color(0, 0, 1, 1), Font = Fonts.Monospace(15f, 0, 0)
                                })) }
                        }
                    };
                    waiting.ShowModalAsync();                      // il dialog di avviso viene mostrato in modo asincrono rispetto all'altra interfaccia

                    try
                    {
                        using (SVM svm = new SVM())
                        {
                            svm.Type = SVM.SvmType.CSvc;
                            svm.SetKernel(SVM.SvmKernelType.Linear);
                            svm.TermCriteria = new MCvTermCriteria((int)1e6, 1e-6);
                            await Task.Run(() =>
                            {
                                for (int i = 0; i < populationSize; i++)
                                {
                                    SkinDetector mySkinDetector = new SkinDetector();

                                    Matrix <float> samples = mySkinDetector.getFeatures(files[i]);

                                    for (int j = 0; j < samples.Cols; j++)
                                    {
                                        trainingMat[i, j] = samples[0, j];
                                    }
                                    if (i < numbpositiveimages)
                                    {
                                        labels[i] = 1;
                                    }
                                    else
                                    {
                                        labels[i] = 0;
                                    }
                                }
                            });

                            Matrix <int> labelsMat = new Matrix <int>(labels);

                            TrainData td = new TrainData(trainingMat, Emgu.CV.ML.MlEnum.DataLayoutType.RowSample, labelsMat);

                            if (svm.TrainAuto(td))
                            {
                                waiting.Close();

                                SaveFileDialog SaveClassifierDialog = new SaveFileDialog {
                                    Title = "Indica il nome del classificatore"
                                };

                                SaveClassifierDialog.Filters.Add(new FileDialogFilter("XML Document", ".xml"));
                                SaveClassifierDialog.CurrentFilter      = SaveClassifierDialog.Filters[0];
                                SaveClassifierDialog.CurrentFilterIndex = 0;

                                bool ExistSameClassifier = true;

                                while (ExistSameClassifier)
                                {
                                    if (SaveClassifierDialog.ShowDialog(null) == DialogResult.Ok)
                                    {
                                        if (File.Exists(SaveClassifierDialog.FileName + ".xml"))
                                        {
                                            ExistSameClassifier = true;
                                            MessageBox.Show("Esiste già un classificatore con questo nome", 0);
                                        }
                                        else
                                        {
                                            ExistSameClassifier = false;
                                            string savefile = SaveClassifierDialog.FileName + ".xml";
                                            svm.Save(savefile);
                                            ClassifierUsedForAnalysis = savefile;
                                        }
                                    }
                                }
                                MessageBox.Show("Addestramento completato. Il classificatore è pronto!", 0);
                            }
                            else
                            {
                                MessageBox.Show("Ooops !\nQualcosa è andato storto,verrà utilizzato il classificatore standard");
                                ClassifierUsedForAnalysis = PathClassifierStandard;
                            }
                        }
                    }
                    catch (Exception e)
                    { Console.WriteLine(e.ToString()); }
                    existClassifier = true;
                }
                else                                               //Caso in cui il classificatore esiste
                {
                    mytab2.ToolTip = "Attendere prego: stiamo elaborando i risultati...";
                    Dialog warning = new Dialog {
                        Title = "", Size = new Eto.Drawing.Size(750, 128), Content = new TableLayout {
                            Rows = { new TableRow(new TableCell(new ImageView {
                                    Image = new Eto.Drawing.Bitmap(System.Reflection.Assembly.GetEntryAssembly().GetManifestResourceStream("pedopornanalyzer.Properties.Resources.warning.png"))
                                }), new TableCell(new Label                   {
                                    Text = "Attendere prego: stiamo elaborando i risultati...", VerticalAlignment = VerticalAlignment.Center, TextAlignment = TextAlignment.Center, TextColor = new Eto.Drawing.Color(1, 1, 1, 1), BackgroundColor = new Eto.Drawing.Color(0, 0, 1, 1), Font = Fonts.Monospace(15f, 0, 0)
                                })) }
                        }
                    };
                    warning.ShowModalAsync();                      // il dialog di avviso viene mostrato in modo asincrono rispetto all'altra interfaccia
                    // Il recupero di tutte le immagini dal dispositivo lo faccio fare ad un altro Task in modo da mantere la UI "viva"
                    await Task.Run(() =>
                    {
                        DiskUtils.GetImagesFromExtension(DriveToClassify);                                      //le immagini vengono recuperate dal lavoro di estrazione di Davide
                        fileImages = DiskUtils.fileimmagine.ToArray();                                          //le immagini recuperate(il loro path in realtà) vengono inserite in un array
                    });

                    warning.Close();                                            // ora che i risultati sono pronti chiudo il dialog di elaborazione dei risultati...
                    mytab2.ToolTip             = "";                            // ...resetto a "vuoto" il tooltip della pagine
                    mytab2.PauseResume.Enabled = true;                          //...abilito il pulsante Pausa/Riprendi.
                    ImageAnalyzed  = 0;                                         //Inizialmente il numero di immagini analizzate è zero
                    Positives      = 0;                                         //Inizialmente il numero di immagini positive è zero
                    Negatives      = 0;                                         //Inizialmente il numero di immagini negative è zero
                    populationSize = 0;                                         //Inizialmente il numero delle immagini da analizzare è zero
                    populationSize = fileImages.Length;                         //Setto il valore del numero delle immagini da analizzare: è pari al numero di elementi dell'array

                    mytab2.progress.MaxValue = populationSize;                  //Setto il valore massimo che la progress bar può assumere:è pari al numero di immagini da analizzare
                    PositiveImages           = new List <string>();             //Inizializzo l'array che dovrà contenere il path delle immagini positive
                    cyclebreak = true;

                    AnalyzerAsync(mytab2);                                                              //Lancio la funzione principale
                }
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// 打开Excel并将DataGridView控件中数据导出到Excel
        /// </summary>
        /// <param name="dgv">DataGridView对象 </param>
        /// <param name="isShowExcle">是否显示Excel界面 </param>
        /// <remarks>
        /// add com "Microsoft Excel 11.0 Object Library"
        /// using Excel=Microsoft.Office.Interop.Excel;
        /// </remarks>
        /// <returns> </returns>
        //public static bool DataGridviewShowToExcel(DataGridView dgv, bool isShowExcle)
        //{
        //    if (dgv.Rows.Count == 0)
        //        return false;
        //    //建立Excel对象
        //    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
        //    excel.Application.Workbooks.Add(true);
        //    excel.Visible = isShowExcle;
        //    //生成字段名称
        //    int colnum = 0;
        //    for (int i = 0; i < dgv.ColumnCount; i++)
        //    {
        //        if (dgv.Columns[i].Visible)
        //        {
        //            excel.Cells[1, colnum + 1] = dgv.Columns[i].HeaderText;
        //            colnum++;
        //        }
        //    }
        //    //填充数据
        //    for (int i = 0; i < dgv.RowCount; i++)
        //    {
        //        for (int j = 0; j < dgv.ColumnCount; j++)
        //        {
        //            if (dgv[j, i].ValueType == typeof(string))
        //            {
        //                excel.Cells[i + 2, j + 1] = "'" + dgv[j, i].Value.ToString();
        //            }
        //            else
        //            {
        //                excel.Cells[i + 2, j + 1] = dgv[j, i].Value.ToString();
        //            }
        //        }
        //    }
        //    return true;
        //}
        #endregion

        #region DateGridView导出到csv格式的Excel
        /// <summary>
        /// 常用方法,列之间加/t,一行一行输出,此文件其实是csv文件,不过默认可以当成Excel打开。
        /// </summary>
        /// <remarks>
        /// using System.IO;
        /// </remarks>
        /// <param name="dgv"></param>
        public static void DataGridViewToExcel(DataGridView dgv)
        {
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Filter           = "Execl files (*.xls)|*.xls";
            dlg.FilterIndex      = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt     = true;
            dlg.Title            = "保存为Excel文件";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw          = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string       columnTitle = "";
                try
                {
                    //写入列标题
                    for (int i = 0; i < dgv.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            columnTitle += "/t";
                        }
                        columnTitle += dgv.Columns[i].HeaderText;
                    }
                    sw.WriteLine(columnTitle);

                    //写入列内容
                    for (int j = 0; j < dgv.Rows.Count; j++)
                    {
                        string columnValue = "";
                        for (int k = 0; k < dgv.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                columnValue += "/t";
                            }
                            if (dgv.Rows[j].Cells[k].Value == null)
                            {
                                columnValue += "";
                            }
                            else
                            {
                                columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                            }
                        }
                        sw.WriteLine(columnValue);
                    }
                    sw.Close();
                    myStream.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }
        }
Ejemplo n.º 39
0
        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "Excel | *.xls";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string fileName = sfd.FileName;

                Microsoft.Office.Interop.Excel.Workbook  workBook = Main.ExcelApp.Workbooks.Add(); // 워크북 추가
                Microsoft.Office.Interop.Excel.Worksheet workSheet;

                for (int i = 0; i < lsvPay.Items.Count; i++)
                {
                    string name = lsvPay.Items[i].SubItems[0].Text;
                    if (workBook.Worksheets.Count <= i)
                    {
                        workBook.Worksheets.Add();
                    }

                    workSheet      = workBook.Worksheets.get_Item(1) as Microsoft.Office.Interop.Excel.Worksheet;
                    workSheet.Name = name;


                    string           query = "SELECT contract.ID, contract.inputdate, contract.recevicedocument, contract.shopname, contract.type, contract.registrationnumber, contract.phonenumber, contract.address, contract.representative, contract.salerpersion, contract.storeid, contract.offerdb, contract.dbmanager, contract.iscontract, contract.content FROM contract, paytable where contract.storeid = paytable.storeid and paytable.avablecalc = 'O' and contract.salerpersion = '" + name + "'";
                    DataSet          ds    = new DataSet();
                    OleDbDataAdapter adp   = new OleDbDataAdapter(query, Main.conn);
                    adp.Fill(ds);

                    workSheet.Cells[1, 1] = lsvPay.Columns[0].Text;
                    workSheet.Cells[1, 2] = lsvPay.Columns[1].Text;
                    workSheet.Cells[1, 3] = lsvPay.Columns[2].Text;
                    workSheet.Cells[1, 4] = lsvPay.Columns[3].Text;
                    workSheet.Cells[2, 1] = lsvPay.Items[i].SubItems[0].Text;
                    workSheet.Cells[2, 2] = lsvPay.Items[i].SubItems[1].Text;
                    workSheet.Cells[2, 3] = lsvPay.Items[i].SubItems[2].Text;
                    workSheet.Cells[2, 4] = lsvPay.Items[i].SubItems[3].Text;


                    int colIndex = 1;
                    foreach (ColumnHeader col in lsvPayList.Columns)
                    {
                        workSheet.Cells[3, colIndex] = col.Text;
                        colIndex++;
                    }

                    int rowIndex = 4;
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        colIndex = 1;
                        foreach (object colItem in row.ItemArray)
                        {
                            string str = colItem.ToString();
                            workSheet.Cells[rowIndex, colIndex] = str;
                            colIndex++;
                        }
                        rowIndex++;
                    }
                }
                workBook.SaveAs(fileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
                workBook.Close(true);
                MessageBox.Show("저장 완료");
            }
        }
Ejemplo n.º 40
0
        private void saveObjFlowxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog()
            {
                Title            = "Save ObjFlow.xml",
                InitialDirectory = @"C:\Users\User\Desktop",
                Filter           = "xml file|*.xml"
            };

            if (saveFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            List <ObjFlow_Xml.Value_Array> ValueAry = new List <ObjFlow_Xml.Value_Array>();

            for (int Count = 0; Count < dataGridView1.RowCount; Count++)
            {
                #region Item
                List <int> Item_Val_List = new List <int>();
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[3].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[4].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[5].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[6].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[7].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[8].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[9].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[10].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[11].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[12].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[13].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[14].Value.ToString()));
                Item_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[15].Value.ToString()));

                List <ObjFlow_Xml.Item.Item_Value_Array> Clip_Value_List = new List <ObjFlow_Xml.Item.Item_Value_Array>();
                for (int ItemValueCount = 0; ItemValueCount < Item_Val_List.Count; ItemValueCount++)
                {
                    ObjFlow_Xml.Item.Item_Value_Array IVA = new ObjFlow_Xml.Item.Item_Value_Array()
                    {
                        ItemVal = Item_Val_List[ItemValueCount]
                    };

                    Clip_Value_List.Add(IVA);
                }
                #endregion

                #region ItemObj
                List <int> ItemObj_Val_List = new List <int>();
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[16].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[17].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[18].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[19].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[20].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[21].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[22].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[23].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[24].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[25].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[26].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[27].Value.ToString()));
                ItemObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[28].Value.ToString()));

                List <ObjFlow_Xml.ItemObj.ItemObj_Value_Array> ItemObj_Value_List = new List <ObjFlow_Xml.ItemObj.ItemObj_Value_Array>();
                for (int ItemObjValueCount = 0; ItemObjValueCount < ItemObj_Val_List.Count; ItemObjValueCount++)
                {
                    ObjFlow_Xml.ItemObj.ItemObj_Value_Array ItemObjValAry = new ObjFlow_Xml.ItemObj.ItemObj_Value_Array()
                    {
                        ItemObjVal = ItemObj_Val_List[ItemObjValueCount]
                    };

                    ItemObj_Value_List.Add(ItemObjValAry);
                }
                #endregion

                #region Kart
                List <int> Kart_Val_List = new List <int>();
                Kart_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[29].Value.ToString()));
                Kart_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[30].Value.ToString()));
                Kart_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[31].Value.ToString()));
                Kart_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[32].Value.ToString()));

                List <ObjFlow_Xml.Kart.Kart_Value_Array> Kart_Value_List = new List <ObjFlow_Xml.Kart.Kart_Value_Array>();
                for (int KartValueCount = 0; KartValueCount < Kart_Val_List.Count; KartValueCount++)
                {
                    ObjFlow_Xml.Kart.Kart_Value_Array KartValAry = new ObjFlow_Xml.Kart.Kart_Value_Array
                    {
                        KartVal = Kart_Val_List[KartValueCount]
                    };

                    Kart_Value_List.Add(KartValAry);
                }
                #endregion

                #region KartObj
                List <int> KartObj_Val_List = new List <int>();
                KartObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[33].Value.ToString()));
                KartObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[34].Value.ToString()));
                KartObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[35].Value.ToString()));
                KartObj_Val_List.Add(int.Parse(dataGridView2.Rows[Count].Cells[36].Value.ToString()));

                List <ObjFlow_Xml.KartObj.KartObj_Value_Array> KartObj_Value_List = new List <ObjFlow_Xml.KartObj.KartObj_Value_Array>();
                for (int KartObjValueCount = 0; KartObjValueCount < KartObj_Val_List.Count; KartObjValueCount++)
                {
                    ObjFlow_Xml.KartObj.KartObj_Value_Array KartObjValAry = new ObjFlow_Xml.KartObj.KartObj_Value_Array
                    {
                        KartObjVal = KartObj_Val_List[KartObjValueCount]
                    };

                    KartObj_Value_List.Add(KartObjValAry);
                }
                #endregion

                #region ResName
                List <string> ResName_Val_List = new List <string>();
                ResName_Val_List.Add(dataGridView2.Rows[Count].Cells[38].Value.ToString());

                List <ObjFlow_Xml.ResName.ResName_Value_Array> ResName_Value_List = new List <ObjFlow_Xml.ResName.ResName_Value_Array>();
                for (int ResNameValueCount = 0; ResNameValueCount < ResName_Val_List.Count; ResNameValueCount++)
                {
                    ObjFlow_Xml.ResName.ResName_Value_Array ResNameValAry = new ObjFlow_Xml.ResName.ResName_Value_Array
                    {
                        ResNameStr_Value_Type = "string",
                        ResNameStr            = ResName_Val_List[ResNameValueCount]
                    };

                    ResName_Value_List.Add(ResNameValAry);
                }
                #endregion

                #region ObjFlow_ROOT
                ObjFlow_Xml.Value_Array value_Array = new ObjFlow_Xml.Value_Array
                {
                    AiReact         = int.Parse(dataGridView1.Rows[Count].Cells[0].Value.ToString()),
                    CalcCut         = Convert.ToBoolean(((DataGridViewCheckBoxCell)dataGridView1.Rows[Count].Cells[1]).Value),
                    Clip            = Convert.ToBoolean(((DataGridViewCheckBoxCell)dataGridView1.Rows[Count].Cells[2]).Value),
                    ClipRadius      = dataGridView1.Rows[Count].Cells[3].Value.ToString(),
                    ColOffsetY      = dataGridView1.Rows[Count].Cells[4].Value.ToString(),
                    ColShape        = int.Parse(dataGridView1.Rows[Count].Cells[5].Value.ToString()),
                    DemoCameraCheck = Convert.ToBoolean(((DataGridViewCheckBoxCell)dataGridView1.Rows[Count].Cells[6]).Value),

                    LightSetting   = int.Parse(dataGridView1.Rows[Count].Cells[7].Value.ToString()),
                    Lod1           = dataGridView1.Rows[Count].Cells[8].Value.ToString(),
                    Lod2           = dataGridView1.Rows[Count].Cells[9].Value.ToString(),
                    Lod_NoDisp     = dataGridView1.Rows[Count].Cells[10].Value.ToString(),
                    MgrId          = int.Parse(dataGridView1.Rows[Count].Cells[11].Value.ToString()),
                    ModelDraw      = int.Parse(dataGridView1.Rows[Count].Cells[12].Value.ToString()),
                    ModelEffNo     = int.Parse(dataGridView1.Rows[Count].Cells[13].Value.ToString()),
                    MoveBeforeSync = Convert.ToBoolean(((DataGridViewCheckBoxCell)dataGridView1.Rows[Count].Cells[14]).Value),
                    NotCreate      = Convert.ToBoolean(((DataGridViewCheckBoxCell)dataGridView1.Rows[Count].Cells[15]).Value),
                    ObjId          = int.Parse(dataGridView1.Rows[Count].Cells[16].Value.ToString()),
                    Offset         = dataGridView1.Rows[Count].Cells[17].Value.ToString(),
                    Origin         = int.Parse(dataGridView1.Rows[Count].Cells[18].Value.ToString()),
                    PackunEat      = Convert.ToBoolean(((DataGridViewCheckBoxCell)dataGridView1.Rows[Count].Cells[19]).Value),
                    PathType       = int.Parse(dataGridView1.Rows[Count].Cells[20].Value.ToString()),
                    PylonReact     = int.Parse(dataGridView1.Rows[Count].Cells[21].Value.ToString()),
                    VR             = Convert.ToBoolean(((DataGridViewCheckBoxCell)dataGridView1.Rows[Count].Cells[22]).Value),
                    ColSize        = new ObjFlow_Xml.ColSize_Val
                    {
                        X_Val = dataGridView2.Rows[Count].Cells[0].Value.ToString(),
                        Y_Val = dataGridView2.Rows[Count].Cells[1].Value.ToString(),
                        Z_Val = dataGridView2.Rows[Count].Cells[2].Value.ToString()
                    },
                    Items = new ObjFlow_Xml.Item
                    {
                        Item_Value_Type = "array",
                        Item_Value_Ary  = Clip_Value_List
                    },
                    ItemObjs = new ObjFlow_Xml.ItemObj
                    {
                        ItemObj_Value_Type = "array",
                        ItemObj_Value_Ary  = ItemObj_Value_List
                    },
                    Karts = new ObjFlow_Xml.Kart
                    {
                        Kart_Value_Type = "array",
                        Kart_Value_Ary  = Kart_Value_List
                    },
                    KartObjs = new ObjFlow_Xml.KartObj
                    {
                        KartObj_Value_Type = "array",
                        KartObj_Value_Ary  = KartObj_Value_List
                    },
                    Label = new ObjFlow_Xml.Label
                    {
                        Label_Type   = "string",
                        Label_String = dataGridView2.Rows[Count].Cells[37].Value.ToString()
                    },
                    ResNames = new ObjFlow_Xml.ResName
                    {
                        ResName_Value_Type = "string",
                        ResName_Value_Ary  = ResName_Value_List
                    }
                };
                #endregion

                ValueAry.Add(value_Array);
            }

            ObjFlow_Xml.ObjFlow_Read_ROOT YAMLROOT = new ObjFlow_Xml.ObjFlow_Read_ROOT
            {
                yaml_Type    = "array",
                Value_Arrays = ValueAry
            };

            //Delete Namespaces
            var xns = new XmlSerializerNamespaces();
            xns.Add(string.Empty, string.Empty);

            System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(ObjFlow_Xml.ObjFlow_Read_ROOT));
            System.IO.StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, false, new System.Text.UTF8Encoding(false));
            serializer.Serialize(sw, YAMLROOT, xns);
            sw.Close();
        }
Ejemplo n.º 41
0
        private void ReceiveMessage(Socket socket)
        {
            string msg;

            server = txtIP.Text.Trim() + ":" + txtPort.Text.Trim();


            //5 处理客户端连接请求
            while (true)
            {
                var buffer = new byte[1024 * 1024 * 2]; //缓冲区大小
                var length = -1;
                try
                {
                    //Receive方法:接收数据到buffer,并返回数据长度。buffer是byte[].
                    length = socketClient.Receive(buffer);
                }
                catch (Exception e)
                {
                    AddLog(0, "服务器断开连接 " + e.Message);
                    break;
                }

                if (length > 0)
                {
                    //处理接收数据
                    var type = (MessageType)buffer[0];
                    switch (type)
                    {
                    case MessageType.ASCII:
                        msg = Encoding.ASCII.GetString(buffer, 1, length - 1);
                        AddLog(0, server + ": " + msg);
                        break;

                    case MessageType.UTF8:
                        msg = Encoding.UTF8.GetString(buffer, 1, length - 1);
                        AddLog(0, server + ": " + msg);
                        break;

                    case MessageType.Hex:
                        msg = HexGetString(buffer, 1, length - 1);
                        AddLog(0, server + ": " + msg);

                        break;

                    case MessageType.File:
                        Invoke(new Action(() =>
                        {
                            var sfd    = new SaveFileDialog();
                            sfd.Filter =
                                "txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|xlsx files(*.xlsx)|*.xlsx|All files(*.*)|*.*";
                            if (sfd.ShowDialog() == DialogResult.OK)
                            {
                                var fileSavePath = sfd.FileName;
                                using (var fs = new FileStream(fileSavePath, FileMode.Create))
                                {
                                    fs.Write(buffer, 1, length - 1);
                                }

                                AddLog(0, "文件保存成功:" + fileSavePath);
                            }
                        }));
                        break;

                    case MessageType.JSON:
                        Invoke(new Action(() =>
                        {
                            var res     = Encoding.Default.GetString(buffer, 1, length);
                            var stuList = JSONHelper.JSONToEntity <List <Student> >(res);
                            new FrmJson(stuList).Show();
                            AddLog(0, "接收JSON对象" + res);
                        }));
                        break;
                    }
                }
                else
                {
                    AddLog(0, "服务器断开连接");
                    break;
                }

//
            }
        }
Ejemplo n.º 42
0
        public void DataToExcel(DataGridView m_DataView)
        {
            SaveFileDialog kk = new SaveFileDialog();

            kk.Title       = "工作量统计" + DateTime.Now.ToString("yyyMMdd");
            kk.Filter      = "EXECL文件(*.xls) |*.xls |所有文件(*.*) |*.*";
            kk.FilterIndex = 1;
            if (kk.ShowDialog() == DialogResult.OK)
            {
                string FileName = kk.FileName;
                if (File.Exists(FileName))
                {
                    File.Delete(FileName);
                }
                FileStream   objFileStream;
                StreamWriter objStreamWriter;
                string       strLine = "";
                objFileStream   = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
                objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
                for (int i = 0; i < m_DataView.Columns.Count; i++)
                {
                    if (m_DataView.Columns[i].Visible == true)
                    {
                        strLine = strLine + m_DataView.Columns[i].HeaderText.ToString() + Convert.ToChar(9);
                    }
                }
                objStreamWriter.WriteLine(strLine);
                strLine = "";

                for (int i = 0; i < m_DataView.Rows.Count; i++)
                {
                    if (m_DataView.Columns[0].Visible == true)
                    {
                        if (m_DataView.Rows[i].Cells[0].Value == null)
                        {
                            strLine = strLine + " " + Convert.ToChar(9);
                        }
                        else
                        {
                            strLine = strLine + m_DataView.Rows[i].Cells[0].Value.ToString() + Convert.ToChar(9);
                        }
                    }
                    for (int j = 1; j < m_DataView.Columns.Count; j++)
                    {
                        if (m_DataView.Columns[j].Visible == true)
                        {
                            if (m_DataView.Rows[i].Cells[j].Value == null)
                            {
                                strLine = strLine + " " + Convert.ToChar(9);
                            }
                            else
                            {
                                string rowstr = "";
                                rowstr = m_DataView.Rows[i].Cells[j].Value.ToString();
                                if (rowstr.IndexOf("\r\n") > 0)
                                {
                                    rowstr = rowstr.Replace("\r\n", " ");
                                }
                                if (rowstr.IndexOf("\t") > 0)
                                {
                                    rowstr = rowstr.Replace("\t", " ");
                                }
                                strLine = strLine + rowstr + Convert.ToChar(9);
                            }
                        }
                    }
                    objStreamWriter.WriteLine(strLine);
                    strLine = "";
                }
                objStreamWriter.Close();
                objFileStream.Close();
                MessageBox.Show(this, "保存EXCEL成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 43
0
        private void dgFilings_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex == -1)
                {
                    return;
                }

                int selectedIndex = dgFilings.CurrentCell.RowIndex;
                int colIndex      = dgFilings.CurrentCell.ColumnIndex;

                if (selectedIndex > -1 && selectedIndex < dgEnvelope.Rows.Count && colIndex == 0)
                {
                    // Get filing Id to cancel
                    string filingId = Convert.ToString(dgFilings.Rows[selectedIndex].Cells[4].Value);

                    if (MessageBox.Show("Are you sure to cancel filings.", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        this.Cursor = Cursors.WaitCursor;
                        LogManager.Trace(String.Format("Envelope Details : Canceling of filing Id- {0} started.", filingId));

                        if (AppConstants.ApiCaller.CancelFiling(filingId.Trim()))
                        {
                            this.Cursor = Cursors.Default;
                            MessageBox.Show("Filing cancelled successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            LoadFilings(this.lblEnvelopeId.Text.Trim());
                        }
                        LogManager.Trace(String.Format("Envelope Details : Cannceling of filing Id -{0} completed.", filingId));
                    }
                }
                if (selectedIndex > -1 && selectedIndex < dgEnvelope.Rows.Count && colIndex == -1)
                {
                    // Get filing Id to download
                    string filingId = Convert.ToString(dgFilings.Rows[selectedIndex].Cells[4].Value);
                    //Download filing

                    string url = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf ";

                    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                    saveFileDialog1.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
                    saveFileDialog1.Title            = "Save Filing File";
                    saveFileDialog1.CheckFileExists  = false;
                    saveFileDialog1.CheckPathExists  = true;
                    saveFileDialog1.DefaultExt       = "pdf";
                    saveFileDialog1.FileName         = "filing.pdf";
                    saveFileDialog1.Filter           = "Filing PDF files (*.pdf)|*.pdf";
                    saveFileDialog1.FilterIndex      = 2;
                    saveFileDialog1.RestoreDirectory = true;
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        string localFileName = saveFileDialog1.FileName;
                        // Download the pdf file and save it local system folder.
                        LogManager.Trace(String.Format("Envelope Details : Downloading filing for Id - {0} started.", filingId));
                        using (WebClient webClient = new WebClient())
                        {
                            webClient.UseDefaultCredentials = true;
                            webClient.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
                            webClient.DownloadFile(new Uri(url), localFileName);
                            MessageBox.Show("Filing downloaded successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }

                        LogManager.Trace(String.Format("Envelope Details : Downloading filing for Id - {0} completed.", FilingId));
                    }
                }

                if (selectedIndex > -1 && selectedIndex < dgEnvelope.Rows.Count && colIndex == 1)
                {
                    // Get filing Id to cancel
                    string filingId = Convert.ToString(dgFilings.Rows[selectedIndex].Cells[4].Value);

                    string url = "https://" + AppConstants.ApiCaller.getEnv() + ".uslegalpro.com/efile/filingdetail/" + filingId;

                    System.Diagnostics.Process.Start(url);
                }
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                LogManager.LogError(ex);
            }
        }
Ejemplo n.º 44
0
        private bool DoAfterCaptureJobs()
        {
            if (tempImage == null)
            {
                return(true);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AddImageEffects))
            {
                tempImage = TaskHelpers.AddImageEffects(tempImage, Info.TaskSettings.ImageSettingsReference);

                if (tempImage == null)
                {
                    DebugHelper.WriteLine("Error: Applying image effects resulted empty image.");
                    return(false);
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.AnnotateImage))
            {
                tempImage = TaskHelpers.AnnotateImage(tempImage, Info.FileName, Info.TaskSettings, true);

                if (tempImage == null)
                {
                    return(false);
                }
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.CopyImageToClipboard))
            {
                ClipboardHelpers.CopyImage(tempImage);
                DebugHelper.WriteLine("Image copied to clipboard.");
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SendImageToPrinter))
            {
                TaskHelpers.PrintImage(tempImage);
            }

            if (Info.TaskSettings.AfterCaptureJob.HasFlagAny(AfterCaptureTasks.SaveImageToFile, AfterCaptureTasks.SaveImageToFileWithDialog, AfterCaptureTasks.DoOCR,
                                                             AfterCaptureTasks.UploadImageToHost))
            {
                using (tempImage)
                {
                    ImageData imageData = TaskHelpers.PrepareImage(tempImage, Info.TaskSettings);
                    Data          = imageData.ImageStream;
                    Info.FileName = Path.ChangeExtension(Info.FileName, imageData.ImageFormat.GetDescription());

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFile))
                    {
                        string filePath = TaskHelpers.CheckFilePath(Info.TaskSettings.CaptureFolder, Info.FileName, Info.TaskSettings);

                        if (!string.IsNullOrEmpty(filePath))
                        {
                            Info.FilePath = filePath;
                            imageData.Write(Info.FilePath);
                            DebugHelper.WriteLine("Image saved to file: " + Info.FilePath);
                        }
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveImageToFileWithDialog))
                    {
                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            bool imageSaved;

                            do
                            {
                                if (string.IsNullOrEmpty(lastSaveAsFolder) || !Directory.Exists(lastSaveAsFolder))
                                {
                                    lastSaveAsFolder = Info.TaskSettings.CaptureFolder;
                                }

                                sfd.InitialDirectory = lastSaveAsFolder;
                                sfd.FileName         = Info.FileName;
                                sfd.DefaultExt       = Path.GetExtension(Info.FileName).Substring(1);
                                sfd.Filter           = string.Format("*{0}|*{0}|All files (*.*)|*.*", Path.GetExtension(Info.FileName));
                                sfd.Title            = Resources.UploadTask_DoAfterCaptureJobs_Choose_a_folder_to_save + " " + Path.GetFileName(Info.FileName);

                                if (sfd.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(sfd.FileName))
                                {
                                    Info.FilePath    = sfd.FileName;
                                    lastSaveAsFolder = Path.GetDirectoryName(Info.FilePath);
                                    imageSaved       = imageData.Write(Info.FilePath);

                                    if (imageSaved)
                                    {
                                        DebugHelper.WriteLine("Image saved to file with dialog: " + Info.FilePath);
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            } while (!imageSaved);
                        }
                    }

                    if (Info.TaskSettings.AfterCaptureJob.HasFlag(AfterCaptureTasks.SaveThumbnailImageToFile))
                    {
                        string thumbnailFilename, thumbnailFolder;

                        if (!string.IsNullOrEmpty(Info.FilePath))
                        {
                            thumbnailFilename = Path.GetFileName(Info.FilePath);
                            thumbnailFolder   = Path.GetDirectoryName(Info.FilePath);
                        }
                        else
                        {
                            thumbnailFilename = Info.FileName;
                            thumbnailFolder   = Info.TaskSettings.CaptureFolder;
                        }

                        Info.ThumbnailFilePath = TaskHelpers.CreateThumbnail(tempImage, thumbnailFolder, thumbnailFilename, Info.TaskSettings);

                        if (!string.IsNullOrEmpty(Info.ThumbnailFilePath))
                        {
                            DebugHelper.WriteLine("Thumbnail saved to file: " + Info.ThumbnailFilePath);
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 45
0
        public static int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory;
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;
            IWorkbook workbook = null;
            FileStream fs = null;
            // bool disposed;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "xlsx|*.xls|xlsx|*.xlsx";
            sfd.Title = "Excel文件导出";
            string fileName = path + DateTime.Now.ToShortDateString().Replace("/","-")+ ".xlsx";

          

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook();
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                    ICellStyle style = workbook.CreateCellStyle();
                    style.FillPattern = FillPattern.SolidForeground;

                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);

                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel
                workbook.Close();
                fs.Close();
                System.Diagnostics.Process[] Proc = System.Diagnostics.Process.GetProcessesByName("");
               
                return 0;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }
Ejemplo n.º 46
0
 private void InitializeComponent()
 {
     this.components          = new System.ComponentModel.Container();
     this.titleLabel          = new System.Windows.Forms.Label();
     this.copyrightLabel      = new System.Windows.Forms.Label();
     this.closeButton         = new System.Windows.Forms.Button();
     this.minimizeButton      = new System.Windows.Forms.Button();
     this.helpButton          = new System.Windows.Forms.Button();
     this.mapContextMenu      = new System.Windows.Forms.ContextMenuStrip(this.components);
     this.addDeviceButton     = new System.Windows.Forms.ToolStripMenuItem();
     this.editDeviceButton    = new System.Windows.Forms.ToolStripMenuItem();
     this.deleteDeviceButton  = new System.Windows.Forms.ToolStripMenuItem();
     this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
     this.importButton        = new System.Windows.Forms.ToolStripMenuItem();
     this.exportButton        = new System.Windows.Forms.ToolStripMenuItem();
     this.statusLabel         = new System.Windows.Forms.Label();
     this.exportDialog        = new System.Windows.Forms.SaveFileDialog();
     this.importDialog        = new System.Windows.Forms.OpenFileDialog();
     this.mapContextMenu.SuspendLayout();
     this.SuspendLayout();
     //
     // titleLabel
     //
     this.titleLabel.AutoSize = true;
     this.titleLabel.Font     = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.titleLabel.Location = new System.Drawing.Point(10, 6);
     this.titleLabel.Margin   = new System.Windows.Forms.Padding(2, 0, 2, 0);
     this.titleLabel.Name     = "titleLabel";
     this.titleLabel.Size     = new System.Drawing.Size(151, 20);
     this.titleLabel.TabIndex = 0;
     this.titleLabel.Text     = "Ping Monitor V1.2";
     //
     // copyrightLabel
     //
     this.copyrightLabel.AutoSize = true;
     this.copyrightLabel.Font     = new System.Drawing.Font("Microsoft Sans Serif", 7F);
     this.copyrightLabel.Location = new System.Drawing.Point(165, 13);
     this.copyrightLabel.Margin   = new System.Windows.Forms.Padding(2, 0, 2, 0);
     this.copyrightLabel.Name     = "copyrightLabel";
     this.copyrightLabel.Size     = new System.Drawing.Size(128, 13);
     this.copyrightLabel.TabIndex = 1;
     this.copyrightLabel.Text     = "(© Markus Zechner, 2019)";
     //
     // closeButton
     //
     this.closeButton.Anchor    = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.closeButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.closeButton.Font      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.closeButton.Location  = new System.Drawing.Point(1883, 12);
     this.closeButton.Name      = "closeButton";
     this.closeButton.Size      = new System.Drawing.Size(25, 25);
     this.closeButton.TabIndex  = 2;
     this.closeButton.Text      = "X";
     this.closeButton.UseVisualStyleBackColor = true;
     this.closeButton.Click += new System.EventHandler(this.onClose);
     //
     // minimizeButton
     //
     this.minimizeButton.Anchor    = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.minimizeButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.minimizeButton.Font      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.minimizeButton.Location  = new System.Drawing.Point(1852, 12);
     this.minimizeButton.Name      = "minimizeButton";
     this.minimizeButton.Size      = new System.Drawing.Size(25, 25);
     this.minimizeButton.TabIndex  = 3;
     this.minimizeButton.Text      = "_";
     this.minimizeButton.UseVisualStyleBackColor = true;
     this.minimizeButton.Click += new System.EventHandler(this.onMinimize);
     //
     // helpButton
     //
     this.helpButton.Anchor    = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.helpButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
     this.helpButton.Font      = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
     this.helpButton.Location  = new System.Drawing.Point(1821, 12);
     this.helpButton.Name      = "helpButton";
     this.helpButton.Size      = new System.Drawing.Size(25, 25);
     this.helpButton.TabIndex  = 4;
     this.helpButton.Text      = "?";
     this.helpButton.UseVisualStyleBackColor = true;
     this.helpButton.Click += new System.EventHandler(this.onHelp);
     //
     // mapContextMenu
     //
     this.mapContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
         this.addDeviceButton,
         this.editDeviceButton,
         this.deleteDeviceButton,
         this.toolStripSeparator1,
         this.importButton,
         this.exportButton
     });
     this.mapContextMenu.Name = "mapContextMenu";
     this.mapContextMenu.Size = new System.Drawing.Size(170, 120);
     //
     // addDeviceButton
     //
     this.addDeviceButton.Name   = "addDeviceButton";
     this.addDeviceButton.Size   = new System.Drawing.Size(169, 22);
     this.addDeviceButton.Text   = "Add Device...";
     this.addDeviceButton.Click += new System.EventHandler(this.onAddDevice);
     //
     // editDeviceButton
     //
     this.editDeviceButton.Enabled = false;
     this.editDeviceButton.Name    = "editDeviceButton";
     this.editDeviceButton.Size    = new System.Drawing.Size(169, 22);
     this.editDeviceButton.Text    = "Edit...";
     this.editDeviceButton.Click  += new System.EventHandler(this.onEditDevice);
     //
     // deleteDeviceButton
     //
     this.deleteDeviceButton.Enabled = false;
     this.deleteDeviceButton.Name    = "deleteDeviceButton";
     this.deleteDeviceButton.Size    = new System.Drawing.Size(169, 22);
     this.deleteDeviceButton.Text    = "Delete";
     this.deleteDeviceButton.Click  += new System.EventHandler(this.onDeleteDevice);
     //
     // toolStripSeparator1
     //
     this.toolStripSeparator1.Name = "toolStripSeparator1";
     this.toolStripSeparator1.Size = new System.Drawing.Size(166, 6);
     //
     // importButton
     //
     this.importButton.Name   = "importButton";
     this.importButton.Size   = new System.Drawing.Size(169, 22);
     this.importButton.Text   = "Import from File...";
     this.importButton.Click += new System.EventHandler(this.onImport);
     //
     // exportButton
     //
     this.exportButton.Enabled = false;
     this.exportButton.Name    = "exportButton";
     this.exportButton.Size    = new System.Drawing.Size(169, 22);
     this.exportButton.Text    = "Export to File...";
     this.exportButton.Click  += new System.EventHandler(this.onExport);
     //
     // statusLabel
     //
     this.statusLabel.Anchor   = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
     this.statusLabel.AutoSize = true;
     this.statusLabel.Font     = new System.Drawing.Font("Microsoft Sans Serif", 7F);
     this.statusLabel.Location = new System.Drawing.Point(1672, 19);
     this.statusLabel.Margin   = new System.Windows.Forms.Padding(2, 0, 2, 0);
     this.statusLabel.Name     = "statusLabel";
     this.statusLabel.Size     = new System.Drawing.Size(144, 13);
     this.statusLabel.TabIndex = 5;
     this.statusLabel.Text     = "Waiting for Threads to close...";
     this.statusLabel.Visible  = false;
     //
     // exportDialog
     //
     this.exportDialog.DefaultExt = "pmc";
     this.exportDialog.FileName   = "config.pmc";
     this.exportDialog.Filter     = "PingMonitor Configuration Files|*.pmc";
     this.exportDialog.Title      = "Export Configuration";
     //
     // importDialog
     //
     this.importDialog.DefaultExt = "pmc";
     this.importDialog.Filter     = "PingMonitor Configuration Files|*.pmc";
     this.importDialog.Title      = "Import Configuration";
     //
     // MainForm
     //
     this.AutoScaleDimensions = new System.Drawing.SizeF(5F, 9F);
     this.AutoScaleMode       = System.Windows.Forms.AutoScaleMode.Font;
     this.BackColor           = System.Drawing.Color.FromArgb(((int)(((byte)(20)))), ((int)(((byte)(20)))), ((int)(((byte)(20)))));
     this.ClientSize          = new System.Drawing.Size(1920, 1061);
     this.Controls.Add(this.statusLabel);
     this.Controls.Add(this.helpButton);
     this.Controls.Add(this.minimizeButton);
     this.Controls.Add(this.closeButton);
     this.Controls.Add(this.copyrightLabel);
     this.Controls.Add(this.titleLabel);
     this.Font            = new System.Drawing.Font("Microsoft Sans Serif", 6F);
     this.ForeColor       = System.Drawing.Color.White;
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     this.Margin          = new System.Windows.Forms.Padding(2);
     this.Name            = "MainForm";
     this.StartPosition   = System.Windows.Forms.FormStartPosition.CenterScreen;
     this.Text            = "Ping Monitor";
     this.Shown          += new System.EventHandler(this.onShow);
     this.Paint          += new System.Windows.Forms.PaintEventHandler(this.onPaint);
     this.DoubleClick    += new System.EventHandler(this.onDoubleClick);
     this.MouseClick     += new System.Windows.Forms.MouseEventHandler(this.onClick);
     this.MouseDown      += new System.Windows.Forms.MouseEventHandler(this.onMouseDown);
     this.MouseMove      += new System.Windows.Forms.MouseEventHandler(this.onMouseMove);
     this.MouseUp        += new System.Windows.Forms.MouseEventHandler(this.onMouseUp);
     this.mapContextMenu.ResumeLayout(false);
     this.ResumeLayout(false);
     this.PerformLayout();
 }
Ejemplo n.º 47
0
        public void savexml(int r, int c)
        {
            string         loc  = "";
            SaveFileDialog open = new SaveFileDialog();

            if (open.ShowDialog() == DialogResult.OK)
            {
                loc = open.FileName;
            }

            Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            Excel.Workbook    xlWorkBook;
            Excel._Worksheet  xlWorkSheet;
            object            misValue = System.Reflection.Missing.Value;

            xlWorkBook  = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);



            int Count = 0;

            char[] ab = inputTextBox.Text.ToCharArray();
            // xlWorkSheet.Cells[1,1]="Sheet 2 Content";
            for (int ii = 0; ii <= (inputTextBox.Text.Length) - 1; ii++)
            {
                if (ab[ii] == ' ')
                {
                    Count = Count + 1;
                }
            }
            //MessageBox.Show("count is" + Count + "Length of Plain Text" + (textBox2.Text.Length) + "Contents" + textBox2.Text);


            int row = r;
            int col = c;
            //MessageBox.Show("row=" + row + "column" + col);
            int    x = 0;
            string a = "";

            for (int i = 1; i <= row; i++)
            {
                for (int j = 1; j <= col; j++)
                {
                    while (x < (inputTextBox.Text.Length))
                    {
                        if (ab[x] == ' ')
                        {
                            xlWorkSheet.Cells[i, j] = a;
                            a = null;
                            x++;
                            break;
                        }
                        else
                        {
                            a = a + ab[x];
                            x++;
                        }
                    }
                }
            }



            xlWorkBook.SaveAs(loc + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet);
                xlWorkSheet = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Exception Occured While  Releasing Object" + ex.ToString());
            }
            //    MessageBox.Show("XML file is saved");
        }
Ejemplo n.º 48
0
        private void button1_Click(object sender, EventArgs e)
        {
            //SAVE FILE
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "*.xml|*.xml";
            
            //LOAD FILE
            if (dialog.ShowDialog() == DialogResult.OK)
            using( FileStream fs = new FileStream(dialog.FileName, FileMode.Create, FileAccess.Write))
            using (XmlTextWriter writer = new XmlTextWriter(fs, Encoding.Unicode))
            {

                writer.Indentation = 1;
                writer.IndentChar = '\t';
                writer.Formatting = Formatting.Indented;

                writer.WriteStartDocument();

                writer.WriteStartElement("Inventory");

                MySqlCommand command = new MySqlCommand("SELECT `ContainerMaxStorage`,`Container` FROM `inventory` WHERE `CharId`=?CharId", conn);
                command.Parameters.AddWithValue("CharId", uint.Parse(textBox1.Text, NumberFormatInfo.InvariantInfo));

                MySqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess);
                while (reader.Read())
                {

                    byte MaxInventoryStorage = reader.GetByte(0);
                    byte[] buffer2 = new byte[4];
                    reader.GetBytes(1, 0, buffer2, 0, 4);
                    uint count = BitConverter.ToUInt32(buffer2, 0);

                    byte[] buffer = new byte[67];
                    int offset = 4;
                    for (int i = 0; i < count; i++)
                    {
                        //READ IT CHUNKED
                        reader.GetBytes(1, offset, buffer, 0, 67);
                        writer.WriteStartElement("Item");

                        //WRITES THE ITEM ID
                        writer.WriteStartElement("ItemId");
                        writer.WriteValue(BitConverter.ToUInt32(buffer, 0));
                        writer.WriteEndElement();

                        //WRITES THE DURABILITY OF THE ITEM
                        writer.WriteStartElement("Durability");
                        writer.WriteValue(BitConverter.ToUInt16(buffer, 51));
                        writer.WriteEndElement();

                        writer.WriteEndElement();
                        offset += 67;
                    }
                }

                reader.Close();

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }
Ejemplo n.º 49
0
        /// <summary>
        /// Create a Critter, put them into Career Mode, link them, and open the newly-created Critter.
        /// </summary>
        /// <param name="strCritterName">Name of the Critter's Metatype.</param>
        /// <param name="intForce">Critter's Force.</param>
        private void CreateCritter(string strCritterName, int intForce)
        {
            // The Critter should use the same settings file as the character.
            Character objCharacter = new Character();

            objCharacter.SettingsFile = _objSpirit.CharacterObject.SettingsFile;

            // Override the defaults for the setting.
            objCharacter.IgnoreRules = true;
            objCharacter.IsCritter   = true;
            objCharacter.BuildMethod = CharacterBuildMethod.Karma;
            objCharacter.BuildPoints = 0;

            if (txtCritterName.Text != string.Empty)
            {
                objCharacter.Name = txtCritterName.Text;
            }

            // Make sure that Running Wild is one of the allowed source books since most of the Critter Powers come from this book.
            bool blnRunningWild = false;

            blnRunningWild = (objCharacter.Options.Books.Contains("RW"));

            if (!blnRunningWild)
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_Main_RunningWild"), LanguageManager.Instance.GetString("MessageTitle_Main_RunningWild"), MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // Ask the user to select a filename for the new character.
            string strForce = LanguageManager.Instance.GetString("String_Force");

            if (_objSpirit.EntityType == SpiritType.Sprite)
            {
                strForce = LanguageManager.Instance.GetString("String_Rating");
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter   = "Chummer5 Files (*.chum5)|*.chum5|All Files (*.*)|*.*";
            saveFileDialog.FileName = strCritterName + " (" + strForce + " " + _objSpirit.Force.ToString() + ").chum5";
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string strFileName = saveFileDialog.FileName;
                objCharacter.FileName = strFileName;
            }
            else
            {
                return;
            }

            // Code from frmMetatype.
            ImprovementManager objImprovementManager = new ImprovementManager(objCharacter);
            XmlDocument        objXmlDocument        = XmlManager.Instance.Load("critters.xml");

            XmlNode objXmlMetatype = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + strCritterName + "\"]");

            // If the Critter could not be found, show an error and get out of here.
            if (objXmlMetatype == null)
            {
                MessageBox.Show(LanguageManager.Instance.GetString("Message_UnknownCritterType").Replace("{0}", strCritterName), LanguageManager.Instance.GetString("MessageTitle_SelectCritterType"), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // Set Metatype information.
            if (strCritterName == "Ally Spirit")
            {
                objCharacter.BOD.AssignLimits(ExpressionToString(objXmlMetatype["bodmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["bodmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["bodaug"].InnerText, intForce, 0));
                objCharacter.AGI.AssignLimits(ExpressionToString(objXmlMetatype["agimin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["agimax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["agiaug"].InnerText, intForce, 0));
                objCharacter.REA.AssignLimits(ExpressionToString(objXmlMetatype["reamin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["reamax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["reaaug"].InnerText, intForce, 0));
                objCharacter.STR.AssignLimits(ExpressionToString(objXmlMetatype["strmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["strmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["straug"].InnerText, intForce, 0));
                objCharacter.CHA.AssignLimits(ExpressionToString(objXmlMetatype["chamin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["chamax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["chaaug"].InnerText, intForce, 0));
                objCharacter.INT.AssignLimits(ExpressionToString(objXmlMetatype["intmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["intmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["intaug"].InnerText, intForce, 0));
                objCharacter.LOG.AssignLimits(ExpressionToString(objXmlMetatype["logmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["logmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["logaug"].InnerText, intForce, 0));
                objCharacter.WIL.AssignLimits(ExpressionToString(objXmlMetatype["wilmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["wilmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["wilaug"].InnerText, intForce, 0));
                objCharacter.INI.AssignLimits(ExpressionToString(objXmlMetatype["inimin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["inimax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["iniaug"].InnerText, intForce, 0));
                objCharacter.MAG.AssignLimits(ExpressionToString(objXmlMetatype["magmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["magmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["magaug"].InnerText, intForce, 0));
                objCharacter.RES.AssignLimits(ExpressionToString(objXmlMetatype["resmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["resmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["resaug"].InnerText, intForce, 0));
                objCharacter.EDG.AssignLimits(ExpressionToString(objXmlMetatype["edgmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["edgmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["edgaug"].InnerText, intForce, 0));
                objCharacter.ESS.AssignLimits(ExpressionToString(objXmlMetatype["essmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essaug"].InnerText, intForce, 0));
            }
            else
            {
                int intMinModifier = -3;
                if (objXmlMetatype["category"].InnerText == "Mutant Critters")
                {
                    intMinModifier = 0;
                }
                objCharacter.BOD.AssignLimits(ExpressionToString(objXmlMetatype["bodmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["bodmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["bodmin"].InnerText, intForce, 3));
                objCharacter.AGI.AssignLimits(ExpressionToString(objXmlMetatype["agimin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["agimin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["agimin"].InnerText, intForce, 3));
                objCharacter.REA.AssignLimits(ExpressionToString(objXmlMetatype["reamin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["reamin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["reamin"].InnerText, intForce, 3));
                objCharacter.STR.AssignLimits(ExpressionToString(objXmlMetatype["strmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["strmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["strmin"].InnerText, intForce, 3));
                objCharacter.CHA.AssignLimits(ExpressionToString(objXmlMetatype["chamin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["chamin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["chamin"].InnerText, intForce, 3));
                objCharacter.INT.AssignLimits(ExpressionToString(objXmlMetatype["intmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["intmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["intmin"].InnerText, intForce, 3));
                objCharacter.LOG.AssignLimits(ExpressionToString(objXmlMetatype["logmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["logmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["logmin"].InnerText, intForce, 3));
                objCharacter.WIL.AssignLimits(ExpressionToString(objXmlMetatype["wilmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["wilmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["wilmin"].InnerText, intForce, 3));
                objCharacter.INI.AssignLimits(ExpressionToString(objXmlMetatype["inimin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["inimax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["iniaug"].InnerText, intForce, 0));
                objCharacter.MAG.AssignLimits(ExpressionToString(objXmlMetatype["magmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["magmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["magmin"].InnerText, intForce, 3));
                objCharacter.RES.AssignLimits(ExpressionToString(objXmlMetatype["resmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["resmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["resmin"].InnerText, intForce, 3));
                objCharacter.EDG.AssignLimits(ExpressionToString(objXmlMetatype["edgmin"].InnerText, intForce, intMinModifier), ExpressionToString(objXmlMetatype["edgmin"].InnerText, intForce, 3), ExpressionToString(objXmlMetatype["edgmin"].InnerText, intForce, 3));
                objCharacter.ESS.AssignLimits(ExpressionToString(objXmlMetatype["essmin"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essmax"].InnerText, intForce, 0), ExpressionToString(objXmlMetatype["essaug"].InnerText, intForce, 0));
            }

            // If we're working with a Critter, set the Attributes to their default values.
            objCharacter.BOD.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["bodmin"].InnerText, intForce, 0));
            objCharacter.AGI.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["agimin"].InnerText, intForce, 0));
            objCharacter.REA.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["reamin"].InnerText, intForce, 0));
            objCharacter.STR.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["strmin"].InnerText, intForce, 0));
            objCharacter.CHA.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["chamin"].InnerText, intForce, 0));
            objCharacter.INT.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["intmin"].InnerText, intForce, 0));
            objCharacter.LOG.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["logmin"].InnerText, intForce, 0));
            objCharacter.WIL.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["wilmin"].InnerText, intForce, 0));
            objCharacter.MAG.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["magmin"].InnerText, intForce, 0));
            objCharacter.RES.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["resmin"].InnerText, intForce, 0));
            objCharacter.EDG.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["edgmin"].InnerText, intForce, 0));
            objCharacter.ESS.Value = Convert.ToInt32(ExpressionToString(objXmlMetatype["essmax"].InnerText, intForce, 0));

            // Sprites can never have Physical Attributes or WIL.
            if (objXmlMetatype["category"].InnerText.EndsWith("Sprite"))
            {
                objCharacter.BOD.AssignLimits("0", "0", "0");
                objCharacter.AGI.AssignLimits("0", "0", "0");
                objCharacter.REA.AssignLimits("0", "0", "0");
                objCharacter.STR.AssignLimits("0", "0", "0");
                objCharacter.WIL.AssignLimits("0", "0", "0");
                objCharacter.INI.MetatypeMinimum = Convert.ToInt32(ExpressionToString(objXmlMetatype["inimax"].InnerText, intForce, 0));
                objCharacter.INI.MetatypeMaximum = Convert.ToInt32(ExpressionToString(objXmlMetatype["inimax"].InnerText, intForce, 0));
            }

            objCharacter.Metatype         = strCritterName;
            objCharacter.MetatypeCategory = objXmlMetatype["category"].InnerText;
            objCharacter.Metavariant      = "";
            objCharacter.MetatypeBP       = 0;

            if (objXmlMetatype["movement"] != null)
            {
                objCharacter.Movement = objXmlMetatype["movement"].InnerText;
            }
            // Load the Qualities file.
            XmlDocument objXmlQualityDocument = XmlManager.Instance.Load("qualities.xml");

            // Determine if the Metatype has any bonuses.
            if (objXmlMetatype.InnerXml.Contains("bonus"))
            {
                objImprovementManager.CreateImprovements(Improvement.ImprovementSource.Metatype, strCritterName, objXmlMetatype.SelectSingleNode("bonus"), false, 1, strCritterName);
            }

            // Create the Qualities that come with the Metatype.
            foreach (XmlNode objXmlQualityItem in objXmlMetatype.SelectNodes("qualities/positive/quality"))
            {
                XmlNode         objXmlQuality  = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQualityItem.InnerText + "\"]");
                TreeNode        objNode        = new TreeNode();
                List <Weapon>   objWeapons     = new List <Weapon>();
                List <TreeNode> objWeaponNodes = new List <TreeNode>();
                Quality         objQuality     = new Quality(objCharacter);
                string          strForceValue  = "";
                if (objXmlQualityItem.Attributes["select"] != null)
                {
                    strForceValue = objXmlQualityItem.Attributes["select"].InnerText;
                }
                QualitySource objSource = new QualitySource();
                objSource = QualitySource.Metatype;
                if (objXmlQualityItem.Attributes["removable"] != null)
                {
                    objSource = QualitySource.MetatypeRemovable;
                }
                objQuality.Create(objXmlQuality, objCharacter, objSource, objNode, objWeapons, objWeaponNodes, strForceValue);
                objCharacter.Qualities.Add(objQuality);

                // Add any created Weapons to the character.
                foreach (Weapon objWeapon in objWeapons)
                {
                    objCharacter.Weapons.Add(objWeapon);
                }
            }
            foreach (XmlNode objXmlQualityItem in objXmlMetatype.SelectNodes("qualities/negative/quality"))
            {
                XmlNode         objXmlQuality  = objXmlQualityDocument.SelectSingleNode("/chummer/qualities/quality[name = \"" + objXmlQualityItem.InnerText + "\"]");
                TreeNode        objNode        = new TreeNode();
                List <Weapon>   objWeapons     = new List <Weapon>();
                List <TreeNode> objWeaponNodes = new List <TreeNode>();
                Quality         objQuality     = new Quality(objCharacter);
                string          strForceValue  = "";
                if (objXmlQualityItem.Attributes["select"] != null)
                {
                    strForceValue = objXmlQualityItem.Attributes["select"].InnerText;
                }
                QualitySource objSource = new QualitySource();
                objSource = QualitySource.Metatype;
                if (objXmlQualityItem.Attributes["removable"] != null)
                {
                    objSource = QualitySource.MetatypeRemovable;
                }
                objQuality.Create(objXmlQuality, objCharacter, objSource, objNode, objWeapons, objWeaponNodes, strForceValue);
                objCharacter.Qualities.Add(objQuality);

                // Add any created Weapons to the character.
                foreach (Weapon objWeapon in objWeapons)
                {
                    objCharacter.Weapons.Add(objWeapon);
                }
            }

            // Add any Critter Powers the Metatype/Critter should have.
            XmlNode objXmlCritter = objXmlDocument.SelectSingleNode("/chummer/metatypes/metatype[name = \"" + objCharacter.Metatype + "\"]");

            objXmlDocument = XmlManager.Instance.Load("critterpowers.xml");
            foreach (XmlNode objXmlPower in objXmlCritter.SelectNodes("powers/power"))
            {
                XmlNode      objXmlCritterPower = objXmlDocument.SelectSingleNode("/chummer/powers/power[name = \"" + objXmlPower.InnerText + "\"]");
                TreeNode     objNode            = new TreeNode();
                CritterPower objPower           = new CritterPower(objCharacter);
                string       strForcedValue     = "";
                int          intRating          = 0;

                if (objXmlPower.Attributes["rating"] != null)
                {
                    intRating = Convert.ToInt32(objXmlPower.Attributes["rating"].InnerText);
                }
                if (objXmlPower.Attributes["select"] != null)
                {
                    strForcedValue = objXmlPower.Attributes["select"].InnerText;
                }

                objPower.Create(objXmlCritterPower, objCharacter, objNode, intRating, strForcedValue);
                objCharacter.CritterPowers.Add(objPower);
            }

            // Set the Skill Ratings for the Critter.
            foreach (XmlNode objXmlSkill in objXmlCritter.SelectNodes("skills/skill"))
            {
                if (objXmlSkill.InnerText.Contains("Exotic"))
                {
                    Skill objExotic = new Skill(objCharacter);
                    objExotic.ExoticSkill = true;
                    objExotic.Attribute   = "AGI";
                    if (objXmlSkill.Attributes["spec"] != null)
                    {
                        SkillSpecialization objSpec = new SkillSpecialization(objXmlSkill.Attributes["spec"].InnerText);
                        objExotic.Specializations.Add(objSpec);
                    }
                    if (Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0)) > 6)
                    {
                        objExotic.RatingMaximum = Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0));
                    }
                    objExotic.Rating = Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0));
                    objExotic.Name   = objXmlSkill.InnerText;
                    objCharacter.Skills.Add(objExotic);
                }
                else
                {
                    foreach (Skill objSkill in objCharacter.Skills)
                    {
                        if (objSkill.Name == objXmlSkill.InnerText)
                        {
                            if (objXmlSkill.Attributes["spec"] != null)
                            {
                                SkillSpecialization objSpec = new SkillSpecialization(objXmlSkill.Attributes["spec"].InnerText);
                                objSkill.Specializations.Add(objSpec);
                            }
                            if (Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0)) > 6)
                            {
                                objSkill.RatingMaximum = Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0));
                            }
                            objSkill.Rating = Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0));
                            break;
                        }
                    }
                }
            }

            // Set the Skill Group Ratings for the Critter.
            foreach (XmlNode objXmlSkill in objXmlCritter.SelectNodes("skills/group"))
            {
                foreach (SkillGroup objSkill in objCharacter.SkillGroups)
                {
                    if (objSkill.Name == objXmlSkill.InnerText)
                    {
                        objSkill.RatingMaximum = Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0));
                        objSkill.Rating        = Convert.ToInt32(ExpressionToString(objXmlSkill.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0));
                        break;
                    }
                }
            }

            // Set the Knowledge Skill Ratings for the Critter.
            foreach (XmlNode objXmlSkill in objXmlCritter.SelectNodes("skills/knowledge"))
            {
                Skill objKnowledge = new Skill(objCharacter);
                objKnowledge.Name           = objXmlSkill.InnerText;
                objKnowledge.KnowledgeSkill = true;
                if (objXmlSkill.Attributes["spec"] != null)
                {
                    SkillSpecialization objSpec = new SkillSpecialization(objXmlSkill.Attributes["spec"].InnerText);
                    objKnowledge.Specializations.Add(objSpec);
                }
                objKnowledge.SkillCategory = objXmlSkill.Attributes["category"].InnerText;
                if (Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText) > 6)
                {
                    objKnowledge.RatingMaximum = Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText);
                }
                objKnowledge.Rating = Convert.ToInt32(objXmlSkill.Attributes["rating"].InnerText);
                objCharacter.Skills.Add(objKnowledge);
            }

            // If this is a Critter with a Force (which dictates their Skill Rating/Maximum Skill Rating), set their Skill Rating Maximums.
            if (intForce > 0)
            {
                int intMaxRating = intForce;
                // Determine the highest Skill Rating the Critter has.
                foreach (Skill objSkill in objCharacter.Skills)
                {
                    if (objSkill.RatingMaximum > intMaxRating)
                    {
                        intMaxRating = objSkill.RatingMaximum;
                    }
                }

                // Now that we know the upper limit, set all of the Skill Rating Maximums to match.
                foreach (Skill objSkill in objCharacter.Skills)
                {
                    objSkill.RatingMaximum = intMaxRating;
                }
                foreach (SkillGroup objGroup in objCharacter.SkillGroups)
                {
                    objGroup.RatingMaximum = intMaxRating;
                }

                // Set the MaxSkillRating for the character so it can be used later when they add new Knowledge Skills or Exotic Skills.
                objCharacter.MaxSkillRating = intMaxRating;
            }

            // Add any Complex Forms the Critter comes with (typically Sprites)
            XmlDocument objXmlProgramDocument = XmlManager.Instance.Load("complexforms.xml");

            foreach (XmlNode objXmlComplexForm in objXmlCritter.SelectNodes("complexforms/complexform"))
            {
                string strForceValue = "";
                if (objXmlComplexForm.Attributes["select"] != null)
                {
                    strForceValue = objXmlComplexForm.Attributes["select"].InnerText;
                }
                XmlNode     objXmlProgram = objXmlProgramDocument.SelectSingleNode("/chummer/complexforms/complexform[name = \"" + objXmlComplexForm.InnerText + "\"]");
                TreeNode    objNode       = new TreeNode();
                ComplexForm objProgram    = new ComplexForm(objCharacter);
                objProgram.Create(objXmlProgram, objCharacter, objNode, strForceValue);
                objCharacter.ComplexForms.Add(objProgram);
            }

            // Add any Gear the Critter comes with (typically Programs for A.I.s)
            XmlDocument objXmlGearDocument = XmlManager.Instance.Load("gear.xml");

            foreach (XmlNode objXmlGear in objXmlCritter.SelectNodes("gears/gear"))
            {
                int intRating = 0;
                if (objXmlGear.Attributes["rating"] != null)
                {
                    intRating = Convert.ToInt32(ExpressionToString(objXmlGear.Attributes["rating"].InnerText, Convert.ToInt32(nudForce.Value), 0));
                }
                string strForceValue = "";
                if (objXmlGear.Attributes["select"] != null)
                {
                    strForceValue = objXmlGear.Attributes["select"].InnerText;
                }
                XmlNode         objXmlGearItem = objXmlGearDocument.SelectSingleNode("/chummer/gears/gear[name = \"" + objXmlGear.InnerText + "\"]");
                TreeNode        objNode        = new TreeNode();
                Gear            objGear        = new Gear(objCharacter);
                List <Weapon>   lstWeapons     = new List <Weapon>();
                List <TreeNode> lstWeaponNodes = new List <TreeNode>();
                objGear.Create(objXmlGearItem, objCharacter, objNode, intRating, lstWeapons, lstWeaponNodes, strForceValue);
                objGear.Cost   = "0";
                objGear.Cost3  = "0";
                objGear.Cost6  = "0";
                objGear.Cost10 = "0";
                objCharacter.Gear.Add(objGear);
            }

            // If this is a Mutant Critter, count up the number of Skill points they start with.
            if (objCharacter.MetatypeCategory == "Mutant Critters")
            {
                foreach (Skill objSkill in objCharacter.Skills)
                {
                    objCharacter.MutantCritterBaseSkills += objSkill.Rating;
                }
            }

            // Add the Unarmed Attack Weapon to the character.
            try
            {
                objXmlDocument = XmlManager.Instance.Load("weapons.xml");
                XmlNode  objXmlWeapon = objXmlDocument.SelectSingleNode("/chummer/weapons/weapon[name = \"Unarmed Attack\"]");
                TreeNode objDummy     = new TreeNode();
                Weapon   objWeapon    = new Weapon(objCharacter);
                objWeapon.Create(objXmlWeapon, objCharacter, objDummy, null, null, null);
                objCharacter.Weapons.Add(objWeapon);
            }
            catch
            {
            }

            objCharacter.Alias   = strCritterName;
            objCharacter.Created = true;
            objCharacter.Save();

            string strOpenFile = objCharacter.FileName;

            objCharacter = null;

            // Link the newly-created Critter to the Spirit.
            _objSpirit.FileName = strOpenFile;
            if (_objSpirit.EntityType == SpiritType.Spirit)
            {
                tipTooltip.SetToolTip(imgLink, LanguageManager.Instance.GetString("Tip_Spirit_OpenFile"));
            }
            else
            {
                tipTooltip.SetToolTip(imgLink, LanguageManager.Instance.GetString("Tip_Sprite_OpenFile"));
            }
            FileNameChanged(this);

            GlobalOptions.Instance.MainForm.LoadCharacter(strOpenFile, true);
        }
Ejemplo n.º 50
0
        private void savePDF_btn_Click(object sender, EventArgs e)
        {
            if (info_dgv.Rows.Count > 0)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter   = "PDF (*.pdf)|*.pdf";
                sfd.FileName = "Output.pdf"; bool fileError = false;
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    if (File.Exists(sfd.FileName))
                    {
                        try
                        {
                            File.Delete(sfd.FileName);
                        }
                        catch (IOException ex)
                        {
                            fileError = true;
                            MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
                        }
                    }
                    if (!fileError)
                    {
                        try
                        {
                            PdfPTable pdfTable = new PdfPTable(info_dgv.Columns.Count);
                            pdfTable.DefaultCell.Padding = 3;
                            pdfTable.WidthPercentage     = 100;
                            pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
                            foreach (DataGridViewColumn column in info_dgv.Columns)
                            {
                                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                                pdfTable.AddCell(cell);
                            }
                            foreach (DataGridViewRow row in info_dgv.Rows)
                            {
                                string id = row.Cells[0].Value.ToString();
                                pdfTable.AddCell(id);
                                string Fname = row.Cells[1].Value.ToString();
                                pdfTable.AddCell(Fname);
                                string Lname = row.Cells[2].Value.ToString();
                                pdfTable.AddCell(Lname);
                                string Bdate = row.Cells[3].Value.ToString();
                                pdfTable.AddCell(Bdate);
                                string gender = row.Cells[4].Value.ToString();
                                pdfTable.AddCell(gender);
                                string phone = row.Cells[5].Value.ToString();
                                pdfTable.AddCell(phone);
                                string address = row.Cells[6].Value.ToString();
                                pdfTable.AddCell(address);
                                byte[] imageByte            = (byte[])row.Cells[7].Value;
                                iTextSharp.text.Image Image = iTextSharp.text.Image.GetInstance(imageByte);
                                pdfTable.AddCell(Image);
                            }
                            using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
                            {
                                iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 20f, 20f, 10f);
                                PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open();
                                pdfDoc.Add(pdfTable);
                                pdfDoc.Close();
                                stream.Close();
                            }

                            MessageBox.Show("Data Exported Successfully !!!", "Info");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error :" + ex.Message);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("No Record To Export !!!", "Info");
            }
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Constructor of MDHandler - all parameters are injected
 /// </summary>
 /// <param name="container">The injected container of the application</param>
 /// <param name="loggerService">The injected logger service of the application</param>
 public PyCraftHandler(IUnityContainer container, ILoggerService loggerService)
 {
     _container     = container;
     _loggerService = loggerService;
     _dialog        = new SaveFileDialog();
 }
Ejemplo n.º 52
0
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog open = new SaveFileDialog();
                if (open.ShowDialog() == DialogResult.OK)
                {
                    string fn;
                    fn = open.FileName + ".txt";


                    //writing into file

                    System.IO.StreamWriter objw;
                    objw = new System.IO.StreamWriter(fn);
                    objw.Write(inputTextBox.Text);
                    objw.Close();
                    //end
                }

                /* else
                 * {
                 *   string aa = textBox1.Text;
                 *
                 *   char[] ext = aa.ToCharArray();
                 *   int l = aa.Length;
                 *
                 *   int a = aa.IndexOf('.');
                 *   if (ext[a + 1] == 'x')
                 *   {
                 *       int r = Convert.ToInt32(textBox2.Text);
                 *       int c = Convert.ToInt32(textBox3.Text);
                 *       savexml(r, c);
                 *   }
                 *   else if (ext[a + 1] == 't')
                 *   {
                 *       savetxt();
                 *   }
                 *   else if (ext[a + 1] == 'd')
                 *   {
                 *       savedoc();
                 *   }
                 *   else if (ext[a + 1] == 'p' && ext[a + 2] == 'd')
                 *   {
                 *       savepdf();
                 *   }
                 *   else
                 *   {
                 *       SaveFileDialog open = new SaveFileDialog();
                 *       if (open.ShowDialog() == DialogResult.OK)
                 *       {
                 *           string fn;
                 *           fn = open.FileName;
                 *
                 *
                 *           //writing into file
                 *
                 *           System.IO.StreamWriter objw;
                 *           objw = new System.IO.StreamWriter(fn);
                 *           objw.Write(inputTextBox.Text);
                 *           objw.Close();
                 *           //end
                 *       }
                 *   }
                 * }*/
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error Occured: " + ex.Message);
            }
        }
Ejemplo n.º 53
0
        //Експортувати у файл
        private void ExportButton_Click(object sender, RoutedEventArgs e)
        {
            ComboBoxItem comboItem = (ComboBoxItem)ComboBox.SelectedItem;

            //Експортувати в документ PDF
            if (comboItem.Name != null && comboItem.Name.ToString() == "Pdf")
            {
                string extension = "pdf";
                //
                SaveFileDialog dialog = new SaveFileDialog()
                {
                    DefaultExt       = extension,
                    RestoreDirectory = true,
                    Title            = "Збереження",
                    Filter           = String.Format("Файл {1} (*.{0})|*.{0}|Всі файли (*.*)|*.*", extension, "Pdf"),
                    FilterIndex      = 1
                };

                if (dialog.ShowDialog() == true)
                {
                    using (Stream stream = dialog.OpenFile())
                    {
                        //параметри експорту
                        CandidatesGridView.ExportToPdf(stream,
                                                       new GridViewPdfExportOptions()
                        {
                            ShowColumnHeaders   = true,
                            ShowColumnFooters   = true,
                            ShowGroupFooters    = true,
                            ExportDefaultStyles = true,
                            PageOrientation     = PageOrientation.Landscape
                        });
                        //Повідомлення про успішне експортування
                        MessageBox.Show("Експорт у файл Pdf виконано успішно!", "Повідомлення",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            //Експортувати в документ Excel
            if (comboItem.Name != null && comboItem.Name.ToString() == "Xlsx")
            {
                string extension = "xlsx";

                SaveFileDialog dialog = new SaveFileDialog()
                {
                    DefaultExt       = extension,
                    Title            = "Збереження",
                    RestoreDirectory = true,
                    Filter           = String.Format("Файл {1} (*.{0})|*.{0}|Всі файли (*.*)|*.*", extension, "Excel"),
                    FilterIndex      = 1
                };

                if (dialog.ShowDialog() == true)
                {
                    using (Stream stream = dialog.OpenFile())
                    {
                        //параметри експорту
                        CandidatesGridView.ExportToXlsx(stream,
                                                        new GridViewDocumentExportOptions()
                        {
                            ShowColumnFooters   = true,
                            ShowColumnHeaders   = true,
                            ShowGroupFooters    = true,
                            ExportDefaultStyles = true
                        });
                        //Повідомлення про успішне експортування
                        MessageBox.Show("Експорт у файл Excel виконано успішно!", "Повідомлення",
                                        MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
        }
Ejemplo n.º 54
0
        public Windows()
        {
            Button bp = new Button("Show borderless window");

            PackStart(bp);
            bp.Clicked += delegate {
                Window w = new Window();
                w.Decorated = false;
                Button c = new Button("This is a window");
//				c.Margin.SetAll (10);
                w.Content  = c;
                c.Clicked += delegate {
                    w.Dispose();
                };
                var bpos = bp.ScreenBounds;
                w.ScreenBounds = new Rectangle(bpos.X, bpos.Y + bp.Size.Height, w.Width, w.Height);
                w.Show();
            };
            Button b = new Button("Show message dialog");

            PackStart(b);
            b.Clicked += delegate {
                MessageDialog.ShowMessage(ParentWindow, "Hi there!");
            };

            Button db = new Button("Show custom dialog");

            PackStart(db);
            db.Clicked += delegate {
                Dialog d = new Dialog();
                d.Title = "This is a dialog";
                Table t = new Table();
                t.Add(new Label("Some field:"), 0, 0);
                t.Add(new TextEntry(), 1, 0);
                t.Add(new Label("Another field:"), 0, 1);
                t.Add(new TextEntry(), 1, 1);
                d.Content         = t;
                d.CloseRequested += delegate(object sender, CloseRequestedEventArgs args) {
                    args.AllowClose = MessageDialog.Confirm("Really close?", Command.Close);
                };

                Command custom = new Command("Custom");
                d.Buttons.Add(new DialogButton(custom));
                d.Buttons.Add(new DialogButton("Custom OK", Command.Ok));
                d.Buttons.Add(new DialogButton(Command.Cancel));
                d.Buttons.Add(new DialogButton(Command.Ok));

                var r = d.Run(this.ParentWindow);
                db.Label = "Result: " + (r != null ? r.Label : "(Closed)");
                d.Dispose();
            };

            b = new Button("Show Open File dialog");
            PackStart(b);
            b.Clicked += delegate {
                OpenFileDialog dlg = new OpenFileDialog("Select a file");
                dlg.InitialFileName = "Some file";
                dlg.Multiselect     = true;
                dlg.Filters.Add(new FileDialogFilter("Xwt files", "*.xwt"));
                dlg.Filters.Add(new FileDialogFilter("All files", "*.*"));
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Files have been selected!", string.Join("\n", dlg.FileNames));
                }
            };

            b = new Button("Show Save File dialog");
            PackStart(b);
            b.Clicked += delegate {
                SaveFileDialog dlg = new SaveFileDialog("Select a file");
                dlg.InitialFileName = "Some file";
                dlg.Multiselect     = true;
                dlg.Filters.Add(new FileDialogFilter("Xwt files", "*.xwt"));
                dlg.Filters.Add(new FileDialogFilter("All files", "*.*"));
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Files have been selected!", string.Join("\n", dlg.FileNames));
                }
            };

            b = new Button("Show Select Folder dialog (Multi select)");
            PackStart(b);
            b.Clicked += delegate {
                SelectFolderDialog dlg = new SelectFolderDialog("Select some folder");
                dlg.Multiselect = true;
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Folders have been selected!", string.Join("\n", dlg.Folders));
                }
            };

            b = new Button("Show Select Folder dialog (Single select)");
            PackStart(b);
            b.Clicked += delegate {
                SelectFolderDialog dlg = new SelectFolderDialog("Select a folder");
                dlg.Multiselect = false;
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Folders have been selected!", string.Join("\n", dlg.Folders));
                }
            };

            b = new Button("Show Select Folder dialog (Single select, allow creation)");
            PackStart(b);
            b.Clicked += delegate {
                SelectFolderDialog dlg = new SelectFolderDialog("Select or create a folder");
                dlg.Multiselect      = false;
                dlg.CanCreateFolders = true;
                if (dlg.Run())
                {
                    MessageDialog.ShowMessage("Folders have been selected/created!", string.Join("\n", dlg.Folders));
                }
            };

            b = new Button("Show Select Color dialog");
            PackStart(b);
            b.Clicked += delegate {
                SelectColorDialog dlg = new SelectColorDialog("Select a color");
                dlg.SupportsAlpha = true;
                dlg.Color         = Xwt.Drawing.Colors.AliceBlue;
                if (dlg.Run(ParentWindow))
                {
                    MessageDialog.ShowMessage("A color has been selected!", dlg.Color.ToString());
                }
            };

            b = new Button("Show window shown event");
            PackStart(b);
            b.Clicked += delegate
            {
                Window w = new Window();
                w.Decorated = false;
                Button c = new Button("This is a window with events on");
                w.Content  = c;
                c.Clicked += delegate
                {
                    w.Dispose();
                };
                w.Shown  += (sender, args) => MessageDialog.ShowMessage("My Parent has been shown");
                w.Hidden += (sender, args) => MessageDialog.ShowMessage("My Parent has been hidden");

                w.Show();
            };

            b = new Button("Show dialog with dynamically updating content");
            PackStart(b);
            b.Clicked += delegate
            {
                var dialog = new Dialog();
                dialog.Content = new Label("Hello World");
                Xwt.Application.TimeoutInvoke(TimeSpan.FromSeconds(2), () => {
                    dialog.Content = new Label("Goodbye World");
                    return(false);
                });
                dialog.Run();
            };

            b = new Button("Show dialog and make this window not sensitive");
            PackStart(b);
            b.Clicked += delegate
            {
                var dialog = new Dialog();
                dialog.Content = new Label("Hello World");
                dialog.Run();
                dialog.Shown  += (sender, args) => this.ParentWindow.Sensitive = false;
                dialog.Closed += (sender, args) => this.ParentWindow.Sensitive = true;
            };
        }
Ejemplo n.º 55
0
        //відкрити файл резюме кандидата
        private void OpenButton_Click(object sender, RoutedEventArgs e)
        {
            //при натисканні кнопки OpenButton - змінити фокус на рядок, в якому знаходиться кнопка
            var senderElement = e.OriginalSource as FrameworkElement;
            var row           = senderElement.ParentOfType <GridViewRow>();

            if (row != null)
            {
                row.IsSelected = true;
            }

            //Обрати номер CvId (запису кандидата) виділеної лінійки з GridView
            DataRowView rowview = CandidatesGridView.SelectedItem as DataRowView;

            if (rowview != null)
            {
                var idValue = rowview.Row.ItemArray[0].ToString();

                //використаємо з'єднання
                using (SqlConnection con = new SqlConnection(connection))
                {
                    //Витягнемо ім'я файлу та сам файл
                    SqlCommand cmd = new SqlCommand("SELECT FileName, Data FROM Candidates where CvId=@CvId", con);
                    cmd.Parameters.AddWithValue("@CvId", idValue);
                    //відкриваємо з'єднання
                    con.Open();

                    //прочитаємо потік
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            //визначимо назву файлу
                            string path = reader.GetString(0);

                            //витягнемо файл
                            byte[] transactionContext = reader.GetSqlBytes(1).Buffer;

                            //діалог збереження файлу
                            SaveFileDialog dlg = new SaveFileDialog();
                            dlg.RestoreDirectory = true;
                            dlg.Title            = "Збереження";

                            //Ім'я файлу з бази даних
                            dlg.FileName = path;

                            //Показати діалог збереження файлу
                            bool?result = dlg.ShowDialog();

                            //Якщо підтверджено - зберегти у файл
                            if (result == true)
                            {
                                FileStream fs = new FileStream(dlg.FileName, FileMode.Create, FileAccess.ReadWrite);
                                fs.Write(transactionContext, 0, transactionContext.Length);
                                fs.Close();

                                //Повідомлення про успішне експортування
                                MessageBox.Show(
                                    "Документ '" + Path.GetFileName(dlg.FileName.Trim()) + "' успішно збережено!",
                                    "Повідомлення",
                                    MessageBoxButton.OK, MessageBoxImage.Information);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 56
0
        private void Button_build_Click(object sender, EventArgs e)
        {
            try
            {
                if (FileName != null)
                {
                    StreamWriter sw = new StreamWriter(FileName);
                    sw.Write(this.TextBox_Program.Text);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Resources.Exception_happened_during_saving__ + ex.Message + "\r\n" + ex.StackTrace, Ultility.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            SaveFileDialog svd = new SaveFileDialog();

            svd.InitialDirectory = GetOpenFolderDirectory();

            svd.DefaultExt = ".dll";
            svd.Filter     = "PAT Library Files (*.dll)|*.dll";
            svd.FileName   = Path.GetFileNameWithoutExtension(this.StatusLabel_FileName.Text);

            if (svd.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string dllName = svd.FileName;

                    //delete the dll if exist
                    if (File.Exists(svd.FileName))
                    {
                        File.Delete(svd.FileName);
                    }

                    if (Button_BuildMode.ComboBox.Text == "Contracts")
                    {
                        dllName = dllName + ".temp";
                    }

                    CompilerParameters parameters;
                    CompilerResults    results;

                    parameters = new CompilerParameters();
                    parameters.OutputAssembly     = dllName;
                    parameters.GenerateExecutable = false;
                    parameters.GenerateInMemory   = false;


                    if (Button_BuildMode.ComboBox.Text == "Release")
                    {
                        parameters.IncludeDebugInformation = false;
                    }
                    else
                    {
                        parameters.IncludeDebugInformation = true;
                    }

                    parameters.TreatWarningsAsErrors = false;
                    parameters.WarningLevel          = 4;



                    // Optimize output, and make a windows executable (no console)
                    parameters.CompilerOptions = "/optimize /target:library";

                    // Put any references you need here - even your own dll's, if you want to use them
                    List <string> refs = new List <string>()
                    {
                        "System.dll",
                        "System.Core.dll",
                        "System.Drawing.dll",
                        "System.Windows.Forms.dll",
                        Path.Combine(Common.Ultility.Ultility.APPLICATION_PATH, "PAT.Common.dll"),
                        //Application.StartupPath + "\\PAT.Module.CSP.dll"
                    };

                    //add additional DLL files need for the compilation
                    refs.AddRange(Directory.GetFiles(Path.Combine(Common.Ultility.Ultility.APPLICATION_PATH, "ExtDLL"), "*.dll"));

                    if (Button_BuildMode.ComboBox.Text == "Contracts")
                    {
                        refs.Add(Path.Combine(Ultility.LibFolderPath, "Microsoft.Contracts.dll"));
                    }

                    // Add the assemblies that we will reference to our compiler parameters
                    parameters.ReferencedAssemblies.AddRange(refs.ToArray());

                    Dictionary <string, string> provOptions = new Dictionary <string, string>();

                    provOptions.Add("CompilerVersion", "v3.5");

                    // Get a code provider for C#
                    CSharpCodeProvider provider = new CSharpCodeProvider(provOptions);


                    // Read the entire contents of the file
                    string sourceCode = this.TextBox_Program.Text;


                    //Add the contracts line
                    if (Button_BuildMode.ComboBox.Text == "Contracts")
                    {
                        string contractDefine = "#define CONTRACTS_FULL";
                        if (!sourceCode.Contains(contractDefine))
                        {
                            sourceCode = contractDefine + " \r\n" + sourceCode;
                        }
                    }

                    string assemblyAttributes = string.Empty;
                    //if (sourceExe != null)
                    //    assemblyAttributes = CopyAssemblyInformation(sourceExe);

                    // Add assembly attributes to the source code
                    sourceCode = sourceCode.Replace("[[AssemblyAttributes]]", assemblyAttributes);

                    // Compile our code
                    results = provider.CompileAssemblyFromSource(parameters, new string[] { sourceCode });

                    if (results.Errors.Count > 0)
                    {
                        foreach (CompilerError error in results.Errors)
                        {
                            MessageBox.Show(Resources.An_error_occurred_while_compiling_the_C__code__ +
                                            String.Format(
                                                "Line {0}, Col {1}: Error {2} - {3}",
                                                error.Line,
                                                error.Column,
                                                error.ErrorNumber,
                                                error.ErrorText), Ultility.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        if (Button_BuildMode.ComboBox.Text == "Contracts") // && results.Errors.Count == 0
                        {
                            try
                            {
                                string  ccrewrite = "\"" + Path.Combine(Ultility.LibFolderPath, "ccrewrite.exe") + "\"";
                                Process process   = new Process();
                                process.StartInfo = new ProcessStartInfo(ccrewrite, "");
                                process.StartInfo.WorkingDirectory = Common.Ultility.Ultility.APPLICATION_PATH;// Application.StartupPath;

                                process.StartInfo.Arguments = "\"" + dllName + "\" -output \"" + svd.FileName + "\"";
                                process.Start();

                                while (!process.HasExited)
                                {
                                    System.Threading.Thread.Sleep(500);
                                }

                                MessageBox.Show(Resources.C__library_is_built_successfully__You_can_use_them_now_in_your_models_, Ultility.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            catch (Exception ex1)
                            {
                                if (File.Exists(dllName))
                                {
                                    File.Delete(dllName);
                                }
                                MessageBox.Show(Resources.Exception_happened_during_the_Contracts_compilation__ + ex1.Message + "\r\n" + ex1.StackTrace, Ultility.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show(Resources.C__library_is_built_successfully__You_can_use_them_now_in_your_models_, Ultility.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }


                    //remove the temp file if any
                    try
                    {
                        if (dllName.EndsWith(".temp") && File.Exists(dllName))
                        {
                            File.Delete(dllName);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(Resources.Exception_happened_during_the_compilation__ + ex.Message + "\r\n" + ex.StackTrace, Ultility.APPLICATION_NAME, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Ejemplo n.º 57
0
        private async void executeExportPersonPhotoCommand(object obj)
        {
            if (!this.isPersonPhotoSaving && this.personPhotoKey != -1)
            {
                this.isPersonPhotoSaving = true;
                Mouse.OverrideCursor     = Cursors.Wait;
                try
                {
                    byte[] imageArray = null;

                    if (this.personPhotoKey == 0)
                    {
                        //string imagePath = Properties.Settings.Default.IntellectInstallDir + "\\bmp\\Person\\" + person.ID + ".bmp";
                        //imageArray = ImageHelper.GetArrayFromFile(imagePath);
                        imageArray = await this.das.GetPersonPhotoFromFileAsync(person.Id);
                    }
                    else
                    {
                        imageArray = await this.das.GetPersonPhotoFromDBAsync(CancellationToken.None, this.person.PersonKey);
                    }

                    if (imageArray != null)
                    {
                        Image  image = IntellectOPK.Model.Utilities.ImageHelper.GetImageFromArray(imageArray);
                        string ext   = IntellectOPK.Model.Utilities.ImageHelper.GetImageFileExtension(image);
                        if (String.IsNullOrEmpty(ext))
                        {
                            ext = "";
                        }
                        string personName = StringHelper.RemoveUnnecessaryChars(this.person.FullName, Model.Person.ValidCharsForFullName);

                        SaveFileDialog saveDialog = new SaveFileDialog();
                        //saveDialog.Title = "Сохранение фото сотрудника";
                        //if(ext != "")
                        //{
                        //    saveDialog.DefaultExt = ext;
                        //    saveDialog.AddExtension = true;
                        //}
                        saveDialog.FileName        = personName;
                        saveDialog.OverwritePrompt = true;
                        //saveDialog.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";
                        saveDialog.Filter = "(*." + ext + ")|*." + ext + "|All files(*.*)|*.*";
                        if (saveDialog.ShowDialog() == true)
                        {
                            this.logAuditEvent("others", "export_photo", null, null, "person_name=" + personName);
                            File.WriteAllBytes(saveDialog.FileName, imageArray);
                            //Message.ShowMessage(ext, "Тип картинки", this.view);
                            //Message.ShowMessage("Файл успешно сохранен", "Информация", this.view);
                        }
                        Mouse.OverrideCursor = null;
                        //this.view.Owner.Activate();
                    }
                }
                catch (Exception ex)
                {
                    Mouse.OverrideCursor = null;
                    Message.ShowError(ex.Message, ex.GetType().ToString(), this.view);
                }
                this.isPersonPhotoSaving = false;
            }
        }
Ejemplo n.º 58
0
        //DO NOT USE
        public void Export_Timeline()
        {
            try
            {
                if (!DateTimeOn)
                {
                    MessageBox.Show("You must have date and time on to generate a timeline.", "ACE Calculator", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }


                SaveFileDialog SFD = new SaveFileDialog();
                SFD.Title  = "Save for export to Wikia timeline format"; // create the save file dialog
                SFD.Filter = "Text documents (*.txt)|.txt";
                SFD.ShowDialog();

                if (SFD.FileName != "")
                {
                    // write the wikia timeline syntax to the file

                    if (File.Exists(SFD.FileName))
                    {
                        File.Delete(SFD.FileName); // prevent overwrite
                    }

                    using (StreamWriter SW = new StreamWriter(new FileStream(SFD.FileName, FileMode.OpenOrCreate)))
                    {
                        SW.WriteLine("<div style=\"overflow: auto; \"><timeline>");
                        SW.WriteLine("ImageSize = width:800 height:240");                     // the size of the timeline
                        SW.WriteLine("PlotArea  = top:10 bottom:80 right:20 left:20");        // the plot area of the timeline
                        SW.WriteLine("Legend    = columns:3 left:30 top:58 columnwidth:270"); // the plot area of the timeline
                        SW.WriteLine("AlignBars = early");                                    // bar alignment

                        // section 2: definition part 2

                        SW.WriteLine("DateFormat = dd/mm/yyyy");                                         // date format
                        SW.WriteLine("Period     = from:01/11/2019 till:01/05/2020");                    // period of the timeline
                        SW.WriteLine("TimeAxis   = orientation:horizontal");                             // orientation of the timeline
                        SW.WriteLine("ScaleMinor = grid:black unit:month increment:1 start:01/11/2019"); // aaa

                        // section 3: colour definitions
                        SW.WriteLine("Colors = ");                                                                               // color definitions
                        SW.WriteLine("  id:canvas value:gray(0.88)");                                                            // background colour
                        SW.WriteLine("  id:GP     value:red");                                                                   // ???
                        SW.WriteLine("  id:TD     value:rgb(0.38,0.73,1)  legend:Tropical_Depression_=_&lt;39_mph_(0-62_km/h)"); // TD background colour
                        SW.WriteLine("  id:TS     value:rgb(0,0.98,0.96)  legend:Tropical_Storm_=_39-73_mph_(63-117 km/h)");     // TS background colour
                        SW.WriteLine("  id:C1     value:rgb(1,1,0.80)     legend:Category_1_=_74-95_mph_(119-153_km/h)");        // C1 background colour
                        SW.WriteLine("  id:C2     value:rgb(1,0.91,0.46)  legend:Category_2_=_96-110_mph_(154-177_km/h)");       // C2 background colour
                        SW.WriteLine("  id:C3     value:rgb(1,0.76,0.25)  legend:Category_3_=_111-130_mph_(178-209-km/h)");      // C3 background colour
                        SW.WriteLine("  id:C4     value:rgb(1,0.56,0.13)  legend:Category_4_=_131-155_mph_(210-249_km/h)");      // C4 background colour
                        SW.WriteLine("  id:C5     value:rgb(1,0.91,0.46)  legend:Category_2_=_96-110_mph_(154-177_km/h)");       // C5 background colour

                        // section 4: BG defs
                        SW.WriteLine("Backgroundcolors = canvas:canvas");

                        // section 5: bar data
                        SW.WriteLine("BarData ="); // bar data
                        SW.WriteLine("  barset:Hurricane");

                        // section 6: plot data
                        SW.WriteLine("  bar:Month");
                    }
                }
                else
                {
                    return;
                }
            }
            catch (IOException err)
            {
                MessageBox.Show($"An error occurred while exporting to EasyTimeline format. An IOException has occurred. We're sorry, but please restart. Thanks.\n\n{err}");
                Application.Current.Shutdown(-2);
            }
        }
Ejemplo n.º 59
0
        private void MenuItem_Click_3(object sender, RoutedEventArgs e)
        {
            TreeViewItem temp = (FoldersTree.SelectedItem as TreeViewItem);
            if (temp == null || (temp.Tag as PathNode).Type != 2) return;

            string fullPath = (temp.Tag as PathNode).FullPath;

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.FileName = System.IO.Path.GetFileNameWithoutExtension(fullPath);
            saveFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(fullPath);
            saveFileDialog.Filter = "Microsoft Word (DOCX)|*.docx|Rich Text Format (RTF)|*.rtf|Portable Document Format (PDF)|*.pdf|HyperText Markup Language (HTML)|*.html|HyperText Markup Language (HTML) Fixed|*.html|Images (Png)|*.png";
            saveFileDialog.FilterIndex = (System.IO.Path.GetExtension(fullPath).ToLower() == ".pdf") ? 1 : 3;
            saveFileDialog.AddExtension = true;
            saveFileDialog.OverwritePrompt = true;
            saveFileDialog.ValidateNames = true;

            if (saveFileDialog.ShowDialog() == true)
                try
                {
                    System.Windows.Input.Cursor cursor = Mouse.OverrideCursor;
                    string openFile = "";
                    try
                    {
                        Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;

                        DocumentCore dc = DocumentCore.Load(fullPath);

                        switch (saveFileDialog.FilterIndex)
                        {
                            case 4:
                                openFile = saveFileDialog.FileName;
                                dc.Save(saveFileDialog.FileName, new HtmlFlowingSaveOptions());
                                break;

                            case 6:
                                {
                                    SautinSoft.Document.DocumentPaginator dp = dc.GetPaginator();
                                    string path = System.IO.Path.GetDirectoryName(saveFileDialog.FileName);
                                    string fileName = System.IO.Path.GetFileNameWithoutExtension(saveFileDialog.FileName);
                                    for (int idx = 0; idx < dp.Pages.Count; ++idx)
                                    {
                                        string s = System.IO.Path.Combine(path, fileName + (idx + 1).ToString() + ".png");
                                        if (string.IsNullOrEmpty(openFile)) openFile = s;
                                        dp.Pages[idx].Rasterize(200).Save(s);
                                    }
                                }
                                break;

                            default:
                                openFile = saveFileDialog.FileName;
                                dc.Save(saveFileDialog.FileName);
                                break;
                        }

                        dc = null;
                    }
                    finally
                    {
                        Mouse.OverrideCursor = cursor;
                        GC.Collect();
                    }

                    System.Diagnostics.Process.Start(openFile);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
        }
Ejemplo n.º 60
0
        public static void GenerateProbeBoundings()
        {
            OpenFileDialog ofd1 = new OpenFileDialog();

            ofd1.Filter = Utils.GetAllFilters(typeof(AAMP));
            if (ofd1.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            //Load the AAMP
            var File = STFileLoader.OpenFileFormat(ofd1.FileName);

            if (File == null || !(File is AAMP))
            {
                throw new Exception("File not a valid AAMP file!");
            }

            //Load bfres for generating the bounds
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter = Utils.GetAllFilters(typeof(BFRES));

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                //Open and check bfres
                var Bfres = STFileLoader.OpenFileFormat(ofd.FileName);
                if (Bfres == null || !(Bfres is BFRES))
                {
                    throw new Exception("File not a valid BFRES file!");
                }

                //Check version instance
                foreach (var val in ((AAMP)File).aampFile.RootNode.childParams)
                {
                    foreach (var param in val.paramObjects)
                    {
                        switch (param.HashString)
                        {
                        case "grid":
                            GenerateGridData((BFRES)Bfres, param.paramEntries);
                            break;
                        }
                    }
                }

                foreach (var param in ((AAMP)File).aampFile.RootNode.paramObjects)
                {
                    switch (param.HashString)
                    {
                    case "root_grid":
                        GenerateGridData((BFRES)Bfres, param.paramEntries);
                        break;
                    }
                }

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = Utils.GetAllFilters(File);
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    //Save the aamp back
                    STFileSaver.SaveFileFormat(File, sfd.FileName);
                }

                File.Unload();
                Bfres.Unload();
            }
        }