Esempio n. 1
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>");
                }
            }
        }
    }
    public static Rhino.Commands.Result ExportControlPoints(Rhino.RhinoDoc doc)
    {
        Rhino.DocObjects.ObjRef objref;
        var get_rc = Rhino.Input.RhinoGet.GetOneObject("Select curve", false, Rhino.DocObjects.ObjectType.Curve, out objref);
        if (get_rc != Rhino.Commands.Result.Success)
          return get_rc;
        var curve = objref.Curve();
        if (curve == null)
          return Rhino.Commands.Result.Failure;
        var nc = curve.ToNurbsCurve();

        var fd = new SaveFileDialog();
        //fd.Filters = "Text Files | *.txt";
        //fd.Filter = "Text Files | *.txt";
        //fd.DefaultExt = "txt";
        //if( fd.ShowDialog(Rhino.RhinoApp.MainWindow())!= System.Windows.Forms.DialogResult.OK)
        if (fd.ShowDialog(null) != DialogResult.Ok)
          return Rhino.Commands.Result.Cancel;
        string path = fd.FileName;
        using( System.IO.StreamWriter sw = new System.IO.StreamWriter(path) )
        {
          foreach( var pt in nc.Points )
          {
        var loc = pt.Location;
        sw.WriteLine("{0} {1} {2}", loc.X, loc.Y, loc.Z);
          }
          sw.Close();
        }
        return Rhino.Commands.Result.Success;
    }
Esempio n. 3
0
    // What to do when the user wants to export a SVG or TeX file
    private void exportHandler(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog = new SaveFileDialog();

        saveFileDialog.Filter = "SVG image|*.svg|TeX file|*.tex";
        saveFileDialog.RestoreDirectory = true;

        if(saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            IGraphics graphics;

            switch (saveFileDialog.FilterIndex)
            {
                case 1:
                    graphics = new SVGGraphics(saveFileDialog.FileName);
                    break;
                case 2:
                    graphics = new TexGraphics(saveFileDialog.FileName);
                    break;
                default:
                    throw new Exception("savefiledialog filterindex: " + saveFileDialog.FilterIndex + " not supported");
                    break;
            }

            this.drawShapes(graphics);
        }
    }
        public void SaveScreen(double paramX, double paramY, double paramWidth, double paramHeight)
        {
            var ix = Convert.ToInt32(paramX);
            var iy = Convert.ToInt32(paramY);
            var iw = Convert.ToInt32(paramWidth);
            var ih = Convert.ToInt32(paramHeight);
            try
            {
                var myImage = new Bitmap(iw, ih);

                var gr1 = Graphics.FromImage(myImage);
                var dc1 = gr1.GetHdc();
                var dc2 = NativeMethods.GetWindowDC(NativeMethods.GetForegroundWindow());
                NativeMethods.BitBlt(dc1, ix, iy, iw, ih, dc2, ix, iy, 13369376);
                gr1.ReleaseHdc(dc1);
                var dlg = new SaveFileDialog {DefaultExt = "png", Filter = "Png Files|*.png"};
                var res = dlg.ShowDialog();
                if (res == System.Windows.Forms.DialogResult.OK)
                    myImage.Save(dlg.FileName, ImageFormat.Png);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(String.Format("SaveScreen exception : {0}", ex.Message));
            }
        }
Esempio n. 5
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>");
                }
            }
        }
    }
    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 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 { }
        }
Esempio n. 8
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;
        }
Esempio n. 9
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);
                }
            }
        }
    }
            protected override void OnActivate()
            {
                try
                {
                    // Step 1: Pop up a file save dialog to get a output path
                    SaveFileDialog saveDlg = new SaveFileDialog();
                    saveDlg.Filter = Resources.IDS_PNG_FILTER;
                    saveDlg.Title = Resources.IDS_SAVE_PICTURE_TITLE;
                    saveDlg.ShowDialog();

                    // Step 2: Output a png image
                    if (saveDlg.FileName != /*MSG0*/"")
                    {
                        CImageOutputUtil.OutputImageFromCurrentSence(IApp.theApp.RenderWindow, saveDlg.FileName);
                    }
                }
                catch (SystemException e)
                {
                    MessageBox.Show(e.Message);
                }
                finally
                {
                    Terminate();
                }
            }
Esempio n. 11
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);
            }
        }
    }
    private void UIBrowse_Click(System.Object sender, System.EventArgs e)
    {
        SaveFileDialog dialog = new SaveFileDialog();
        dialog.Filter = ".ATR|*.ATR|.XFD|*.XFD";
        if (dialog.ShowDialog() != DialogResult.OK) return;

        UIFilename.Text = dialog.FileName;
    }
Esempio n. 13
0
 protected void Save_Click(Object sender, EventArgs e)
 {
     SaveFileDialog s = new SaveFileDialog();
     if(s.ShowDialog() == DialogResult.OK) {
       StreamWriter writer = new StreamWriter(s.OpenFile());
       writer.Write(text.Text);
       writer.Close();
     }
 }
    private void UIBrowse_Click(System.Object sender, System.EventArgs e)
    {
        SaveFileDialog dialog = new SaveFileDialog();

        if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            UIFileName.Text = dialog.FileName;
        }
    }
Esempio n. 15
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 = "Scalable Vector Graphics (*.svg)|*.svg|TeX files (*.tex)|*.tex";
        saveFileDialog.RestoreDirectory = true;

        if(saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            if((stream = saveFileDialog.OpenFile()) != null)
            {
                string name = saveFileDialog.FileName;
                string ext = Path.GetExtension(saveFileDialog.FileName).ToLower();

                switch(ext){
                    case ".tex":
                        LatexGenerator lg = new LatexGenerator();
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            lg.FileWriter = writer;
                            writer.WriteLine("\\documentclass{article}");
                            writer.WriteLine("\\usepackage{tikz}");
                            writer.WriteLine("\\begin{document}");
                            writer.WriteLine("\\begin{tikzpicture}");
                            writer.WriteLine("\\begin{scope}[yscale= -3, xscale= 3]");
                            foreach(Shape s in this.shapes)
                            {
                                s.OutputApi = lg;
                                s.Draw();
                            }
                            writer.WriteLine("\\end{scope}");
                            writer.WriteLine("\\end{tikzpicture}");
                            writer.WriteLine("\\end{document}");
                        }
                        break;
                    default: //save as svg by default
                        SvgGenerator sg = new SvgGenerator();
                        using (StreamWriter writer = new StreamWriter(stream))
                        {
                            sg.FileWriter = writer;
                            writer.WriteLine("<?xml version=\"1.0\" standalone=\"no\"?>");
                            writer.WriteLine("<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">");
                            writer.WriteLine("<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">");
                            foreach (Shape s in this.shapes)
                            {
                                s.OutputApi = sg;
                                s.Draw();
                            }
                            writer.WriteLine("</svg>");
                        }
                        break;
                }
            }
        }
    }
Esempio n. 16
0
 //----< "Save" button >------------------------------
 private void button2_Click(object sender, EventArgs e)
 {
     SaveFileDialog saveFileDialog = new SaveFileDialog();
     saveFileDialog.Title = "Save SPINA File";
     saveFileDialog.Filter = "SPINA Files(*.spi)|*.spi";
     if (saveFileDialog.ShowDialog() == DialogResult.OK)
     {
         SaveSourceCode(saveFileDialog.FileName);
     }
 }
Esempio n. 17
0
 public void Save()
 {
     string save = "";
     SaveFileDialog savefileDialog = new SaveFileDialog();
     savefileDialog.Filter = "Semikolonseparierte Datei (*.csv)|*.csv";
     if (savefileDialog.ShowDialog() == DialogResult.OK)
     {
         save = savefileDialog.FileName;
         this.Data.CreateCSVFile(save,";");
     }
 }
Esempio n. 18
0
        /// <summary>
        /// Creates a csv file
        /// </summary>
        /// <param name="fileName">Desired file name</param>
        /// <returns>Bool if file is created</returns>
        public bool CreateFile(string fileName = null)
        {
            FileDialog = new SaveFileDialog()
            {
                FileName   = fileName ?? "Rapport",
                DefaultExt = ".csv",
                Filter     = "Excel documents (.csv)|*.csv"
            };

            return(FileDialog?.ShowDialog() ?? false);
        }
Esempio n. 19
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        string path = "F:\\网络1.txt";

        SaveFileDialog savefile1 = new SaveFileDialog();
        savefile1.ShowDialog();
        path = savefile1.FileName.ToString();
        System.IO.StreamWriter sw = new System.IO.StreamWriter(path, true);
        sw.Write(TextBox1.Text);

        sw.Dispose();
    }
 private static string PromptForSaveFile(string file, string ext, string filter)
 {
     var dlg = new SaveFileDialog();
     dlg.FileName = file;
     dlg.DefaultExt = ext;
     dlg.Filter = filter;
     if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
     {
         return dlg.FileName;
     }
     return string.Empty;
 }
Esempio n. 21
0
    public static void ExportDataGrid(DataGrid dGrid, String author, String companyName, String mergeCells, int boldHeaderRows)
    {
        SaveFileDialog objSFD = new SaveFileDialog() { DefaultExt = "xml", Filter = FILE_FILTER, FilterIndex = 2 };

        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);
        }
    }
        private void BtnSave_OnCLick(object sender, RoutedEventArgs e)
        {
            var fileDialog = new SaveFileDialog
            {
                DefaultExt = ".sud"
            };
            var result = fileDialog.ShowDialog();

            if (result != System.Windows.Forms.DialogResult.OK) return;

            var file = fileDialog.FileName;
            App.SudokuManager.SaveFile(file);
        }
 public void CaptureScreen(double paramX, double paramY, double paramWidth, double paramHeight)
 {
     var ix = Convert.ToInt32(paramX);
     var iy = Convert.ToInt32(paramY);
     var iw = Convert.ToInt32(paramWidth);
     var ih = Convert.ToInt32(paramHeight);
     var image = new Bitmap(iw, ih, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
     var g = Graphics.FromImage(image);
     g.CopyFromScreen(ix, iy, 0, 0, new Size(iw, ih), CopyPixelOperation.SourceCopy);
     var dlg = new SaveFileDialog {DefaultExt = "png", Filter = "Png Files|*.png"};
     var res = dlg.ShowDialog();
     if (res == System.Windows.Forms.DialogResult.OK)
         image.Save(dlg.FileName, ImageFormat.Png);
 }
Esempio n. 24
0
	void SaveFileButton_Click (object sender, EventArgs e)
	{
		_fileListBox.Items.Clear ();

		_saveFileDialog = new SaveFileDialog ();
#if NET_2_0
		_saveFileDialog.SupportMultiDottedExtensions = _supportMultiDottedCheckBox.Checked;
#endif
		_saveFileDialog.Filter = "Doc files (*.doc)|*.foo.doc|All files|*.*";
		_saveFileDialog.ShowDialog ();

		foreach (string file in _saveFileDialog.FileNames) {
			_fileListBox.Items.Add (file);
		}
	}
        private void OnSave_Button_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new SaveFileDialog()
            {
                InitialDirectory = GameProject.Project.Current.ContentPath,
                Filter           = "Asset file (*.asset)|*.asset"
            };

            if (dlg?.ShowDialog() == true)
            {
                Debug.Assert(!string.IsNullOrEmpty(dlg.FileName));
                var asset = (DataContext as Editors.IAssetEditor).Asset;
                Debug.Assert(asset != null);
                asset.Save(dlg.FileName);
            }
        }
Esempio n. 26
0
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
             SaveFileDialog fileDialog = new SaveFileDialog();

             fileDialog.Filter = "Excel Files (*.xls)|*.xls|All Files (*.*) |*.*";
            fileDialog.ShowDialog();
            string filepath = fileDialog.FileName;
            if (filepath != "")
            {
                bool bResult = objCashDeskManager.ExportToExcel(lvVoucherStatus, filepath);
                if (bResult)
                {
                    MessageBox.ShowBox("MessageID130", BMC_Icon.Information);
                }
            }
        }
Esempio n. 27
0
		private void btnOkay_Click(object sender, RoutedEventArgs e)
		{
			var keypair = new KeyValuePair<string, int>(null, -1);
			var sfd = new SaveFileDialog
			{
				Title = "Assembly - Select where to save your Tag Bookmarks",
				Filter = "Assembly Tag Bookmark File (*.astb)|*.astb"
			};
			if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
				keypair = new KeyValuePair<string, int>(sfd.FileName, cbItems.SelectedIndex);

			// Save keypair to TempStorage
			TempStorage.TagBookmarkSaver = keypair;

			Close();
		}
Esempio n. 28
0
    public static void Main(string[] args)
    {
        //Folder Browser
        FolderBrowserDialog fo = new FolderBrowserDialog();
        fo.SelectedPath = Environment.CurrentDirectory;
        fo.ShowNewFolderButton = true;

        //File Browser
        OpenFileDialog fi = new OpenFileDialog();
        fi.InitialDirectory = Environment.CurrentDirectory;

        //File saver
        SaveFileDialog sv = new SaveFileDialog();
        sv.InitialDirectory = Environment.CurrentDirectory;

        for(int i = 0; i < args.Length; i++)
        {
            if(args[i] == "/fo" || args[i] == "/folder")
            {
                try{fo.Description = args[i+1];}
                catch{fo.Description = "Default description";}
                if(fo.ShowDialog() == DialogResult.OK) {Console.Write(fo.SelectedPath);}
            }
            else if(args[i] == "/fi" || args[i] == "/file")
            {
                fi.Filter = Extension.ToFilter(args[i+1]);
                fi.ShowDialog();
                Console.Write(fi.FileName);
            }
            else if(args[i] == "/sv" || args[i] == "/save")
            {
                sv.Filter = Extension.ToFilter(args[i+1]);
                if(sv.ShowDialog() == DialogResult.OK && sv.FileName.Length > 0) {Console.Write(sv.FileName);}
            }
            else if(args[i] == "/h" || args[i] == "/help" || args[i] == "/?")
            {
                Console.WriteLine("Crée une boîte de dialogue pour ouvrir ou sauvegarder un fichier/un dossier.\n\n");
                Console.WriteLine("  myBrowser [/fi | /file]\n  mybrowser [/fo | /folder]\n  myBrowser [/sv | /save]");
                Console.WriteLine("\n\nUtilisation de /file et de /save :\n  myBrowser [/file | /save] \"addpreset=avi,txt; addcustom=big,Ea games files\"");
                Console.WriteLine("\naddpreset : utilise un presets (voir ci-dessous)\naddcustom : defini une extension personnalisée.\nSyntaxe : addcustom=extension,description. Utiliser un \"addcustom\" pour chacune des extensions à ajouter.\nToujours séparer les instruction par \"; \".");
                Console.WriteLine("\nLes extensions utilisées dans /save ou /file servent à filtrer les types de fichiers à afficher.");
                Console.WriteLine("\n\nUtilisation de /folder :\n  myBrowser /folder \"Insérer une description ici\"");
                Console.WriteLine("\n\nListe de tous les presets :");
                Extension.DisplayLists();
            }
        }
    }
Esempio n. 29
0
 void ChooseFile()
 {
     try
     {
         SaveFileDialog dlg = new SaveFileDialog();
         dlg.DefaultExt = ".tg";
         dlg.Filter = "TestGenerator files (*.tg)|*.tg";
         dlg.ShowDialog();
         TestGenFilePath = dlg.FileName;
         if (TestGenFilePath != "") WriteTGFile();
     }
     catch (Exception exc)
     {
         ShowExceptionMessage();
     }
     shownThisRun = false;
 }
Esempio n. 30
0
 public void CaptureScreen(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);
     Bitmap image = new Bitmap(iw, ih, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
     Graphics g = Graphics.FromImage(image);
     g.CopyFromScreen(ix, iy, ix, iy, new System.Drawing.Size(iw, ih), CopyPixelOperation.SourceCopy);
     SaveFileDialog dlg = new SaveFileDialog();
     dlg.DefaultExt = "png";
     dlg.Filter = "Png Files|*.png";
     DialogResult res = dlg.ShowDialog();
     if (res == System.Windows.Forms.DialogResult.OK)
         image.Save(dlg.FileName, ImageFormat.Png);
 }
Esempio n. 31
0
    public static void SaveImage(Image img)
    {
        try
        {
            using (var sfd = new SaveFileDialog { Title = "Redact | Save Image", Filter = "PNG Files (.png) | *.png" })
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    img.Save(sfd.FileName, ImageFormat.Png);

                    MessageBox.Show("Image successfully saved to " + sfd.FileName, "Redact", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
        }
        catch
        {
            MessageBox.Show("An error occured when attempting to save.", "Redact", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
Esempio n. 32
0
 private void Save_Click(object sender, RoutedEventArgs e)
 {
   Configuration config;
   if (!TryGetCurrentConfig(out config)) { Messages.Text = "Can't save an invalid configuration."; return; }
   if (!IsValidConfig(config)) { Messages.Text = "Can't save an invalid configuration."; return; }
   var dialog = new SaveFileDialog();
   dialog.Filter = "XML File|*.xml";
   if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
   {
     var path = dialog.FileName;
     var xs = new XmlSerializer(typeof(Configuration));
     var file = File.Create(path);
     xs.Serialize(file, config);
     file.Flush();
     file.Close();
   }
 }
Esempio n. 33
0
 private async void SaveButtonEvent(object sender, EventArgs e)
 {
     if (saveFileDialog1?.ShowDialog() == DialogResult.OK)
     {
         try
         {
             EnableControls?.Invoke(false);
             var buffer = Encoding.Default.GetBytes(Text);
             using (var fs = new FileStream(saveFileDialog1.FileName, FileMode.Create, FileAccess.Write, FileShare.None, buffer.Length, true))
             {
                 await fs.WriteAsync(buffer, 0, buffer.Length);
             }
         }
         catch (Exception ex)
         {
             ShowMessage?.Invoke(ex.Message);
         }
         finally
         {
             EnableControls?.Invoke(true);
         }
     }
 }
        private void ExportButton_Click(object sender, EventArgs e)
        {
            Application exApp;

            try
            {
                exApp = new Application();
            }
            catch (Exception)
            {
                MyMsgBox.showError("Не удалось открыть Excel для заполения данных.");
                return;
            }
            string PATH_TO_T9  = "templates\\T-9.xls";
            string PATH_TO_T9A = "templates\\T-9A.xls";

            if (!Directory.Exists("templates"))
            {
                Directory.CreateDirectory("templates");
            }
            // спешл фор Астахова
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
            // try
            // {
            //     // спешл фор 7 винда
            //     //if(Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", "").ToString().Contains("7"))
            //         System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
            // }catch(Exception){}
            try
            {
                if (!File.Exists(PATH_TO_T9))
                {
                    new WebClient().DownloadFile(new Uri("https://github.com/pi62/templates/raw/master/T-9.xls"),
                                                 PATH_TO_T9);
                }

                if (!File.Exists(PATH_TO_T9A))
                {
                    new WebClient().DownloadFile(new Uri("https://github.com/pi62/templates/raw/master/T-9A.xls"),
                                                 PATH_TO_T9A);
                }
            }
            catch (Exception)
            {
                MyMsgBox.showError("Не удалось скачать шаблоны для заполнения.");
                return;
            }

            var saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();

            saveFileDialog1.DefaultExt = "xls";
            saveFileDialog1.ShowDialog();
            var savePath = saveFileDialog1.FileName;

            if (String.IsNullOrWhiteSpace(savePath))
            {
                return;
            }
            if (!Save() || trip == null)
            {
                MyMsgBox.showError("Не удалось сохранить командировку. Экспорт невозможен. Проверьте данные и попробуйте ещё раз");
                return;
            }
            Workbook excelappworkbooks;

            try {
                if (trip.PERSONCARD_IN_TRIP.Count > 1)
                {
                    excelappworkbooks = exApp.Workbooks.Open(Directory.GetCurrentDirectory() + "\\" + PATH_TO_T9A, Type.Missing, false, Type.Missing, Type.Missing,
                                                             Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                }
                else
                {
                    excelappworkbooks = exApp.Workbooks.Open(Directory.GetCurrentDirectory() + "\\" + PATH_TO_T9, Type.Missing, false, Type.Missing, Type.Missing,
                                                             Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                }
            } catch (Exception except)
            {
                Console.Error.WriteLine(except.Message);
                MyMsgBox.showError("Не удалось открыть шаблон");
                return;
            }
            if (excelappworkbooks == null)
            {
                MyMsgBox.showError("Не удалось открыть шаблон");
                return;
            }
            try {
                if (trip.PERSONCARD_IN_TRIP.Count > 1)
                {
                    Worksheet excelsheets = excelappworkbooks.Worksheets.Item[1];
                    OUR_ORG   org         = model.OUR_ORG.First <OUR_ORG>();
                    if (trip.PRIKAZ.ISPROJECT.Equals("1"))
                    {
                        excelsheets.Cells[9, 34].Value  = "ПРОЕКТ ПРИКАЗА";
                        excelsheets.Cells[10, 34].Value = "(распоряжения)";
                    }
                    else
                    {
                        excelsheets.Cells[9, 34].Value  = "ПРИКАЗ";
                        excelsheets.Cells[10, 34].Value = "(распоряжение)";
                    }
                    excelsheets.Cells[5, 1].Value = org.NAME;
                    excelsheets.Cells[5, 93]      = org.OKPO;
                    excelsheets.Cells[9, 61]      = trip.PRIKAZ.NUMDOC;
                    if (trip.PRIKAZ.CREATEDATE != null)
                    {
                        excelsheets.Cells[9, 80] = trip.PRIKAZ.CREATEDATE.Value.ToString("dd.MM.yyyy");
                    }
                    int i = 0;
                    foreach (PERSONCARD_IN_TRIP person in trip.PERSONCARD_IN_TRIP)
                    {
                        if (i == 3)
                        {
                            MyMsgBox.showError("В одном приказе не больше 3х человек");
                            break;
                        }
                        excelsheets.Cells[15, 44 + 22 * i].Value = person.SURNAME + " " + person.NAME + " " + person.MIDDLENAME;
                        excelsheets.Cells[16, 44 + 22 * i].Value = person.TABEL_NUM;
                        if (person.PODRAZDELORG != null)
                        {
                            excelsheets.Cells[17, 44 + 22 * i].Value = person.PODRAZDELORG.NAME;
                        }
                        excelsheets.Cells[18, 44 + 22 * i].Value = person.JOB_POS.NAME;
                        excelsheets.Cells[21, 44 + 22 * i].Value = person.STARTDATE.Value.ToString("dd.MM.yyyy");
                        excelsheets.Cells[22, 44 + 22 * i].Value = person.ENDDATE.Value.ToString("dd.MM.yyyy");
                        excelsheets.Cells[23, 44 + 22 * i].Value = (int)person.ENDDATE.Value.Subtract(person.STARTDATE.Value).TotalDays;
                        excelsheets.Cells[24, 44 + 22 * i].Value = person.GOAL;
                        excelsheets.Cells[25, 44 + 22 * i].Value = person.FINANCE;
                        i++;
                    }

                    foreach (TRIP_ORG tripOrg in trip.TRIP_ORG)
                    {
                        excelsheets.Cells[19, 44].Value += tripOrg.PLACE_TRIP.NAME;
                        excelsheets.Cells[19, 44].Value += ", " + tripOrg.NAME;
                        excelsheets.Cells[19, 44].Value += ";  ";
                    }

                    if (trip.OSNOVANIEDATE != null)
                    {
                        excelsheets.Cells[30, 36].Value = trip.OSNOVANIE + " от " + trip.OSNOVANIEDATE.Value.ToString("dd.MM.yyyy");
                    }
                    else
                    {
                        excelsheets.Cells[30, 36].Value = trip.OSNOVANIE;
                    }
                }
                else
                {
                    Worksheet excelsheets = excelappworkbooks.Worksheets.Item[1];
                    OUR_ORG   org         = model.OUR_ORG.First();
                    if (trip.PRIKAZ.ISPROJECT.Equals("1"))
                    {
                        excelsheets.Cells[13, 19].Value = "ПРОЕКТ ПРИКАЗА";
                        excelsheets.Cells[14, 19].Value = "(распоряжения)";
                    }
                    else
                    {
                        excelsheets.Cells[13, 19].Value = "ПРИКАЗ";
                        excelsheets.Cells[14, 19].Value = "(распоряжение)";
                    }

                    excelsheets.Cells[7, 1].Value = org.NAME;
                    excelsheets.Cells[7, 45]      = org.OKPO;
                    excelsheets.Cells[13, 35]     = trip.PRIKAZ.NUMDOC;
                    if (trip.PRIKAZ.CREATEDATE != null)
                    {
                        excelsheets.Cells[13, 48] = trip.PRIKAZ.CREATEDATE.Value.ToString("dd.MM.yyyy");
                    }
                    PERSONCARD_IN_TRIP person = trip.PERSONCARD_IN_TRIP.First();
                    excelsheets.Cells[18, 1].Value  = person.SURNAME + " " + person.NAME + " " + person.MIDDLENAME;
                    excelsheets.Cells[18, 47].Value = person.TABEL_NUM;
                    if (person.PODRAZDELORG != null)
                    {
                        excelsheets.Cells[20, 1].Value = person.PODRAZDELORG.NAME;
                    }
                    excelsheets.Cells[22, 1].Value = person.JOB_POS.NAME;
                    int i = 0;
                    foreach (TRIP_ORG tripOrg in trip.TRIP_ORG)
                    {
                        if (excelsheets.Cells[24 + i, 1].Text.Length > 100)
                        {
                            if (i == 0)
                            {
                                i += 2;
                            }
                            else
                            {
                                i++;
                            }
                        }
                        excelsheets.Cells[24 + i, 1].Value += tripOrg.PLACE_TRIP.NAME;
                        excelsheets.Cells[24 + i, 1].Value += ", " + tripOrg.NAME;
                        excelsheets.Cells[24 + i, 1].Value += " ; ";
                    }
                    excelsheets.Cells[33, 3].Value  = person.STARTDATE.Value.Day;
                    excelsheets.Cells[33, 7].Value  = person.STARTDATE.Value.ToString("MMMM");
                    excelsheets.Cells[33, 21].Value = person.STARTDATE.Value.ToString("yy");

                    excelsheets.Cells[33, 30].Value = person.ENDDATE.Value.Day;
                    excelsheets.Cells[33, 34].Value = person.ENDDATE.Value.ToString("MMMM");
                    excelsheets.Cells[33, 48].Value = person.ENDDATE.Value.ToString("yy");

                    excelsheets.Cells[31, 8].Value  = (int)person.ENDDATE.Value.Subtract(person.STARTDATE.Value).TotalDays;
                    excelsheets.Cells[35, 6].Value  = person.GOAL;
                    excelsheets.Cells[38, 18].Value = person.FINANCE;



                    if (trip.OSNOVANIEDATE != null)
                    {
                        excelsheets.Cells[42, 15].Value = trip.OSNOVANIE + " от " + trip.OSNOVANIEDATE.Value.ToString("dd.MM.yyyy");
                    }
                    else
                    {
                        excelsheets.Cells[42, 15].Value = trip.OSNOVANIE;
                    }
                }
            }
            catch (Exception except)
            {
                Console.Error.WriteLine(except.Message);
            }
            MyMsgBox.showInfo("Готово!");
            excelappworkbooks.SaveAs(savePath);
            exApp.Quit();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string aqe = @"""";

            string[] ayirt = textBox2.Text.Replace(" ", string.Empty).Split(',');
            int      jh    = 0;

            foreach (char lk in textBox2.Text)
            {
                if (lk == '"')
                {
                    jh++;
                }
            }
            int sonuc = jh % ayirt.Length;

            if (string.IsNullOrEmpty(textBox1.Text))
            {
                MessageBox.Show("Please type password", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("Please type to crypt extension!", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (textBox2.Text.Contains("."))
            {
                MessageBox.Show("Please don't type dot into the extensions", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (!textBox2.Text.Contains('"') || !textBox2.Text.Contains(",") && checkBox2.Checked == false)
            {
                MessageBox.Show("Please type into the extensions textbox , (comma) or " + '"' + " (double quotes)", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (string.IsNullOrEmpty(textBox3.Text))
            {
                MessageBox.Show("Please type path to crypting!", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (string.IsNullOrEmpty(textBox6.Text))
            {
                MessageBox.Show("Please type your crypt extension!", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            else if (!textBox6.Text.Contains("."))
            {
                MessageBox.Show("Please type into the your crypt textbox dot!", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (textBox2.Text.Contains(aqe + aqe) && sonuc == 0 || textBox2.Text.Contains(aqe + " " + aqe))
            {
                MessageBox.Show("Please type into the extension textbox comma", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (textBox2.Text.Length - textBox2.Text.LastIndexOf(",") == 1 || textBox2.Text.Length - textBox2.Text.LastIndexOf(",") == 2)
            {
                MessageBox.Show("Please check unnecessary comma in extensions text", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (sonuc != 0)
            {
                MessageBox.Show("Please check double quotes in extensions textbox!", "Exclamation!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                SaveFileDialog dosya = new SaveFileDialog();
                dosya.Filter = "Exe | *.exe";
                if (dosya.ShowDialog() == DialogResult.OK)
                {
                    textBox2.Text = textBox2.Text.Replace(" ", string.Empty);
                    using (StreamReader reader = new StreamReader("crypt.source"))
                    {
                        try
                        {
                            string j   = "+" + '@' + '"' + "\\" + '"';
                            string kod = Base64Decode(reader.ReadToEnd()).Replace("HANGIDIZINLER", textBox3.Text.Replace("[Desktop]", "Environment.GetFolderPath(Environment.SpecialFolder.Desktop)" + j).Replace("[Documents]", "Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)" + j).Replace("[Pictures]", "Environment.GetFolderPath(Environment.SpecialFolder.MyPictures)" + j)).Replace("HANGIUZANTILER", textBox2.Text.Replace(" ", string.Empty)).Replace("PASSWORD", textBox1.Text).Replace(".UZANTICRYPT", textBox6.Text).Replace(
                                "NOTISMI", textBox5.Text).Replace("MESAJ", textBox4.Text + Environment.NewLine + textBox7.Text).Replace("DEGER", s);

                            string ayar = " ";
                            if (Builder.Build(dosya.FileName, kod, ayar, icon))
                            {
                                MessageBox.Show("Build was successfully!\n" + dosya.FileName, "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                using (StreamWriter sw = File.AppendText("log.txt"))
                                {
                                    sw.WriteLine("Password is:   " + textBox1.Text + "   Hour: " + string.Format("{0:HH:mm:ss}", DateTime.Now) + " Date: " + DateTime.Now.ToString("d/M/yyyy") + " Victim Name: " + textBox7.Text);
                                }
                            }
                        }
                        catch (Exception ex) { MessageBox.Show(ex.Message, "Haahha", MessageBoxButtons.OK, MessageBoxIcon.Error); }
                    }
                }
            }
        }
Esempio n. 36
0
        private void SaveNodeFormats(ObjectEditor editor, bool UseSaveDialog, bool UseCompressDialog)
        {
            foreach (var node in editor.GetNodes())
            {
                IFileFormat format = null;
                if (node is ArchiveBase)
                {
                    format = (IFileFormat)((ArchiveBase)node).ArchiveFile;

                    if (node is ArchiveRootNodeWrapper)
                    {
                        ((ArchiveRootNodeWrapper)node).UpdateFileNames();
                    }
                }
                else if (node is IFileFormat)
                {
                    format = ((IFileFormat)node);
                }
                if (format != null)
                {
                    if (!format.CanSave)
                    {
                        return;
                    }

                    string FileName = format.FilePath;
                    if (!File.Exists(FileName))
                    {
                        UseSaveDialog = true;
                    }

                    if (UseSaveDialog)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.Filter   = Utils.GetAllFilters(format);
                        sfd.FileName = format.FileName;

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

                        FileName = sfd.FileName;
                    }
                    Cursor.Current = Cursors.WaitCursor;

                    //Use the export method for particular formats like bfres for special save operations
                    if (format is STGenericWrapper && !(format is STGenericTexture))
                    {
                        ((STGenericWrapper)format).Export(FileName);
                        return;
                    }

                    if (node is ArchiveBase)
                    {
                        STFileSaver.SaveFileFormat(((IFileFormat)((ArchiveBase)node).ArchiveFile), FileName, UseCompressDialog);
                    }
                    else
                    {
                        STFileSaver.SaveFileFormat(((IFileFormat)node), FileName, UseCompressDialog);
                    }
                    Cursor.Current = Cursors.Default;
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "")
            {
                MessageBox.Show("往生者姓名請勿空白!!!", "提示訊息", MessageBoxButtons.OK, MessageBoxIcon.Error);
               // MessageBox.Show("往生者姓名請問空白!!!");
            }
            else
            {
                SaveFileDialog sf = new SaveFileDialog();//使用存檔的對話框
                sf.DefaultExt = "doc";
                sf.Filter = "Word document|*.doc";
                sf.AddExtension = true;
                sf.RestoreDirectory = false;
                sf.Title = "另存新檔";
                sf.InitialDirectory = @"C:/";
                Word._Application word_app = new Microsoft.Office.Interop.Word.Application();
                Word._Document word_document;
                Object oEndOfDoc = "\\endofdoc";
                object path;//設定一些object宣告
                object oMissing = System.Reflection.Missing.Value;
                object oSaveChanges = Word.WdSaveOptions.wdSaveChanges;
                object oformat = Word.WdSaveFormat.wdFormatDocument97;//wdFormatDocument97為Word 97-2003 文件 (*.doc)
                object start = 0, end = 0;
                if (word_app == null)//若無office程式則無法使用
                    MessageBox.Show("無法建立word檔案!!");
                else
                {
                    if (sf.ShowDialog() == DialogResult.OK)
                    {
                        path = sf.FileName;
                        word_app.Visible = false;//不顯示word程式
                        word_app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;//不顯示警告或彈跳視窗。如果出現彈跳視窗,將選擇預設值繼續執行。
                        word_document = word_app.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);//新增檔案

                        word_document.PageSetup.TopMargin = word_app.CentimetersToPoints(float.Parse("1.5"));
                        word_document.PageSetup.BottomMargin = word_app.CentimetersToPoints(float.Parse("1.5"));
                        word_document.PageSetup.LeftMargin = word_app.CentimetersToPoints(float.Parse("2"));
                        word_document.PageSetup.RightMargin = word_app.CentimetersToPoints(float.Parse("2"));

                        Word.Range rng = word_document.Range(ref start, ref end);


                        Word.Paragraph oPara1;
                        oPara1 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara1.Range.Text = "三寶尊佛前引過";
                        oPara1.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        oPara1.Range.Font.Size = 24;
                        // oPara1.Range.Font.Bold = 1;
                        // oPara1.Format.SpaceAfter = 36;    //24 pt spacing after paragraph.//在段落之後 24 pt 空格
                        oPara1.Range.InsertParagraphAfter();

                        //Insert a paragraph at the end of the document.
                        // ' 在文件的尾端插入一個段落。            
                        Word.Paragraph oPara2;
                        object oRng = word_document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        oPara2 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara2.Range.Text = textBox1.Text+"府              末切日期";
                        oPara2.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                        oPara2.Range.Font.Size = 14;
                        // oPara2.Format.SpaceAfter = 6;
                        oPara2.Range.InsertParagraphAfter();

                        //Insert another paragraph.
                        //插入另外一個段落。
                      
                        /*------------------------------------*/
                        string dd = dateTimePicker1.Text;
                        dd = dd.Replace("年", ",").Replace("月", ",").Replace("日", ",");
                        string[] ddd = { " ", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十", "二十一", "二十二", "二十三", "二十四", "二十五", "二十六", "二十七", "二十八", "二十九", "三十", "三十一" };
                        string[] ss = { "", "秦廣王", "楚江王", "宋帝王", "伍官王", "閻羅王", "變成王", "泰山王", "平等王", "都市王", "輪轉王" };
                        string[] arrday = { "", "首七", "二七", "三七", "四七", "五七", "六七", "滿七", "百日", "對年" };
                        string[] family = { "", "(兒子)", "", "(女兒)", "", "(孫輩)", "", "(圓滿)", "" };
                        string[] week = { "", "一", "二", "三", "四", "五", "六","日" };
                        Dictionary<int, int> lsCalendar = new Dictionary<int, int>() { { 2020, 4 } };
                        string[] arr = dd.Split(",".ToCharArray());
                        int a = (int)decimal.Parse(arr[0]);
                        int b = (int)decimal.Parse(arr[1]);
                        int c = (int)decimal.Parse(arr[2]);


                        Word.Paragraph oPara3;

                        oRng = word_document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        oPara3 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara3.Range.Text = "年國曆     月      日";
                        oPara3.Range.Font.Size = 14;
                        oPara3.Range.Font.Bold = 0;
                        // oPara3.Format.SpaceAfter = 6;
                        Word.Paragraph oPara10;
                        oPara10 = word_document.Content.Paragraphs.Add(ref oMissing);

                        oPara10.Range.Text =  (a-1911)+"  年國曆  " + ddd[b] + "月" + ddd[c] + "日";
                        oPara10.Range.Font.Size = 14;
                        oPara10.Range.Font.Bold = 0;
                        // oPara10.Format.SpaceAfter = 6;

                        DateTime dtObj = new DateTime(2018, 6, 11);

                        //以 月份 日, 年 的格式輸出
                        string outputDate = dtObj.ToString("MMMM dd, yyyy", new CultureInfo("zh-tw"));
                       // label7.Text = outputDate;
                        DateTime dt = new DateTime(a, b, c);
                        Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-tw");
                        System.Globalization.TaiwanCalendar TC = new System.Globalization.TaiwanCalendar();
                        System.Globalization.TaiwanLunisolarCalendar TA = new System.Globalization.TaiwanLunisolarCalendar();
                        //   label1.Text = string.Format("明國:{0}/{1}/{2} <br>", TC.GetYear(dt), TC.GetMonth(dt), TC.GetDayOfMonth(dt)) + ddd[TC.GetDayOfMonth(dt)];
                        //  label2.Text = string.Format("農歷:{0}/{1}/{2} <br>", TA.GetYear(dt), TA.GetMonth(dt), TA.GetDayOfMonth(dt));
                        string  Date_of_death = "農歷"+ddd[TA.GetMonth(dt)]+"月"+ ddd[TA.GetDayOfMonth(dt)] + "日";
                        //   label2.Text = string.Format("農歷:{0}<br>", TA.AddDays(dt, 365));
                        int count = 4;

                        for (int i = 1; i <= 7; i++)
                        {
                            int d = 7 * i;
                            int dn;
                            //  label3.Text += arrday[i] + " " + dt.AddDays(d - 1).ToString("MMMM dd, yyyy", new CultureInfo("zh-tw")) + Environment.NewLine;
                            /*
                            Word.Paragraph oPara4;
                            oRng = word_document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                            oPara4 = word_document.Content.Paragraphs.Add(ref oRng);
                            Word.Paragraph oPara5;
                            oRng = word_document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                            oPara5 = word_document.Content.Paragraphs.Add(ref oRng);
                            oPara4.Range.Text += ss[i] ;
                            oPara4.Range.Font.Superscript = 0;
                            oPara4.Range.Font.Size = 14;
                            oPara4.Range.Font.Bold = 0;*/
                            Word.Paragraph oPara = word_document.Content.Paragraphs.Add(ref oMissing);
                            if (i == 2)
                            {
                                dn = int.Parse(dt.AddDays((d / 2) - 1).ToString("dd"));
                              //  label3.Text += "地方風俗 " + arrday[i] + " " + dt.AddDays((d / 2) - 2).ToString("MM 月dd", new CultureInfo("zh-tw")) + "日" + Environment.NewLine;
                                oPara.Range.Text += "   地方風俗 " + "國曆  " + dt.AddDays((d / 2) - 2).ToString("MMMM", new CultureInfo("zh-tw")) +ddd[dn].PadLeft(3,' ')+ "日 上午  八時至十七時之間("+week[int.Parse(TC.GetDayOfWeek(dt.AddDays((d / 2) - 2)).ToString("d"))]+")";
                            }
                            dn = int.Parse(dt.AddDays(d - 1).ToString("dd"));
                            /*  oPara5.Range.Text += ss[i]+" "+arrday[i] + " " + dt.AddDays(d - 1).ToString("MMMM dd", new CultureInfo("zh-tw"))+ddd[dn] ;
                              oPara5.Range.Font.Superscript = 1;
                              oPara5.Range.Font.Size = 14;
                              oPara5.Range.Font.Bold = 0;
                              // oPara4.Format.SpaceAfter = 6;
                              // oPara4.Range.InsertParagraphAfter();*/

                            string s7 = dt.AddDays(d - 1).ToString("MMMM", new CultureInfo("zh-tw")) + ddd[dn].PadLeft(3,' ') + "日";
                            
                            oPara.Range.Text += ss[i] + "   " + arrday[i] + "  國曆  " +s7.PadRight(7,' ') + "上午  八時至十七時之間("+week[(int)decimal.Parse(TC.GetDayOfWeek(dt.AddDays(d-1)).ToString("d"))]+")"+family[i];
                            // oPara.Range.InsertParagraphAfter();
                            /*  object oStart = oPara.Range.Start + 4;
                              object oEnd = oPara.Range.Start + oPara.Range.Text.Length;
                              Word.Range rSuperscript = word_document.Range(ref oStart, ref oEnd);
                              rSuperscript.Font.Superscript = 1;*/
                            count += 1;
                        }
                        /*
                        Word.Paragraph oPara14;
                        oRng = word_document.Bookmarks.get_Item(ref oEndOfDoc).Range;
                        oPara14 = word_document.Content.Paragraphs.Add(ref oRng);

                        oPara14.Range.Font.Bold = 0; // 0 為非粗體, 1 為粗體
                        oPara14.Range.Font.Superscript = 0;
                        oPara14.Range.Font.Name = "標楷體"; // 字型
                        oPara14.Range.Font.Size = 14; // 字體大小
                                                     // oPara4.Range.Font.Color = WdColor.wdColorLime; // 顏色
                                                     // oPara4.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; // 置中

                        oPara14.Range.Text = "作七時刻均為概定 請自行擬定時刻 以上時間參考用";
                        oPara14.Range.InsertParagraphAfter();
                        oPara14.Range.Text = "一般做七『例如星期三逝世-每星期二為七』";
                        oPara14.Range.Font.Name = "標楷體";
                        oPara14.Range.Font.Superscript = 0;
                        oPara14.Range.InsertParagraphAfter();
                        oPara14.Range.Text = "民間風俗做法頭七可作前一日晚上21-23時『交時』";
                        oPara14.Range.Font.Name = "標楷體";
                        oPara14.Range.Font.Superscript = 0;
                        oPara14.Range.InsertParagraphAfter();
                        oPara14.Range.Text = "出殯後之做七-可於自宅.(靈骨安置地點或寺廟祭祀)";
                        oPara14.Range.Font.Name = "標楷體";
                        oPara14.Range.Font.Superscript = 0;
                        oPara14.Range.InsertParagraphAfter();
                       */
                        //百日
                        int dn99 = int.Parse(dt.AddDays(99).ToString("dd"));
                        //  dt = dt.AddDays(99);
                        string s99 = dt.AddDays(99).ToString("MMMM", new CultureInfo("zh-tw")) + ddd[dn99].PadLeft(3,' ') + "日";
                        Word.Paragraph oPara4 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara4.Range.Text += ss[8] + "   " + arrday[8] + "  國曆  " + s99.PadRight(7,' ')+ "上午  八時至十七時之間("+week[int.Parse(TC.GetDayOfWeek(dt.AddDays(99)).ToString("d"))]+")";
                        oPara4.Range.InsertParagraphAfter();
                        //對年
                        string result = string.Empty;
                        System.Globalization.TaiwanLunisolarCalendar tls = new System.Globalization.TaiwanLunisolarCalendar();
                        DateTime begin = tls.AddDays(DateTime.Now, 0);
                        Boolean leap = tls.IsLeapYear(TA.GetYear(dt.AddYears(1)));
                        DateTime dtt = tls.ToDateTime(TA.GetYear(dt), TA.GetMonth(dt), TA.GetDayOfMonth(dt), 0, 0, 0, 0);
                        
                        if (leap)
                        {
                            if (TA.GetMonth(dtt) > lsCalendar[(int)a])
                            {

                                dtt = tls.AddMonths(dtt, -1);
                            }
                            //label5.Text = "適逢" + TA.GetYear(dt.AddYears(1)) + "年閏月,因而農曆月份須提前一個月";
                            dtt = tls.AddMonths(dtt, -1);
                        }
                        dtt = tls.AddYears(dtt, 1);

                        TimeSpan tss = dtt - begin;
                        int day = tls.GetDayOfMonth(dtt);
                        int month = tls.GetMonth(dtt);
                        int year = tls.GetYear(dtt);

                       // label4.Text = string.Format("國歷{0}\n農曆{0}年{1}月{2}日", year, month, day, DateTime.Now.Add(tss).ToString("yyyy/MM/dd"));
                        int dn365 = int.Parse(DateTime.Now.Add(tss).ToString("dd"));
                        string s365 = string.Format("{0}", DateTime.Now.Add(tss).ToString("MMMM")) + ddd[dn365].PadLeft(3,' ') + "日";
                        Word.Paragraph oPara5 = word_document.Content.Paragraphs.Add(ref oMissing);
                        int year365 = int.Parse(DateTime.Now.Add(tss).ToString("yyyy"))-1911;
                        oPara5.Range.Text = ss[9] + "   " + arrday[9] + "  國曆  " + s365.PadRight(7,' ')+ "上午  八時至十七時之間("+week[int.Parse(TC.GetDayOfWeek(DateTime.Now.Add(tss)).ToString("d"))]+")"+"("+ year365 + ")";
                        oPara5.Range.InsertParagraphAfter();

                        Word.Paragraph oPara6 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara6.Range.Text = "民間風俗-逝者(對年-足一年)不閏月-閏月-正常計算";
                        Word.Paragraph oPara7 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara6.Range.Text = "忌日祭祀均以農曆計算-"+ Date_of_death;
                        Word.Paragraph oPara3y = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara6.Range.Text = "輪轉王  三年 國曆  月   日     時至  時";
                        oPara6.Range.InsertParagraphAfter();
                        Word.Paragraph oPara8 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara8.Range.Text = "拾殿冥王判超昇";
                        oPara8.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                        oPara8.Range.Font.Size = 24;
                        Word.Paragraph oPara9 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara8.Range.Text = "作七時刻均為概定 請自行擬定時刻 以上時間參考用";
                        oPara8.Range.Font.Size = 14;
                        Word.Paragraph oPara11 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara8.Range.Text = "一般做七『例如星期三逝世-每星期二為七』";
                        oPara8.Range.Font.Size = 14;
                        Word.Paragraph oPara12 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara8.Range.Text = "民間風俗做法頭七可作前一日晚上21-23時『交時』";
                        oPara8.Range.Font.Size = 14;
                        Word.Paragraph oPara13 = word_document.Content.Paragraphs.Add(ref oMissing);
                        oPara8.Range.Text = "出殯後之做七-可於自宅.(靈骨安置地點或寺廟祭祀)";
                        oPara8.Range.Font.Size = 14;
                        //  label6.Text = string.Format("農歷:{0}/{1}/{2} <br>", TA.GetYear(dt), TA.GetMonth(dt), TA.GetDayOfMonth(dt));

                        /*    Word.Table table = word_document.Tables.Add(rng, 10, 6, ref oMissing, ref oMissing);//設定表格
                           table.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;//內框線
                           table.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;//外框線
                           table.Select();//選取指令
                           word_app.Selection.Font.Name = "標楷體";//設定選取的資料字型
                           word_app.Selection.Font.Size = 10;//設定文字大小
                           word_app.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; //將其設為靠中間
                            for (int i = 1; i <= 10; i++)//將表格的資料寫入word檔案裡,第一列的值為1,第一行的值為1
                                 for (int j = 1; j <= 6; j++)
                                 {
                                     table.Cell(i, j).Range.Text = i + "," + j;
                                     table.Cell(i, j).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                                     table.Columns[j].Width = 70f;
                                     table.Rows[i].Height = 70f;
                                 }*/

                        word_document.SaveAs(ref path, ref oformat, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing
                        , ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);//存檔
                        word_document.Close(ref oMissing, ref oMissing, ref oMissing);//關閉
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(word_document);//釋放
                        word_document = null;
                        word_app.Quit(ref oMissing, ref oMissing, ref oMissing);//結束
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(word_app);//釋放
                        word_app = null;
                        MessageBox.Show("寫入檔案,儲存成功", " 提示訊息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    sf.Dispose();//釋放
                    sf = null;
                }

            }
        }
Esempio n. 38
0
        public static void SaveOrderIntoFile(string prologue, List <PaymentRecord> content, List <List <int> > filialMarks,
                                             string epilogue)
        {
            List <String> lines = new List <String>();
            int           count = content.Count;

            for (int i = 0; i < count; i++)
            {
                if (filialMarks[i].Count == 1)
                {
                    int filialIndex = Array.IndexOf(filialSpecialAccounts, content[i].correspondentAccount);

                    if (filialIndex != -1)
                    {
                        lines.Add(ChangedPaymentRecord(content[i], filialIndex, true));
                    }
                    else
                    {
                        lines.Add(ChangedPaymentRecord(content[i], filialMarks[i].First(), false));
                    }
                }
                else
                {
                    int filialCount = filialMarks[i].Count;

                    for (int j = 0; j < filialCount; j++)
                    {
                        if (j == 0)
                        {
                            lines.Add(ChangedPaymentRecord(content[i], filialMarks[i][j], true, true, false));
                        }
                        else
                        {
                            lines.Add(ChangedPaymentRecord(content[i], filialMarks[i][j], true, false, false));
                        }
                    }
                }
            }

            String allLines = "";

            foreach (String line in lines)
            {
                allLines += line + "\r\n";
            }

            SaveFileDialog dialog = new SaveFileDialog();

            dialog.Filter           = "txt files (*.txt)|*.txt";
            dialog.RestoreDirectory = true;
            dialog.FileName         = MainForm.fileName.Remove(MainForm.fileName.Length - 4) + "_П_";
            resultFileName          = dialog.FileName;

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

            File.WriteAllText(dialog.FileName, prologue, Encoding.Default);
            File.AppendAllText(dialog.FileName, allLines, Encoding.Default);
            File.AppendAllText(dialog.FileName, epilogue, Encoding.Default);
        }
Esempio n. 39
0
        /// <summary>
        /// Save Files attached to query
        /// </summary>
        /// <param name="doc">Document object </param>
        private void Savefile(Document doc)
        {
            saveFileDialog.FileName = Path.GetFileName(doc.Filename);

            if (doc.Filename.EndsWith("xml", StringComparison.OrdinalIgnoreCase))
            {
                saveFileDialog.FilterIndex = 2;
            }
            else if (!doc.Filename.EndsWith("txt", StringComparison.OrdinalIgnoreCase))
            {
                string fileExtension = Path.GetExtension(doc.Filename);
                if (fileExtension.NullOrEmpty())
                {
                    if (!doc.MimeType.NullOrEmpty() && doc.MimeType.IndexOf("/") >= 0)
                    {
                        fileExtension         = "." + doc.MimeType.Substring(doc.MimeType.IndexOf('/') + 1);
                        saveFileDialog.Filter = string.Format("{1} files (*{0})|*{0}|{2}", fileExtension, fileExtension.Substring(1, 1).ToUpper() + fileExtension.Substring(2), saveFileDialog.Filter);
                    }
                }
                else
                {
                    saveFileDialog.Filter = string.Format("{1} files (*{0})|*{0}|{2}", fileExtension, fileExtension.Substring(1, 1).ToUpper() + fileExtension.Substring(2), saveFileDialog.Filter);
                }
            }

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

            var sSaveLocation = saveFileDialog.FileName;

            var progress = new ProgressForm("Saving File", "Transferring the File from the Portal...")
            {
                Indeteminate = doc.Size <= 0
            };

            byte[] buffer = new byte[0x100000];
            Observable.Using(() => File.Create(sSaveLocation),
                             outStream =>
                             Observable.Using(() =>
            {
                Stream dcStream;
                if (isRequestView == true)
                {
                    if (doc.MimeType != "application/vnd.pmn.lnk")
                    {
                        dcStream = new DocumentChunkStream(Guid.Parse(doc.DocumentID), networkSetting);
                    }
                    else
                    {
                        string lnk = string.Empty;
                        using (var docStream = new DocumentChunkStream(Guid.Parse(doc.DocumentID), networkSetting))
                        {
                            lnk = new StreamReader(docStream).ReadToEnd();
                            docStream.Close();
                        }
                        if (networkSetting.SftpClient == null)
                        {
                            networkSetting.SftpClient = new SFTPClient(networkSetting.Host, networkSetting.Port, networkSetting.Username, networkSetting.DecryptedPassword);
                        }
                        dcStream = networkSetting.SftpClient.FileStream(lnk);
                    }
                }
                else
                {
                    if (_cache != null && _cache.Enabled)
                    {
                        dcStream = _cache.GetDocumentStream(Guid.Parse(doc.DocumentID));
                    }
                    else
                    {
                        processor.ResponseDocument(requestId, doc.DocumentID, out dcStream, 60000);
                    }
                }
                return(dcStream);
            },
                                              inStream =>
                                              Observable.Return(0, Scheduler.Default).Repeat()
                                              .Select(_ => inStream.Read(buffer, 0, buffer.Length))
                                              .TakeWhile(bytesRead => bytesRead > 0)
                                              .Do(bytesRead => outStream.Write(buffer, 0, bytesRead))
                                              .Scan(0, (totalTransferred, bytesRead) => totalTransferred + bytesRead)
                                              .ObserveOn(this)
                                              //.Do(totalTransferred => progress.Progress = totalTransferred * 100 / Math.Max(doc.Size, 1))
                                              .Do(totalTransferred => progress.Progress = totalTransferred * 100 / Math.Max((inStream.CanSeek ? (int)inStream.Length : doc.Size), 1))
                                              )
                             )
            .SubscribeOn(Scheduler.Default)
            .TakeUntil(progress.ShowAndWaitForCancel(this))
            .ObserveOn(this)
            .Finally(progress.Dispose)
            .LogExceptions(log.Error)
            .Do(_ => {},
                ex => { MessageBox.Show(this, "There was an error saving the file: \r\n\r\n" + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); },
                () => { MessageBox.Show(this, "File downloaded successfully", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); })
            .Catch()
            .Subscribe();
        }
Esempio n. 40
0
        private void btnPrint_Click(object sender, EventArgs e)
        {
            // 根據日期區間取得申報案件資料
            DataTable dt = DAO.Case.GetCaseDataByDateRange(dtStart.Value.ToString("yyyy/MM/dd"), dtEnd.Value.ToString("yyyy / MM / dd"));

            Dictionary <string, List <DataRow> > dicCaseDataByKey = new Dictionary <string, List <DataRow> >();

            // 資料整理
            foreach (DataRow row in dt.Rows)
            {
                string key = "" + row["place_name"] + row["equip_name"];

                if (!dicCaseDataByKey.ContainsKey(key))
                {
                    dicCaseDataByKey.Add(key, new List <DataRow>());
                }
                dicCaseDataByKey[key].Add(row);
            }
            // 產出報表
            Workbook wb = new Workbook(new MemoryStream(Properties.Resources.統計申報案件樣板));

            //wb.Worksheets[0].Cells[0].PutValue("位置");
            //wb.Worksheets[0].Cells[1].PutValue("設施");
            //wb.Worksheets[0].Cells[2].PutValue("申報次數");

            int rowIndex = 1;

            foreach (string key in dicCaseDataByKey.Keys)
            {
                int    colIndex  = 0;
                string placeName = "" + dicCaseDataByKey[key][0]["place_name"];
                string equipName = "" + dicCaseDataByKey[key][0]["equip_name"];
                int    count     = dicCaseDataByKey[key].Count();

                // 複製樣板格式
                wb.Worksheets[0].Cells.CopyRow(wb.Worksheets[0].Cells, 1, rowIndex);

                wb.Worksheets[0].Cells[rowIndex, colIndex++].PutValue(placeName);
                wb.Worksheets[0].Cells[rowIndex, colIndex++].PutValue(equipName);
                wb.Worksheets[0].Cells[rowIndex, colIndex++].PutValue(count);

                rowIndex++;
            }

            #region 儲存資料
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                string         fileName       = string.Format("{0}_{1}統計申報案件報表", dtStart.Value.ToString("yyyy_MM_dd"), dtEnd.Value.ToString("yyyy_MM_dd"));
                saveFileDialog.Title    = fileName;
                saveFileDialog.FileName = string.Format("{0}.xlsx", fileName);
                saveFileDialog.Filter   = "Excel (*.xlsx)|*.xlsx|所有檔案 (*.*)|*.*";

                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    DialogResult result = new DialogResult();
                    try
                    {
                        wb.Save(saveFileDialog.FileName);
                        result = MsgBox.Show("檔案儲存完成,是否開啟檔案?", "是否開啟", MessageBoxButtons.YesNo);
                    }
                    catch (Exception ex)
                    {
                        MsgBox.Show(ex.Message);
                        return;
                    }

                    if (result == DialogResult.Yes)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(saveFileDialog.FileName);
                        }
                        catch (Exception ex)
                        {
                            MsgBox.Show("開啟檔案發生失敗:" + ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    this.Close();
                }
            }
            #endregion
        }
Esempio n. 41
0
        /// <summary>
        /// Uses a Microsoft OneDrive Cloud Storage Provider (OneDrive Consumer, OneDrive for Business, Microsoft Graph) to download a KeePass database
        /// </summary>
        /// <param name="databaseConfig">Configuration of the database to sync</param>
        /// <param name="updateStatus">Action to write status messages to to display in the UI</param>
        /// <returns>Path to the local KeePass database or NULL if the process has been aborted</returns>
        public static async Task <string> OpenFromOneDriveCloudProvider(Configuration databaseConfig, Action <string> updateStatus)
        {
            // Connect to OneDrive
            var oneDriveApi = await Utilities.GetOneDriveApi(databaseConfig);

            if (oneDriveApi == null)
            {
                switch (databaseConfig.CloudStorageType.Value)
                {
                case CloudStorageType.OneDriveConsumer: updateStatus("Failed to connect to OneDrive"); break;

                case CloudStorageType.MicrosoftGraph:
                case CloudStorageType.MicrosoftGraphDeviceLogin:
                    updateStatus("Failed to connect to Microsoft Graph"); break;

                default: updateStatus("Failed to connect to cloud service"); break;
                }
                return(null);
            }

            // Save the RefreshToken in the configuration so we can use it again next time
            databaseConfig.RefreshToken = oneDriveApi.AccessToken.RefreshToken;

            // Fetch details about this OneDrive account
            var oneDriveAccount = await oneDriveApi.GetDrive();

            databaseConfig.OneDriveName = oneDriveAccount.Owner.User.DisplayName;

            // Ask the user to select the database to open on OneDrive
            var oneDriveFilePickerDialog = new Forms.OneDriveFilePickerDialog(oneDriveApi)
            {
                ExplanationText          = "Select the KeePass database to open. Right click for additional options.",
                AllowEnteringNewFileName = false
            };
            await oneDriveFilePickerDialog.LoadFolderItems();

            var result = oneDriveFilePickerDialog.ShowDialog();

            if (result != DialogResult.OK || string.IsNullOrEmpty(oneDriveFilePickerDialog.FileName))
            {
                KeePassDatabase.UpdateStatus("Open KeePass database from OneDrive aborted");
                return(null);
            }

            databaseConfig.RemoteDatabasePath = (oneDriveFilePickerDialog.CurrentOneDriveItem.ParentReference != null ? oneDriveFilePickerDialog.CurrentOneDriveItem.ParentReference.Path : "") + "/" + oneDriveFilePickerDialog.CurrentOneDriveItem.Name + "/" + oneDriveFilePickerDialog.FileName;
            databaseConfig.RemoteDriveId      = oneDriveFilePickerDialog.CurrentOneDriveItem.RemoteItem != null ? oneDriveFilePickerDialog.CurrentOneDriveItem.RemoteItem.ParentReference.DriveId : oneDriveFilePickerDialog.CurrentOneDriveItem.ParentReference.DriveId != null ? oneDriveFilePickerDialog.CurrentOneDriveItem.ParentReference.DriveId : null;
            if (oneDriveFilePickerDialog.CurrentOneDriveItem.File != null || (oneDriveFilePickerDialog.CurrentOneDriveItem.RemoteItem != null && oneDriveFilePickerDialog.CurrentOneDriveItem.RemoteItem.File != null))
            {
                databaseConfig.RemoteItemId = oneDriveFilePickerDialog.CurrentOneDriveItem.File != null ? oneDriveFilePickerDialog.CurrentOneDriveItem.Id : oneDriveFilePickerDialog.CurrentOneDriveItem.RemoteItem.Id;
            }
            else
            {
                databaseConfig.RemoteFolderId = oneDriveFilePickerDialog.CurrentOneDriveItem.RemoteItem != null ? oneDriveFilePickerDialog.CurrentOneDriveItem.RemoteItem.Id : oneDriveFilePickerDialog.CurrentOneDriveItem.Id;
            }
            databaseConfig.RemoteFileName = oneDriveFilePickerDialog.FileName;

            // Retrieve the metadata of the KeePass database on OneDrive
            OneDriveItem oneDriveItem;

            if (string.IsNullOrEmpty(databaseConfig.RemoteItemId))
            {
                // We don't have the ID of the KeePass file, check if the database is stored on the current user its drive or on a shared drive
                OneDriveItem folder;
                if (string.IsNullOrEmpty(databaseConfig.RemoteDriveId))
                {
                    // KeePass database is on the current user its drive
                    folder = await oneDriveApi.GetItemById(databaseConfig.RemoteFolderId);
                }
                else
                {
                    // KeePass database is on a shared drive
                    folder = await oneDriveApi.GetItemFromDriveById(databaseConfig.RemoteFolderId, databaseConfig.RemoteDriveId);
                }

                // Locate the KeePass file in the folder
                oneDriveItem = await oneDriveApi.GetItemInFolder(folder, databaseConfig.RemoteFileName);

                // Check if the KeePass file has been found
                if (oneDriveItem != null)
                {
                    // Store the direct Id to the KeePass file so we can save several API calls on future syncs
                    databaseConfig.RemoteItemId = oneDriveItem.Id;
                    Configuration.Save();
                }
            }
            else
            {
                // We have the ID of the KeePass file, check if it's on the current user its drive or on a shared drive
                if (string.IsNullOrEmpty(databaseConfig.RemoteDriveId))
                {
                    // KeePass database is on the current user its drive
                    oneDriveItem = await oneDriveApi.GetItemById(databaseConfig.RemoteItemId);
                }
                else
                {
                    // KeePass database is on a shared drive
                    oneDriveItem = await oneDriveApi.GetItemFromDriveById(databaseConfig.RemoteItemId, databaseConfig.RemoteDriveId);
                }
            }

            if (oneDriveItem == null)
            {
                // KeePass database not found on OneDrive
                switch (databaseConfig.CloudStorageType.Value)
                {
                case CloudStorageType.OneDriveConsumer: updateStatus(string.Format("Unable to find the database {0} on your OneDrive", databaseConfig.KeePassDatabase.Name)); break;

                case CloudStorageType.MicrosoftGraph: updateStatus(string.Format("Unable to find the database {0} through Microsoft Graph", databaseConfig.KeePassDatabase.Name)); break;

                default: updateStatus("Failed to connect to cloud service"); break;
                }
                return(null);
            }

            // Show the save as dialog to select a location locally where to store the KeePass database
            var saveFiledialog = new SaveFileDialog
            {
                Filter          = "KeePass databases (*.kdbx)|*.kdbx|All Files (*.*)|*.*",
                Title           = "Select where to store the KeePass database locally",
                CheckFileExists = false,
                FileName        = oneDriveItem.Name
            };

            var saveFileDialogResult = saveFiledialog.ShowDialog();

            if (saveFileDialogResult != DialogResult.OK || string.IsNullOrEmpty(saveFiledialog.FileName))
            {
                updateStatus("Open KeePass database from OneDrive aborted");
                return(null);
            }

            // Download the KeePass database to the selected location
            updateStatus("Downloading KeePass database");
            await oneDriveApi.DownloadItemAndSaveAs(oneDriveItem, saveFiledialog.FileName);

            // The ETag changes with every request of the item so we use the CTag instead which only changes when the file changes
            databaseConfig.ETag = oneDriveItem.CTag;

            return(saveFiledialog.FileName);
        }
Esempio n. 42
0
        public void FileSaveVehicle()
        {
            //in the current application directory
            //string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            //string fieldDir = dir + "\\fields\\";

            string dirVehicle = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\AgOpenGPS\\Vehicles\\";

            string directoryName = Path.GetDirectoryName(dirVehicle);

            if ((directoryName.Length > 0) && (!Directory.Exists(directoryName)))
            {
                Directory.CreateDirectory(directoryName);
            }

            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Title            = "Save Vehicle";
            saveDialog.Filter           = "Text Files (*.txt)|*.txt";
            saveDialog.InitialDirectory = directoryName;

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter writer = new StreamWriter(saveDialog.FileName))
                {
                    writer.Write("Overlap," + Properties.Settings.Default.setVehicle_toolOverlap + ",");
                    writer.Write("ToolTrailingHitchLength," + Properties.Settings.Default.setVehicle_toolTrailingHitchLength + ",");
                    writer.Write("AntennaHeight," + Properties.Settings.Default.setVehicle_antennaHeight + ",");
                    writer.Write("LookAhead," + Properties.Settings.Default.setVehicle_lookAhead + ",");
                    writer.Write("AntennaPivot," + Properties.Settings.Default.setVehicle_antennaPivot + ",");

                    writer.Write("HitchLength," + Properties.Settings.Default.setVehicle_hitchLength + ",");
                    writer.Write("ToolOffset," + Properties.Settings.Default.setVehicle_toolOffset + ",");
                    writer.Write("TurnOffDelay," + Properties.Settings.Default.setVehicle_turnOffDelay + ",");
                    writer.Write("Wheelbase," + Properties.Settings.Default.setVehicle_wheelbase + ",");

                    writer.Write("IsPivotBehindAntenna," + Properties.Settings.Default.setVehicle_isPivotBehindAntenna + ",");
                    writer.Write("IsSteerAxleAhead," + Properties.Settings.Default.setVehicle_isSteerAxleAhead + ",");
                    writer.Write("IsToolBehindPivot," + Properties.Settings.Default.setVehicle_isToolBehindPivot + ",");
                    writer.Write("IsToolTrailing," + Properties.Settings.Default.setVehicle_isToolTrailing + ",");

                    writer.Write("Spinner1," + Properties.Settings.Default.setSection_position1 + ",");
                    writer.Write("Spinner2," + Properties.Settings.Default.setSection_position2 + ",");
                    writer.Write("Spinner3," + Properties.Settings.Default.setSection_position3 + ",");
                    writer.Write("Spinner4," + Properties.Settings.Default.setSection_position4 + ",");
                    writer.Write("Spinner5," + Properties.Settings.Default.setSection_position5 + ",");
                    writer.Write("Spinner6," + Properties.Settings.Default.setSection_position6 + ",");

                    writer.Write("Sections," + Properties.Settings.Default.setVehicle_numSections + ",");
                    writer.Write("ToolWidth," + Properties.Settings.Default.setVehicle_toolWidth + ",");

                    writer.Write("Reserved,0,");

                    writer.Write("Reserved,0,"); writer.Write("Reserved,0,");
                    writer.Write("Reserved,0,"); writer.Write("Reserved,0,"); writer.Write("Reserved,0,");
                    writer.Write("Reserved,0,"); writer.Write("Reserved,0,"); writer.Write("Reserved,0,");
                    writer.Write("Reserved,0");
                }
                //little show to say saved and where
                var form = new FormTimedMessage(this, 3000, "Saved in Folder: ", dirVehicle);
                form.Show();
            }
        }
Esempio n. 43
0
        private void buttonGenClient_Click(object sender, EventArgs e)
        {
            string serverIP   = this.textBoxServerIP.Text.Trim();
            string serverPort = this.textBoxServerPort.Text.Trim();
            int    serverPortNum;

            if (!int.TryParse(serverPort, out serverPortNum))
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(this.textBoxServiceName.Text))
            {
                return;
            }
            string serviceName          = this.textBoxServiceName.Text.Trim();
            string avatar               = this.pictureBoxAvatar.Tag.ToString();
            bool   showOriginalFilename = this.checkBoxShowOriginalFileName.Checked;

            // 保存配置
            this.buttonSaveServerSetting.PerformClick();

            SaveFileDialog dialog = new SaveFileDialog();

            dialog.Filter           = "可执行程序(*.exe)|*.exe|所有文件(*.*)|*.*";
            dialog.FilterIndex      = 1;
            dialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                ClientParameters para = new ClientParameters();
                para.SetServerIP(serverIP);
                para.ServerPort   = serverPortNum;
                para.ServiceName  = serviceName;
                para.OnlineAvatar = avatar;

                byte[] fileBytes = null;
                if (System.IO.File.Exists("RemoteControl.Client.dat"))
                {
                    // 读取本地文件
                    fileBytes = System.IO.File.ReadAllBytes("RemoteControl.Client.dat");
                }
                else
                {
                    MsgBox.Info("RemoteControl.Client.dat文件丢失!");
                    return;
                    // 读取资源文件
                    //fileBytes = ResUtil.GetResFileData("RemoteControl.Client.dat");
                }
                // 拷贝文件
                System.IO.File.WriteAllBytes(dialog.FileName, fileBytes);
                // 修改图标
                if (this.checkBoxAppIcon.Checked && this.pictureBoxAppIcon.Tag != null && System.IO.File.Exists(this.pictureBoxAppIcon.Tag.ToString()))
                {
                    IconChanger.ChangeIcon(dialog.FileName, this.pictureBoxAppIcon.Tag as string);
                }
                fileBytes = System.IO.File.ReadAllBytes(dialog.FileName);
                // 修改启动模式
                ClientParametersManager.WriteClientStyle(fileBytes,
                                                         this.checkBoxHideClient.Checked ? ClientParametersManager.ClientStyle.Hidden : ClientParametersManager.ClientStyle.Normal);
                if (!showOriginalFilename)
                {
                    // 隐藏原始文件名
                    ClientParametersManager.HideOriginalFilename(fileBytes);
                }
                // 修改参数
                ClientParametersManager.WriteParameters(fileBytes, dialog.FileName, para);
                MsgBox.Info("客户端生成成功!");
            }
        }
Esempio n. 44
0
        /// <summary>
        ///     rename the entry with all the hassle that accompanies it.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RenameToolStripMenuItemClick(object sender, EventArgs e)
        {
            var newFileDialog = new SaveFileDialog
            {
                AddExtension       = true,
                AutoUpgradeEnabled = true,
                CreatePrompt       = false,
                DefaultExt         = "gpg",
                InitialDirectory   = _config["PassDirectory"],
                Title = Strings.FrmMain_RenameToolStripMenuItemClick_Rename
            };

            if (newFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }

            var tmpFileName = newFileDialog.FileName;

            newFileDialog.Dispose();

            // ReSharper disable once AssignNullToNotNullAttribute
            Directory.CreateDirectory(Path.GetDirectoryName(tmpFileName));
            File.Copy(dirTreeView.SelectedNode.Tag + "\\" + listFileView.SelectedItem + ".gpg", tmpFileName);

            if (!Program.NoGit)
            {
                GitRepo.RemoveFile(dirTreeView.SelectedNode.Tag + "\\" + listFileView.SelectedItem + ".gpg");

                // add to git
                if (!GitRepo.Commit(tmpFileName))
                {
                    MessageBox.Show(
                        Strings.FrmMain_EncryptCallback_Commit_failed_,
                        Strings.Error,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }
            }

            // Check if we want to sync with remote
            if (_config["UseGitRemote"] == false || this.gitRepoOffline)
            {
                this.CreateNodes();
                return;
            }

            if (!Program.NoGit)
            {
                // sync with remote
                if (!GitRepo.Push(_config["GitUser"], DecryptConfig(_config["GitPass"], "pass4win")))
                {
                    MessageBox.Show(
                        Strings.FrmMain_EncryptCallback_Push_to_remote_repo_failed_,
                        Strings.Error,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }
            }
            this.CreateNodes();
        }
Esempio n. 45
0
        public void ExportToExcel()
        {
            Dictionary <string, int> dct;
            Type keyType;

            if (ch == 0)
            {
                dct = filtered.Select((x, i) => new { i, x.NameOfGroup })
                      .ToDictionary(k => k.NameOfGroup, e => e.i);
                keyType = typeof(Group);
            }
            else if (ch == -1)
            {
                dct = filteredTeacher.Select((x, i) => new { i, x.FIO })
                      .ToDictionary(k => k.FIO, e => e.i);
                keyType = typeof(Teacher);
            }
            else
            {
                dct = filteredClassroom.Select((x, i) => new { i, x.NumberOfClassroom })
                      .ToDictionary(k => k.NumberOfClassroom, e => e.i);
                keyType = typeof(ClassRoom);
            }

            var workbook  = new XLWorkbook();
            var worksheet = workbook.Worksheets.Add("Лист1");

            for (int r = 0; r < maxpair; r++)
            {
                worksheet.Cell(r + 2, 1).Style.Alignment.TextRotation   = 90;
                worksheet.Cell(r + 2, 1).Style.Fill.BackgroundColor     = XLColor.FromIndex(22);
                worksheet.Cell(r + 2, 1).Style.Border.TopBorder         = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 2, 1).Style.Border.TopBorderColor    = XLColor.Black;
                worksheet.Cell(r + 2, 1).Style.Border.RightBorder       = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 2, 1).Style.Border.RightBorderColor  = XLColor.Black;
                worksheet.Cell(r + 2, 1).Style.Border.LeftBorder        = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 2, 1).Style.Border.LeftBorderColor   = XLColor.Black;
                worksheet.Cell(r + 2, 1).Style.Border.BottomBorder      = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 2, 1).Style.Border.BottomBorderColor = XLColor.Black;

                worksheet.Row(r + 2).Height = 25;

                worksheet.Cell(r + 2, 1).Style.Alignment.WrapText   = true;
                worksheet.Cell(r + 2, 1).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                worksheet.Cell(r + 2, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                worksheet.Cell(r + 2, 1).RichText.FontSize          = 20;
                worksheet.Cell(r + 2, 1).RichText.FontColor         = XLColor.Black;
                worksheet.Cell(r + 2, 1).RichText.FontName          = "Broadway";
                string str = "";
                if (r / 6 < 1)
                {
                    str = "Понедельник";
                    worksheet.Cell(r + 2, 1).Value = str;
                    worksheet.Range("A2:A7").Column(1).Merge();
                }
                else
                if ((r / 6 < 2) && (r / 6 >= 1))
                {
                    str = "Вторник";
                    worksheet.Cell(r + 2, 1).Value = str;
                    worksheet.Range("A8:A13").Column(1).Merge();
                }
                else
                if ((r / 6 < 3) && (r / 6 >= 2))
                {
                    str = "Среда";
                    worksheet.Cell(r + 2, 1).Value = str;
                    worksheet.Range("A14:A19").Column(1).Merge();
                }
                else
                if ((r / 6 < 4) && (r / 6 >= 3))
                {
                    str = "Четверг";
                    worksheet.Cell(r + 2, 1).Value = str;
                    worksheet.Range("A20:A25").Column(1).Merge();
                }
                else
                if ((r / 6 < 5) && (r / 6 >= 4))
                {
                    str = "Пятница";
                    worksheet.Cell(r + 2, 1).Value = str;
                    worksheet.Range("A26:A31").Column(1).Merge();
                }
                else
                {
                    str = "Суббота";
                    worksheet.Cell(r + 2, 1).Value = str;
                    worksheet.Range("A32:A34").Column(1).Merge();
                }
            }
            string[] strPair = { "I 8:30 - 10:05", "II 10:20 - 11:55", "III 12:10 - 13:45", "IV 14:15 - 15:50", "V 16:05 - 17:40", "VI 17:50 - 19:25" };

            for (int r = 1; r <= maxpair; r++)
            {
                worksheet.Cell(r + 1, 2).Style.Fill.BackgroundColor     = XLColor.FromIndex(22);
                worksheet.Cell(r + 1, 2).Style.Border.TopBorder         = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 1, 2).Style.Border.TopBorderColor    = XLColor.Black;
                worksheet.Cell(r + 1, 2).Style.Border.RightBorder       = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 1, 2).Style.Border.RightBorderColor  = XLColor.Black;
                worksheet.Cell(r + 1, 2).Style.Border.LeftBorder        = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 1, 2).Style.Border.LeftBorderColor   = XLColor.Black;
                worksheet.Cell(r + 1, 2).Style.Border.BottomBorder      = XLBorderStyleValues.Thin;
                worksheet.Cell(r + 1, 2).Style.Border.BottomBorderColor = XLColor.Black;

                worksheet.Cell(r + 1, 2).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                worksheet.Cell(r + 1, 2).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

                worksheet.Row(r + 1).Height    = 25;
                worksheet.Column(2).Width      = 20;
                worksheet.Cell(r + 1, 2).Value = strPair[(r - 1) % strPair.Length];
            }
            if (ch == 0)
            {
                for (int c = 0; c < filtered.Length; c++)
                {
                    worksheet.Column(3 + c).Width = 40;
                    worksheet.Cell(1, 3 + c).Style.Fill.BackgroundColor     = XLColor.FromIndex(22);
                    worksheet.Cell(1, 3 + c).Style.Border.TopBorder         = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.TopBorderColor    = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.RightBorder       = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.RightBorderColor  = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.LeftBorder        = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.LeftBorderColor   = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.BottomBorder      = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.BottomBorderColor = XLColor.Black;

                    worksheet.Cell(1, 3 + c).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                    worksheet.Cell(1, 3 + c).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

                    worksheet.Cell(1, 3 + c).Value = filtered[c].NameOfGroup;
                }
            }
            else if (ch == -1)
            {
                for (int c = 0; c < filteredTeacher.Length; c++)
                {
                    worksheet.Column(3 + c).Width = 40;
                    worksheet.Cell(1, 3 + c).Style.Fill.BackgroundColor     = XLColor.FromIndex(22);
                    worksheet.Cell(1, 3 + c).Style.Border.TopBorder         = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.TopBorderColor    = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.RightBorder       = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.RightBorderColor  = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.LeftBorder        = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.LeftBorderColor   = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.BottomBorder      = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.BottomBorderColor = XLColor.Black;

                    worksheet.Cell(1, 3 + c).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                    worksheet.Cell(1, 3 + c).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

                    worksheet.Cell(1, 3 + c).Value = filteredTeacher[c].FIO;
                }
            }
            else
            {
                for (int c = 0; c < filteredClassroom.Length; c++)
                {
                    worksheet.Column(3 + c).Width = 40;
                    worksheet.Cell(1, 3 + c).Style.Fill.BackgroundColor     = XLColor.FromIndex(22);
                    worksheet.Cell(1, 3 + c).Style.Border.TopBorder         = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.TopBorderColor    = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.RightBorder       = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.RightBorderColor  = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.LeftBorder        = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.LeftBorderColor   = XLColor.Black;
                    worksheet.Cell(1, 3 + c).Style.Border.BottomBorder      = XLBorderStyleValues.Thin;
                    worksheet.Cell(1, 3 + c).Style.Border.BottomBorderColor = XLColor.Black;

                    worksheet.Cell(1, 3 + c).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                    worksheet.Cell(1, 3 + c).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

                    worksheet.Cell(1, 3 + c).Value = filteredClassroom[c].NumberOfClassroom;
                }
            }
            var temp = Data.Select(x => x.ToArray()).ToArray();

            for (int i = 0; i < temp.Length; i++)
            {
                for (int j = 0; j < temp[0].Length; j++)
                {
                    if (ch == 0)
                    {
                        int cind;
                        if (temp[i][j].Item.Group != null)
                        {
                            if (dct.TryGetValue(temp[i][j].Item.Group, out cind))
                            {
                                Data[i][cind].Item = temp[i][j].Item;
                                worksheet.Cell(i + 2, 2 + cind + 1).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                                worksheet.Cell(i + 2, 2 + cind + 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                                worksheet.Cell(i + 2, 2 + cind + 1).Value = Data[i][cind].Item.NumberOfClassroom + " " + Data[i][cind].Item.Subject + " " + Data[i][cind].Item.Teacher;
                            }
                        }
                    }
                    else if (ch == -1)
                    {
                        int cind;
                        if (temp[i][j].Item.Teacher != null)
                        {
                            if (dct.TryGetValue(temp[i][j].Item.Teacher, out cind))
                            {
                                Data[i][cind].Item = temp[i][j].Item;
                                worksheet.Cell(i + 2, 2 + cind + 1).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                                worksheet.Cell(i + 2, 2 + cind + 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                                worksheet.Cell(i + 2, 2 + cind + 1).Value = Data[i][cind].Item.NumberOfClassroom + " " + Data[i][cind].Item.Subject + " " + Data[i][cind].Item.Group;
                            }
                        }
                    }
                    else
                    {
                        int cind;
                        if (temp[i][j].Item.NumberOfClassroom != null)
                        {
                            if (dct.TryGetValue(temp[i][j].Item.NumberOfClassroom, out cind))
                            {
                                Data[i][cind].Item = temp[i][j].Item;
                                worksheet.Cell(i + 2, 2 + cind + 1).Style.Alignment.Vertical   = XLAlignmentVerticalValues.Center;
                                worksheet.Cell(i + 2, 2 + cind + 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                                worksheet.Cell(i + 2, 2 + cind + 1).Value = Data[i][cind].Item.Subject + " " + Data[i][cind].Item.Group + " " + Data[i][cind].Item.Teacher;
                            }
                        }
                    }
                }
            }
            if (IsValidate() == true)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Книга Excel (*.xlsx)|*.xlsx";
                string path = "";
                if (saveFileDialog.ShowDialog() == true)
                {
                    if (!string.IsNullOrEmpty(saveFileDialog.FileName))
                    {
                        path = saveFileDialog.FileName;
                        workbook.SaveAs(path);
                        MessageBox.Show("Сохранено");
                    }
                }
            }
        }
Esempio n. 46
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (this.listReflectionList.Items.Count < 1)
            {
                return;
            }

            bool isCSV = false;

            if (this.cmbExportMethod.Text == "CSV")
            {
                isCSV = true;
            }

            //SaveFileDialogクラスのインスタンスを作成
            SaveFileDialog sfd = new SaveFileDialog();

            //はじめのファイル名を指定する
            sfd.FileName = "abc.txt";
            //はじめに表示されるフォルダを指定する
            sfd.InitialDirectory = Application.StartupPath;
            //[ファイルの種類]に表示される選択肢を指定する
            sfd.Filter = "CSVファイル(*.csv)|*.csv|テキストファイル(*.txt)|*.txt";
            //[ファイルの種類]ではじめに
            //「すべてのファイル」が選択されているようにする
            sfd.FilterIndex = 2;
            //タイトルを設定する
            sfd.Title = "保存先のファイルを選択してください";
            //ダイアログボックスを閉じる前に現在のディレクトリを復元するようにする
            sfd.RestoreDirectory = true;
            //既に存在するファイル名を指定したとき警告する
            //デフォルトでTrueなので指定する必要はない
            sfd.OverwritePrompt = true;
            //存在しないパスが指定されたとき警告を表示する
            //デフォルトでTrueなので指定する必要はない
            sfd.CheckPathExists = true;

            //ダイアログを表示する
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                //OKボタンがクリックされたとき
                //選択されたファイル名を表示する
                //Console.WriteLine(sfd.FileName);

                string filename       = Path.GetFileName(sfd.FileName);
                string ext            = Path.GetExtension(sfd.FileName);
                string path           = Path.GetDirectoryName(sfd.FileName);
                string filetitle      = filename.Substring(0, filename.Length - ext.Length);
                string ClassFileName  = path + @"\" + filetitle + ext;
                string MethodFileName = path + @"\" + filetitle + "_method" + ext;
                string ArgsFileName   = path + @"\" + filetitle + "_args" + ext;

                //FileStream ClassFs = null;
                FileStream MethodFs = null;
                FileStream ArgsFs   = null;
                //StreamWriter ClassWriter = null;
                StreamWriter MethodWriter = null;
                StreamWriter ArgsWriter   = null;
                try
                {
                    /*
                     * try
                     * {
                     *  ClassFs = File.Open(ClassFileName, FileMode.OpenOrCreate | FileMode.Truncate);
                     * }
                     * catch (Exception excp)
                     * {
                     *  ClassFs = File.Open(ClassFileName, FileMode.OpenOrCreate);
                     * }
                     */
                    try
                    {
                        MethodFs = File.Open(MethodFileName, FileMode.OpenOrCreate | FileMode.Truncate);
                    }
                    catch (Exception excp)
                    {
                        MethodFs = File.Open(MethodFileName, FileMode.OpenOrCreate);
                    }
                    try
                    {
                        ArgsFs = File.Open(ArgsFileName, FileMode.OpenOrCreate | FileMode.Truncate);
                    }
                    catch (Exception excp)
                    {
                        ArgsFs = File.Open(ArgsFileName, FileMode.OpenOrCreate);
                    }

                    //ClassWriter = new StreamWriter(ClassFs, Encoding.Default);
                    MethodWriter = new StreamWriter(MethodFs, Encoding.Default);
                    ArgsWriter   = new StreamWriter(ArgsFs, Encoding.Default);


                    if (isCSV)
                    {   // CSV
                        MethodWriter.WriteLine(
                            "\"signature\"," +
                            "\"pubilc\"," +
                            "\"virtual\"," +
                            "\"return type\"," +
                            "\"method name\","
                            );
                        MethodWriter.Flush();

                        ArgsWriter.WriteLine(
                            "\"signature\"," +
                            "\"arg\","
                            );
                        ArgsWriter.Flush();
                    }
                    else
                    {   // TSV
                        MethodWriter.WriteLine(
                            "signature" + ControlChars.Tab +
                            "public" + ControlChars.Tab +
                            "virtual" + ControlChars.Tab +
                            "return type" + ControlChars.Tab +
                            "method name" + ControlChars.Tab
                            );
                        MethodWriter.Flush();

                        ArgsWriter.WriteLine(
                            "signature" + ControlChars.Tab +
                            "arg" + ControlChars.Tab
                            );
                        ArgsWriter.Flush();
                    }


                    foreach (object obj in this.listReflectionList.Items)
                    {
                        string fullsignature = obj as string;
                        if (fullsignature == null)
                        {
                            continue;
                        }

                        string        returnType      = string.Empty;
                        string        publicprotected = string.Empty;
                        string        virtualString   = string.Empty;
                        List <string> args            = new List <string>();
                        List <string> funcs           = this.funcSelector.SelectFunctions(fullsignature, 1, out returnType, out args, out publicprotected, out virtualString);

                        if (this.JudgeIfOrNotAddSelectedFunc(fullsignature, this.tbxFilter.Text, this.cmbPublicElse.Text, this.chkIsProperty.Checked, this.chkIsEvent.Checked, this.chkMethodOnly.Checked))
                        {
                            if (funcs.Count > 0)
                            {
                                if (isCSV)
                                {   // CSV
                                    MethodWriter.WriteLine(
                                        "\"" + fullsignature + "\"," +
                                        "\"" + publicprotected + "\"," +
                                        "\"" + virtualString + "\"," +
                                        "\"" + returnType + "\"," +
                                        "\"" + funcs[0] + "\","
                                        );
                                    MethodWriter.Flush();

                                    foreach (string arg in args)
                                    {
                                        ArgsWriter.WriteLine(
                                            "\"" + fullsignature + "\"," +
                                            "\"" + arg + "\","
                                            );
                                        ArgsWriter.Flush();
                                    }
                                }
                                else
                                {   // TSV
                                    MethodWriter.WriteLine(
                                        fullsignature + ControlChars.Tab +
                                        publicprotected + ControlChars.Tab +
                                        virtualString + ControlChars.Tab +
                                        returnType + ControlChars.Tab +
                                        funcs[0] + ControlChars.Tab
                                        );
                                    MethodWriter.Flush();

                                    foreach (string arg in args)
                                    {
                                        ArgsWriter.WriteLine(
                                            fullsignature + ControlChars.Tab +
                                            arg + ControlChars.Tab
                                            );
                                        ArgsWriter.Flush();
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception excp)
                {
                }
                finally
                {
                    if (MethodWriter != null)
                    {
                        MethodWriter.Close();
                    }
                    if (ArgsWriter != null)
                    {
                        ArgsWriter.Close();
                    }
                    if (MethodFs != null)
                    {
                        MethodFs.Close();
                    }
                    if (ArgsFs != null)
                    {
                        ArgsFs.Close();
                    }
                }
            }
        }
        /// <summary>
        /// 导出后备干部考察材料表
        /// </summary>
        /// <param name="idlist">需要导出后备干部的id号集合</param>
        public void exportword(ArrayList idlist)
        {
            //选择保存路径
            #region
            string         savepath = "";
            SaveFileDialog sa       = new SaveFileDialog();
            sa.Filter   = "Document(*.doc)|*.doc";
            sa.FileName = "考察材料表";
            if (sa.ShowDialog() == DialogResult.OK)
            {
                savepath = sa.FileName;
            }
            else
            {
                return;
            }
            #endregion

            //创建word应用程序
            wordappliction = new Word.Application();
            object        filepath = System.Windows.Forms.Application.StartupPath + "\\wordModel" + "\\考察材料1.doc";
            Word.Document mydoc    = wordappliction.Documents.Open(ref filepath, ref missing, ref readOnly,
                                                                   ref missing, ref missing, ref missing, ref missing, ref missing,
                                                                   ref missing, ref missing, ref missing, ref isVisible, ref missing,
                                                                   ref missing, ref missing, ref missing);
            //wordappliction.Visible = true;
            mydoc.ActiveWindow.Selection.WholeStory();
            mydoc.ActiveWindow.Selection.Tables[1].Select();
            mydoc.ActiveWindow.Selection.Copy();
            for (int i = 1; i < idlist.Count; i++)
            {
                //插入分页符
                #region
                Word.Paragraph para1;
                para1 = mydoc.Content.Paragraphs.Add(ref missing);
                object pBreak = (int)WdBreakType.wdSectionBreakNextPage;
                //控制位置
                para1.Range.InsertBreak(ref pBreak);
                #endregion
                //粘贴剪贴板中的内容,同时加上加上备注。
                para1.Range.Paste();
            }

            string selectid = "";
            for (int i = 0; i < idlist.Count; i++)
            {
                if (i == idlist.Count - 1)
                {
                    selectid = selectid + "'" + idlist[i] + "'";
                }
                else
                {
                    selectid = selectid + "'" + idlist[i] + "',";
                }
            }
            string        sql        = "select  name,material,cid from TB_CommonInfo where isdelete=0 order by rank,joinTeam desc";
            string        cond       = "cid in (" + selectid + ")";
            DataOperation dataOp     = new DataOperation();
            DataTable     datatableT = dataOp.GetOneDataTable_sql(sql);
            DataTable     dt         = new DataTable();
            dt = datatableT.Clone();
            DataView dv = datatableT.AsDataView();
            dv.RowFilter = cond;
            dt           = dv.ToTable();

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                mydoc.Tables[i + 1].Cell(1, 1).Range.Text = dt.Rows[i][0].ToString() + "同志考察材料";
                mydoc.Tables[i + 1].Cell(2, 1).Range.Text = dt.Rows[i][1].ToString();
            }

            #region
            object path = savepath;
            //wordappliction.Documents.Save(path);
            object myobj = System.Reflection.Missing.Value;;
            mydoc.SaveAs(ref path, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj,
                         ref myobj, ref myobj, ref myobj, ref myobj, ref myobj, ref myobj,
                         ref myobj, ref myobj, ref myobj, ref myobj);
            #endregion
            //关闭退出文档
            #region
            //关闭文档
            mydoc.Close(ref myobj, ref myobj, ref myobj);
            //退出应用程序。
            wordappliction.Quit();
            #endregion
            MessageBox.Show("导出成功!");
        }
Esempio n. 48
0
        private async void btnJson_Click(object sender, EventArgs e)
        {
            var userInfo = await ApiManage.instaApi.AccountProcessor.GetRequestForEditProfileAsync();



            #region InfoRmation



            var userName = userInfo.Value.Username;
            var fullNmae = userInfo.Value.FullName;
            var email    = userInfo.Value.Email;
            var site     = userInfo.Value.ExternalUrl;
            var Number   = userInfo.Value.PhoneNumber;
            var prof     = userInfo.Value.ProfilePicUrl;

            #endregion



            #region getFollowers/Following/Photos

            var following = await ApiManage.instaApi.UserProcessor.GetUserFollowingAsync(userInfo.Value.Username,
                                                                                         PaginationParameters.MaxPagesToLoad(1));

            var followers = await ApiManage.instaApi.UserProcessor.GetUserFollowersAsync(userInfo.Value.Username,
                                                                                         PaginationParameters.MaxPagesToLoad(1));


            var userPosts = await ApiManage.instaApi.UserProcessor.GetUserMediaAsync(username : userInfo.Value.Username,
                                                                                     PaginationParameters.Empty);

            #endregion



            SaveFileDialog save = new SaveFileDialog()
            {
                Filter = "|*.json",
                Title  = "ذخیره فایل ",
            };

            if (save.ShowDialog() == DialogResult.OK)
            {
                var select = save.FileName;

                var path = @select;



                UserJsonConvert userJson = new UserJsonConvert()
                {
                    fullName     = fullNmae,
                    userName     = userName,
                    webPage      = !string.IsNullOrEmpty(site) ? site : "No Web Active",
                    number       = Number,
                    email        = email,
                    imageProfile = prof,
                    images       = userPosts.Value,
                    followers    = followers.Value,
                    followings   = following.Value,
                };



                string jsonUser = JsonConvert.SerializeObject(userJson);


                File.WriteAllText(path, jsonUser);


                MessageBox.Show($"فایل شما در مسیر {path} ذخیره شد ", "ذخیره ", MessageBoxButtons.OK,
                                MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading);
            }
            else
            {
                MessageBox.Show("فایل رو کجا بریزم کاکوی گولم ");
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (Profiles_ComboBox.Items.Count == 0)
            {
                _ = MessageBox.Show("Veuillez charger un fichier profiles.json avec des profiles remplis avant de générer une attestation.", "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                FileName = "attestation-deplacement-fr-" + DateTime.Now.ToString("dd-MM-yyyy-HH-mm") + ".pdf",
                Filter   = "Fichier PDF | *.pdf"
            };

            if (saveFileDialog.ShowDialog() ?? false)
            {
                try
                {
                    WebClient webClient = new WebClient();
                    webClient.DownloadFile("https://www.interieur.gouv.fr/attestation_de_deplacement_derogatoire", saveFileDialog.FileName);
                    PdfDocument doc = new PdfDocument();
                    doc.LoadFromFile(saveFileDialog.FileName);
                    PdfFormWidget formWidget = doc.Form as PdfFormWidget;
                    foreach (PdfField field in formWidget.FieldsWidget)// for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
                    {
                        if (field is PdfTextBoxFieldWidget)
                        {
                            PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
                            switch (textBoxField.Name)
                            {
                            case "Nom et prénom":
                                textBoxField.Text = Profiles_ComboBox.Text;
                                break;

                            case "Date de naissance":
                                textBoxField.Text = GetFromFullName(Profiles_ComboBox.Text).BirthDate;
                                break;

                            case "Lieu de naissance":
                                textBoxField.Text = GetFromFullName(Profiles_ComboBox.Text).BirthPlace;
                                break;

                            case "Adresse actuelle":
                                textBoxField.Text = GetFromFullName(Profiles_ComboBox.Text).Address;
                                break;

                            case "Ville":
                                textBoxField.Text = GetFromFullName(Profiles_ComboBox.Text).City;
                                break;

                            case "Date":
                                textBoxField.Text = DateTime.Now.ToString("dd/MM/yyyy");
                                break;

                            case "Heure":
                                textBoxField.Text = DateTime.Now.ToString("HH");
                                break;

                            case "Minute":
                                textBoxField.Text = DateTime.Now.ToString("mm");
                                break;

                            default:
                                break;
                            }
                        }
                        else if (field is PdfCheckBoxWidgetFieldWidget)
                        {
                            PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                            if (checkBoxField.Name == Exit_Reasons_ComboBox.Text)
                            {
                                checkBoxField.Checked = true;
                            }
                        }
                    }
                    doc.SaveToFile(saveFileDialog.FileName);
                    _ = Process.Start("explorer.exe", saveFileDialog.FileName);
                }
                catch (Exception ex)
                {
                    _ = MessageBox.Show(ex.Message, "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
Esempio n. 50
0
        private void BtnXuatFile_PN_Click(object sender, EventArgs e)
        {
            Excel.Application exApp   = new Excel.Application();
            Excel.Workbook    exBook  = exApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            Excel.Worksheet   exSheet = (Excel.Worksheet)exBook.Worksheets[1];
            Excel.Range       exRang  = (Excel.Range)exSheet.Cells[1, 1];

            exRang.Range["A1:A2:A3:G1"].Font.Bold = true;
            exRang.Range["A1:A2:A3:G1"].Font.Size = 14;
            exRang.Range["A1"].Value = lb_TenCH.Text;
            exRang.Range["A2"].Value = lb_DC.Text;
            exRang.Range["A3"].Value = lb_SDT.Text;
            exRang.Range["G1"].Value = "Hà Nội    Ngày: " + lbTime_NghiepVu.Text;

            exRang.Range["E4"].Font.Bold  = true;
            exRang.Range["E4"].Font.Size  = 22;
            exRang.Range["E4"].Value      = "Thống Kê Phiếu Nhập";
            exRang.Range["E4"].Font.Color = Color.Red;

            exRang.Range["A6:G6"].Font.Bold           = true;
            exRang.Range["A6:G6"].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
            exRang.Range["B6:C6"].ColumnWidth         = 20;
            exRang.Range["D6"].ColumnWidth            = 10;
            exRang.Range["C6:E6:F6:G6"].ColumnWidth   = 20;
            exRang.Range["A6"].Value = "STT";
            exRang.Range["B6"].Value = "ID Phiếu Nhập";
            exRang.Range["C6"].Value = "Ngày Nhập";
            exRang.Range["D6"].Value = "ID Nhân Viên";
            exRang.Range["E6"].Value = "NCC";
            exRang.Range["F6"].Value = "Tổng Tiền";
            exRang.Range["G6"].Value = "ID Hóa Đơn Nhập";



            int row = 6;

            for (int i = 0; i < dgvPhieuNhap.Rows.Count - 1; i++)
            {
                row++;
                exRang.Range["A" + row.ToString() + ":" + "H" + row.ToString()].HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;

                exRang.Range["A" + row.ToString()].Value = (i + 1).ToString();
                exRang.Range["B" + row.ToString()].Value = dgvPhieuNhap.Rows[i].Cells[0].Value.ToString();
                exRang.Range["C" + row.ToString()].Value = dgvPhieuNhap.Rows[i].Cells[1].Value.ToString();
                exRang.Range["D" + row.ToString()].Value = dgvPhieuNhap.Rows[i].Cells[2].Value.ToString();
                exRang.Range["E" + row.ToString()].Value = dgvPhieuNhap.Rows[i].Cells[3].Value.ToString();
                exRang.Range["F" + row.ToString()].Value = dgvPhieuNhap.Rows[i].Cells[4].Value.ToString();
                exRang.Range["G" + row.ToString()].Value = dgvPhieuNhap.Rows[i].Cells[5].Value.ToString();
            }
            row = row + 2;
            exRang.Range["E" + row.ToString()].Font.Bold = true;
            exRang.Range["E" + row.ToString()].Value     = "Tổng Sổ Phiếu Nhập: " + (dgvPhieuNhap.Rows.Count - 1);

            exSheet.Name = "Phiếu Nhập";
            exBook.Activate();
            SaveFileDialog svFile = new SaveFileDialog();

            if (svFile.ShowDialog() == DialogResult.OK)
            {
                exBook.SaveAs(svFile.FileName);
                MessageBox.Show("Đã xuất file thành công.", "Chúc Mừng", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            exApp.Quit();
        }
Esempio n. 51
0
        private void خروجیExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFiledialog = new SaveFileDialog();

            saveFiledialog.Filter   = @"Excel Xls|*.xls";
            saveFiledialog.Title    = "Save Excel File";
            saveFiledialog.FileName = "data" + DateTime.Now.ToFa().Replace("/", "-");
            saveFiledialog.ShowDialog();
            if (saveFiledialog.FileName != "")
            {
                using (UnitOfWork db = new UnitOfWork())
                {
                    var finalList = new List <FoodDetailsModel>();
                    var food      = (int)cmbFoodName.SelectedValue;
                    var company   = (int)comboBox1.SelectedValue;
                    var foods     = db.FoodService.GetFoodsbyFoodDetails(MaterialsName.Text, company, food);
                    if (!string.IsNullOrWhiteSpace(PriceFrom.Text))
                    {
                        var fromPrice = Convert.ToDouble(PriceFrom.Text);
                        foods = foods.Where(a => a.FinalPrice >= fromPrice).ToList();
                    }

                    if (!string.IsNullOrWhiteSpace(PriceTo.Text))
                    {
                        var fromPrice = Convert.ToDouble(PriceTo.Text);
                        foods = foods.Where(a => a.FinalPrice <= fromPrice).ToList();
                    }

                    using (var p = new ExcelPackage())
                    {
                        var workbook = p.Workbook;
                        var ws       = p.Workbook.Worksheets.Add("گزارش مصرف کلی ماهیانه");
                        ws.View.RightToLeft = true;


                        var record     = 1;
                        var nextRecord = 1;
                        foreach (var row in foods)
                        {
                            ws.Cells[record, 1, record, 8].Merge = true;
                            ws.Cells[record, 1, record, 8].Style.Fill.PatternType = ExcelFillStyle.Solid;
                            ws.Cells[record, 1, record, 8].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Bisque);
                            ws.Cells[record, 1, record, 8].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1, record, 8].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1, record, 8].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1, record, 8].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1].Value = "ریز اجزای تشکیل دهنده یک پرس :" + " " + row.FoodName;
                            record += 1;
                            ws.Cells[record, 1, record, 2].Merge = true;
                            ws.Cells[record, 1, record, 2].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1, record, 2].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1, record, 2].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1, record, 2].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 1].Value = "نام کالا";

                            ws.Cells[record, 3, record, 4].Merge = true;
                            ws.Cells[record, 3, record, 4].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 3, record, 4].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 3, record, 4].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 3, record, 4].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 3].Value = "(گرم)تعداد ";

                            ws.Cells[record, 5, record, 6].Merge = true;
                            ws.Cells[record, 5, record, 6].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 5, record, 6].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 5, record, 6].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 5, record, 6].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 5].Value = "قیمت هر کیلو ";

                            ws.Cells[record, 7, record, 8].Merge = true;
                            ws.Cells[record, 7, record, 8].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 7, record, 8].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 7, record, 8].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 7, record, 8].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[record, 7].Value = "قیمت نهایی  ";

                            nextRecord = record;
                            //ws.Row(record).Style.Fill.PatternType = ExcelFillStyle.Solid;
                            //ws.Row(record).Style.Fill.PatternType = ExcelFillStyle.Solid;
                            //ws.Row(record).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                            //ws.Row(record).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                            foreach (var rowFoodMaterial in row.FoodMaterials.ToList())
                            {
                                nextRecord += 1;
                                ws.Cells[nextRecord, 1, nextRecord, 2].Merge = true;
                                ws.Cells[nextRecord, 1, nextRecord, 2].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1, nextRecord, 2].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1, nextRecord, 2].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1, nextRecord, 2].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1].Value = rowFoodMaterial.MaterialPrice.Material.MaterialName;

                                ws.Cells[nextRecord, 3, nextRecord, 4].Merge = true;
                                ws.Cells[nextRecord, 3, nextRecord, 4].Merge = true;
                                ws.Cells[nextRecord, 3, nextRecord, 4].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 3, nextRecord, 4].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 3, nextRecord, 4].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 3, nextRecord, 4].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 3].Value = rowFoodMaterial.Quantity;

                                ws.Cells[nextRecord, 5, nextRecord, 6].Merge = true;
                                ws.Cells[nextRecord, 5, nextRecord, 6].Merge = true;
                                ws.Cells[nextRecord, 5, nextRecord, 6].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 5, nextRecord, 6].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 5, nextRecord, 6].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 5, nextRecord, 6].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 5].Value = rowFoodMaterial.UnitPrice;

                                ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7].Value = rowFoodMaterial.MaterialTotalPrice;
                                //ws.Row(nextRecord).Style.Fill.PatternType = ExcelFillStyle.Solid;
                                //ws.Row(nextRecord).Style.Fill.PatternType = ExcelFillStyle.Solid;
                                //ws.Row(nextRecord).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                                //ws.Row(nextRecord).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                            }

                            nextRecord += 1;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Merge = true;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Merge = true;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1].Value = "جمع کل";
                            ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7].Value             = row.FinalPrice;
                            ws.Row(nextRecord).Style.Fill.PatternType = ExcelFillStyle.Solid;
                            ws.Row(nextRecord).Style.Fill.PatternType = ExcelFillStyle.Solid;
                            ws.Row(nextRecord).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                            ws.Row(nextRecord).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                            record      = nextRecord + 1;
                            nextRecord += 1;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Merge = true;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Merge = true;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 1].Value = "هزینه های مازاد";
                            ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                            ws.Cells[nextRecord, 7].Value = "مبلغ";
                            //ws.Row(nextRecord).Style.Fill.PatternType = ExcelFillStyle.Solid;
                            //ws.Row(nextRecord).Style.Fill.PatternType = ExcelFillStyle.Solid;
                            //ws.Row(nextRecord).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                            //ws.Row(nextRecord).Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.Gainsboro);
                            foreach (var rowFoodSurplusPrice in row.FoodSurplusPrices)
                            {
                                ws.Cells[nextRecord, 1, nextRecord, 6].Merge = true;
                                ws.Cells[nextRecord, 1, nextRecord, 6].Merge = true;
                                ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1, nextRecord, 6].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 1].Value = rowFoodSurplusPrice.CostTitle;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Merge = true;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Right.Style  = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Left.Style   = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7, nextRecord, 8].Style.Border.Top.Style    = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                                ws.Cells[nextRecord, 7].Value = rowFoodSurplusPrice.Price;
                                nextRecord += 1;
                            }

                            record = nextRecord + 2;
                        }

                        p.SaveAs(new FileInfo(System.IO.Path.Combine(saveFiledialog.FileName)));
                        MessageBox.Show("ذخیره شد");
                    }
                }
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "PDF (*.pdf)|*.pdf";
                sfd.FileName = "reporte.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(dataGridView1.Columns.Count - 3 );
                            pdfTable.DefaultCell.Padding = 3;
                            pdfTable.WidthPercentage = 100;
                            pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;

                            foreach (DataGridViewColumn column in dataGridView1.Columns)
                            {
                                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));

                                if ((column.Index != 2)
                                    && (column.Index != 6)
                                    && (column.Index != 4))
                                {
                                    pdfTable.AddCell(cell);
                                }
                            }

                            foreach (DataGridViewRow row in dataGridView1.Rows)
                            {
                                foreach (DataGridViewCell cell in row.Cells)
                                {
                                    if (!(cell.Value is null))
                                    {
                                        if ((cell.ColumnIndex != 2)
                                        && (cell.ColumnIndex != 6)
                                        && (cell.ColumnIndex != 4))
                                        {
                                            pdfTable.AddCell(cell.Value.ToString());
                                        }
                                    }
                                }
                            }

                            using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
                            {
                                Document pdfDoc = new Document(PageSize.A4, 10f, 20f, 20f, 10f);
                                PdfWriter.GetInstance(pdfDoc, stream);
                                pdfDoc.Open();
                                pdfDoc.Add(pdfTable);
                                pdfDoc.Close();
                                stream.Close();
                            }

                            MessageBox.Show("Se exporto exitosamente", "Info");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error :" + ex.Message);
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("No hay informacion.", "Info");
            }
        }
Esempio n. 53
0
        private void Save(object sender, RoutedEventArgs e)
        {
            Struktura s = new Struktura();

            string[] files;
            string   path = Directory.GetCurrentDirectory();

            files = Directory.GetFiles(path);
            string         fileName       = txtBox.Text;
            var            jezik          = (ProgramskiJezik)programskiJezik.SelectedValue;
            string         tip            = (string)tipi.SelectedValue;
            var            ogrodje        = (Ogrodje)ogrodja.SelectedValue;
            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                InitialDirectory = path,
                Filter           = "XML Files (*.XML)|*.XML",
                FileName         = fileName
            };
            DialogResult fbd = saveFileDialog.ShowDialog();

            if (fbd == System.Windows.Forms.DialogResult.OK)
            {
                ((MainWindow)System.Windows.Application.Current.MainWindow).s = s;
                s.ime             = fileName;
                s.programskiJezik = jezik.Name.ToLower();
                s.tip             = tip.ToLower();
                s.ogrodje         = ogrodje.Name.ToLower();
                XmlSerializer serializer = new XmlSerializer(typeof(Struktura));
                TextWriter    writer     = new StreamWriter(saveFileDialog.FileName);
                serializer.Serialize(writer, s);
                writer.Close();
                ((MainWindow)System.Windows.Application.Current.MainWindow).struktura.Items.Clear();
                //File.WriteAllText(saveFileDialog.FileName, "Datoteka");
                ((MainWindow)System.Windows.Application.Current.MainWindow).struktura.Items.Add(new TreeViewItem()
                {
                    Header = fileName, HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch
                });
                if (jezik != null && tip != null & ogrodje != null)
                {
                    if (jezik.Name.ToLower() == "c++")
                    {
                        if (tip.ToLower() == "console app")
                        {
                            ((MainWindow)System.Windows.Application.Current.MainWindow).struktura.Items.Add(new TreeViewItem()
                            {
                                Header = "Main.cpp", HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch
                            });
                        }
                    }
                    else if (jezik.Name.ToLower() == "c#")
                    {
                        if (tip.ToLower() == "wpf app")
                        {
                            ((MainWindow)System.Windows.Application.Current.MainWindow).struktura.Items.Add(new TreeViewItem()
                            {
                                Header = "MainWindow.cs", HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch
                            });
                            ((MainWindow)System.Windows.Application.Current.MainWindow).struktura.Items.Add(new TreeViewItem()
                            {
                                Header = "MainWindow.xaml", HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch
                            });
                            ((MainWindow)System.Windows.Application.Current.MainWindow).struktura.Items.Add(new TreeViewItem()
                            {
                                Header = "Settings.cs", HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch
                            });
                        }

                        else if (tip.ToLower() == "console app")
                        {
                            ((MainWindow)System.Windows.Application.Current.MainWindow).struktura.Items.Add(new TreeViewItem()
                            {
                                Header = "Main.cs", HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch
                            });
                        }
                    }
                    this.Close();
                }
            }
        }
Esempio n. 54
0
        private void BtnExportExcel_Click(object sender, EventArgs e)
        {
            if (dgvData.Rows.Count > 0)
            {
                using (SaveFileDialog saveFileDialog = new SaveFileDialog()
                {
                    Filter = "Excel Workbook|*.xlsx"
                })
                {
                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        try
                        {
                            using (XLWorkbook workbook = new XLWorkbook())
                            {
                                if (hairdresserId == null || hairdresserId == 0)
                                {
                                    string query = @"SELECT HR.FirstName + ' ' + HR.LastName AS Hairdresser, COUNT(B.HairstyleId) AS NumberOfServices, SUM(HS.Price) AS EarnedMoney
                                                 FROM dbo.Bookings AS B
                                                 JOIN dbo.Hairdressers AS HR ON B.HairdresserId=HR.Id
                                                 JOIN dbo.Hairstyles AS HS ON B.HairstyleId=HS.Id
                                                 GROUP BY HR.FirstName + ' ' + HR.LastName
                                                 ORDER BY 3 DESC";

                                    SqlConnection     conn           = new SqlConnection("Server =localhost,1401; Database = eHairdresserSalonFareDb;User=sa;Password=QWElkj132!;");
                                    SqlDataAdapter    dataAdapter    = new SqlDataAdapter(query, conn);
                                    SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
                                    DataSet           dataSet        = new DataSet();
                                    dataAdapter.Fill(dataSet);
                                    workbook.Worksheets.Add(dataSet.Tables[0]);
                                    workbook.SaveAs(saveFileDialog.FileName);

                                    MessageBox.Show("You have successfuly exported your data to excel file!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                else
                                {
                                    string query = @"SELECT HR.FirstName + ' ' + HR.LastName AS Hairdresser, COUNT(B.HairstyleId) AS NumberOfServices, SUM(HS.Price) AS EarnedMoney
                                                     FROM dbo.Bookings AS B
                                                     JOIN dbo.Hairdressers AS HR ON B.HairdresserId=HR.Id
                                                     JOIN dbo.Hairstyles AS HS ON B.HairstyleId=HS.Id
                                                     WHERE B.HairdresserId=@hairdresserId
                                                     GROUP BY HR.FirstName + ' ' + HR.LastName
                                                     ORDER BY 1 ASC";

                                    SqlConnection conn = new SqlConnection("Server =localhost,1401; Database = eHairdresserSalonFareDb;User=sa;Password=QWElkj132!;");
                                    conn.Open();

                                    SqlCommand sqlCmd = new SqlCommand(query, conn);
                                    sqlCmd.Parameters.AddWithValue("@HairdresserId", hairdresserId);

                                    SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCmd);
                                    DataSet        dataSet     = new DataSet();
                                    dataAdapter.Fill(dataSet);
                                    workbook.Worksheets.Add(dataSet.Tables[0]);
                                    workbook.SaveAs(saveFileDialog.FileName);

                                    MessageBox.Show("You have successfuly exported your data to excel file!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }
Esempio n. 55
0
        public void ReceiveMsg()
        {
            while (isStart)
            {
                try
                {
                    TcpClient client = listener.AcceptTcpClient();

                    if (client.Connected)
                    {
                        //向列表控件中添加一个客户端的Ip和端口,作为发送时客户的唯一标识
                        listbOnline.Items.Add(client.Client.RemoteEndPoint);
                        ShwMsgForView.ShwMsgforView(lstbxMsgView, "客户端连接成功" + client.Client.RemoteEndPoint.ToString());
                    }

                    NetworkStream stream = client.GetStream();


                    byte[] buffer = new byte[512];

                    //while (true)
                    //{
                    //    byte[] send = Encoding.ASCII.GetBytes("12121212");
                    //    stream.Write(send, 0, send.Length);
                    //    stream.Flush();
                    //    Thread.Sleep(100);
                    //}

                    int size;
                    while ((size = stream.Read(buffer, 0, buffer.Length)) > 0 || isStart)
                    {
                        byte[] recData = new byte[size];
                        Array.Copy(buffer, recData, size);
                        string   recsData = Encoding.ASCII.GetString(recData);
                        string[] rec      = recsData.Split(':');
                        if (rec.Length == 2)
                        {
                            filename = rec[0];
                            filesize = Convert.ToInt64(rec[1]);
                            byte[] send = Encoding.ASCII.GetBytes("OK");
                            stream.Write(send, 0, send.Length);
                            break;
                        }
                    }


                    if (stream != null && isStart)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.FileName = filename;
                        if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        {
                            string fileSavePath = sfd.FileName;//获得用户保存文件的路径
                            writeStream(stream, fileSavePath);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShwMsgForView.ShwMsgforView(lstbxMsgView, "出现异常:" + ex.Message);
                }
            }
        }
Esempio n. 56
0
        private void OnExportWord()
        {
            try
            {
                if (raChung.Checked)
                {
                    if (_textControl1.Text.Trim() == string.Empty)
                    {
                        return;
                    }

                    SaveFileDialog dlg = new SaveFileDialog();
                    dlg.Filter = "Rich Text Format (*.rtf)|*.rtf";
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        _textControl1.Save(dlg.FileName, TXTextControl.StreamType.RichTextFormat);
                    }
                }
                else
                {
                    if (chkNam.Checked && chkNu.Checked)
                    {
                        if (tabMauBaoCao.SelectedIndex == 0)
                        {
                            if (_textControl1.Text.Trim() == string.Empty)
                            {
                                return;
                            }
                            SaveFileDialog dlg = new SaveFileDialog();
                            dlg.Filter = "Rich Text Format (*.rtf)|*.rtf";
                            if (dlg.ShowDialog() == DialogResult.OK)
                            {
                                _textControl1.Save(dlg.FileName, TXTextControl.StreamType.RichTextFormat);
                            }
                        }
                        else
                        {
                            if (_textControl2.Text.Trim() == string.Empty)
                            {
                                return;
                            }
                            SaveFileDialog dlg = new SaveFileDialog();
                            dlg.Filter = "Rich Text Format (*.rtf)|*.rtf";
                            if (dlg.ShowDialog() == DialogResult.OK)
                            {
                                _textControl2.Save(dlg.FileName, TXTextControl.StreamType.RichTextFormat);
                            }
                        }
                    }
                    else
                    {
                        if (chkNam.Checked)
                        {
                            if (_textControl1.Text.Trim() == string.Empty)
                            {
                                return;
                            }
                            SaveFileDialog dlg = new SaveFileDialog();
                            dlg.Filter = "Rich Text Format (*.rtf)|*.rtf";
                            if (dlg.ShowDialog() == DialogResult.OK)
                            {
                                _textControl1.Save(dlg.FileName, TXTextControl.StreamType.RichTextFormat);
                            }
                        }
                        else if (chkNu.Checked)
                        {
                            if (_textControl2.Text.Trim() == string.Empty)
                            {
                                return;
                            }
                            SaveFileDialog dlg = new SaveFileDialog();
                            dlg.Filter = "Rich Text Format (*.rtf)|*.rtf";
                            if (dlg.ShowDialog() == DialogResult.OK)
                            {
                                _textControl2.Save(dlg.FileName, TXTextControl.StreamType.RichTextFormat);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MsgBox.Show(Application.ProductName, ex.Message, IconType.Error);
            }
        }
Esempio n. 57
0
        public void SaveActiveFile(bool UseSaveDialog = true, bool UseCompressDialog = true)
        {
            if (ActiveMdiChild != null)
            {
                if (ActiveMdiChild is ObjectEditor)
                {
                    SaveNodeFormats((ObjectEditor)ActiveMdiChild, UseSaveDialog, UseCompressDialog);
                }
                else
                {
                    var format = GetActiveIFileFormat();

                    if (!format.CanSave)
                    {
                        return;
                    }

                    string FileName = format.FilePath;
                    if (!File.Exists(FileName))
                    {
                        UseSaveDialog = true;
                    }

                    if (UseSaveDialog)
                    {
                        if (format is VGAdudioFile)
                        {
                            SaveFileDialog sfd = new SaveFileDialog();

                            List <IFileFormat> formats = new List <IFileFormat>();
                            foreach (VGAdudioFile fileFormat in FileManager.GetVGAudioFileFormats())
                            {
                                formats.Add((IFileFormat)fileFormat);
                            }
                            sfd.Filter = Utils.GetAllFilters(formats);

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

                            foreach (var fileFormat in formats)
                            {
                                foreach (var ext in format.Extension)
                                {
                                    if (Utils.HasExtension(sfd.FileName, ext))
                                    {
                                        ((VGAdudioFile)format).Format = fileFormat;
                                    }
                                }
                            }

                            FileName = sfd.FileName;
                        }
                        else
                        {
                            SaveFileDialog sfd = new SaveFileDialog();
                            sfd.Filter   = Utils.GetAllFilters(format);
                            sfd.FileName = format.FileName;

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

                            FileName = sfd.FileName;
                        }
                    }
                    Cursor.Current = Cursors.WaitCursor;
                    STFileSaver.SaveFileFormat(format, FileName, UseCompressDialog);
                    Cursor.Current = Cursors.Default;
                }
            }
        }
Esempio n. 58
0
        public void OutputAsExcelFile(DataGridView dataGridView)
        {
            if (dataGridView.Rows.Count <= 0)
            {
                MessageBox.Show("表中没有数据,导出失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string         filePath = "";
            SaveFileDialog s        = new SaveFileDialog();

            s.Title       = "保存Excel文件";
            s.Filter      = "Excel文件(*.xls)|*.xls";
            s.FilterIndex = 1;
            if (s.ShowDialog() == DialogResult.OK)
            {
                filePath = s.FileName;
            }
            else
            {
                return;
            }
            //第一步:将dataGridView转化为dataTable,这样可以过滤掉dataGridView中的隐藏列

            DataTable tmpDataTable = new DataTable("tmpDataTable");
            DataTable modelTable   = new DataTable("ModelTable");

            for (int column = 0; column < dataGridView.Columns.Count; column++)
            {
                if (dataGridView.Columns[column].Visible == true)
                {
                    DataColumn tempColumn = new DataColumn(dataGridView.Columns[column].HeaderText, typeof(string));
                    tmpDataTable.Columns.Add(tempColumn);
                    DataColumn modelColumn = new DataColumn(dataGridView.Columns[column].Name, typeof(string));
                    modelTable.Columns.Add(modelColumn);
                }
            }
            for (int row = 0; row < dataGridView.Rows.Count; row++)
            {
                if (dataGridView.Rows[row].Visible == false)
                {
                    continue;
                }
                DataRow tempRow = tmpDataTable.NewRow();
                for (int i = 0; i < tmpDataTable.Columns.Count; i++)
                {
                    tempRow[i] = dataGridView.Rows[row].Cells[modelTable.Columns[i].ColumnName].Value;
                }
                tmpDataTable.Rows.Add(tempRow);
            }
            if (tmpDataTable == null)
            {
                return;
            }

            //第二步:导出dataTable到Excel
            long rowNum    = tmpDataTable.Rows.Count;    //行数
            int  columnNum = tmpDataTable.Columns.Count; //列数

            Excel.Application m_xlApp = new Excel.Application();
            m_xlApp.DisplayAlerts = false;//不显示更改提示
            m_xlApp.Visible       = false;

            Excel.Workbooks workbooks = m_xlApp.Workbooks;
            Excel.Workbook  workbook  = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
            Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];//取得sheet1

            try
            {
                string[,] datas = new string[rowNum + 1, columnNum];
                for (int i = 0; i < columnNum; i++) //写入字段
                {
                    datas[0, i] = tmpDataTable.Columns[i].Caption;
                }
                //Excel.Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, columnNum]);
                Excel.Range range = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[1, columnNum]];
                range.Interior.ColorIndex = 15;//15代表灰色
                range.Font.Bold           = true;
                range.Font.Size           = 10;

                int r = 0;
                for (r = 0; r < rowNum; r++)
                {
                    for (int i = 0; i < columnNum; i++)
                    {
                        object obj = tmpDataTable.Rows[r][tmpDataTable.Columns[i].ToString()];
                        datas[r + 1, i] = obj == null ? "" : "'" + obj.ToString().Trim();//在obj.ToString()前加单引号是为了防止自动转化格式
                    }
                    System.Windows.Forms.Application.DoEvents();
                    //添加进度条
                }

                Excel.Range fchR = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]];
                fchR.Value2 = datas;

                worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。

                m_xlApp.Visible = false;


                range = m_xlApp.Range[worksheet.Cells[1, 1], worksheet.Cells[rowNum + 1, columnNum]];

                range.Font.Size           = 9;
                range.RowHeight           = 14.25;
                range.Borders.LineStyle   = 1;
                range.HorizontalAlignment = 1;
                workbook.Saved            = true;
                workbook.SaveCopyAs(filePath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出异常:" + ex.Message, "导出异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                EndReport();
            }

            m_xlApp.Workbooks.Close();
            m_xlApp.Workbooks.Application.Quit();
            m_xlApp.Application.Quit();
            m_xlApp.Quit();
            MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Esempio n. 59
0
        private async void OnGeneratePayload(object obj)
        {
            var listener = Listeners.FirstOrDefault(l => l.ListenerName.Equals(SelectedListener.Split(":")[0].TrimEnd(), StringComparison.OrdinalIgnoreCase));

            var req = new PayloadRequest();

            switch (listener.ListenerType)
            {
            case ListenerType.HTTP:
                req = new HttpPayloadRequest {
                    ListenerGuid = listener.ListenerGuid, SleepInterval = SleepInterval, SleepJitter = SleepJitter
                };
                break;

            case ListenerType.TCP:
                req = new TcpPayloadRequest {
                    ListenerGuid = listener.ListenerGuid
                };
                break;

            case ListenerType.SMB:
                req = new SmbPayloadRequest {
                    ListenerGuid = listener.ListenerGuid
                };
                break;
            }

            req.KillDate = KillDate;

            if (SelectedFormat.Equals("PowerShell", StringComparison.OrdinalIgnoreCase) || SelectedFormat.Contains("EXE", StringComparison.OrdinalIgnoreCase))
            {
                req.OutputType = OutputType.Exe;
            }

            var window = new Window
            {
                Height = 100,
                Width  = 360,
                WindowStartupLocation = WindowStartupLocation.CenterOwner,
                Content = new ProgressBarView {
                    DataContext = new ProgressBarViewModel {
                        Label = "Building..."
                    }
                }
            };

            window.Show();

            var payload = new byte[] { };

            switch (listener.ListenerType)
            {
            case ListenerType.HTTP:
                payload = await PayloadAPI.GenerateHttpStager(req as HttpPayloadRequest);

                break;

            case ListenerType.TCP:
                payload = await PayloadAPI.GenerateTcpStager(req as TcpPayloadRequest);

                break;

            case ListenerType.SMB:
                payload = await PayloadAPI.GenerateSmbStager(req as SmbPayloadRequest);

                break;
            }

            window.Close();

            if (payload.Length > 0)
            {
                if (SelectedFormat.Equals("PowerShell", StringComparison.OrdinalIgnoreCase))
                {
                    var launcher    = PowerShellLauncher.GenerateLauncher(payload);
                    var encLauncher = Convert.ToBase64String(Encoding.Unicode.GetBytes(launcher));

                    var powerShellPayloadViewModel = new PowerShellPayloadViewModel
                    {
                        Launcher    = $"powershell.exe -nop -w hidden -c \"{launcher}\"",
                        EncLauncher = $@"powershell.exe -nop -w hidden -enc {encLauncher}",
                    };

                    var powerShellPayloadView = new PowerShellPayloadView
                    {
                        DataContext = powerShellPayloadViewModel
                    };

                    powerShellPayloadView.Show();
                }
                else
                {
                    var save = new SaveFileDialog();

                    if (SelectedFormat.Contains("EXE", StringComparison.OrdinalIgnoreCase))
                    {
                        save.Filter = "EXE (*.exe)|*.exe";
                    }
                    else if (SelectedFormat.Contains("DLL", StringComparison.OrdinalIgnoreCase))
                    {
                        save.Filter = "DLL (*.dll)|*.dll";
                    }

                    if ((bool)save.ShowDialog())
                    {
                        File.WriteAllBytes(save.FileName, payload);
                    }
                }
            }

            View.Close();
        }
Esempio n. 60
0
        private void cStructsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sd = new SaveFileDialog()
            {
                DefaultExt = "c", Filter = "C Files|*.c"
            })
                if (sd.ShowDialog(this) == DialogResult.OK)
                {
                    bool dx = false;
                    if (outfmt == ModelFormat.Basic)
                    {
                        dx = MessageBox.Show(this, "Do you want to export in SADX format?", "SAMDL", MessageBoxButtons.YesNo) == DialogResult.Yes;
                    }
                    List <string> labels = new List <string>()
                    {
                        model.Name
                    };
                    using (StreamWriter sw = File.CreateText(sd.FileName))
                    {
                        sw.Write("/* NINJA ");
                        switch (outfmt)
                        {
                        case ModelFormat.Basic:
                        case ModelFormat.BasicDX:
                            if (dx)
                            {
                                sw.Write("Basic (with Sonic Adventure DX additions)");
                            }
                            else
                            {
                                sw.Write("Basic");
                            }
                            break;

                        case ModelFormat.Chunk:
                            sw.Write("Chunk");
                            break;
                        }
                        sw.WriteLine(" model");
                        sw.WriteLine(" * ");
                        sw.WriteLine(" * Generated by SAMDL");
                        sw.WriteLine(" * ");
                        if (modelFile != null)
                        {
                            if (!string.IsNullOrEmpty(modelFile.Description))
                            {
                                sw.Write(" * Description: ");
                                sw.WriteLine(modelFile.Description);
                                sw.WriteLine(" * ");
                            }
                            if (!string.IsNullOrEmpty(modelFile.Author))
                            {
                                sw.Write(" * Author: ");
                                sw.WriteLine(modelFile.Author);
                                sw.WriteLine(" * ");
                            }
                        }
                        sw.WriteLine(" */");
                        sw.WriteLine();
                        string[] texnames = null;
                        if (TexturePackName != null)
                        {
                            texnames = new string[TextureInfo.Length];
                            for (int i = 0; i < TextureInfo.Length; i++)
                            {
                                texnames[i] = string.Format("{0}TexName_{1}", TexturePackName, TextureInfo[i].Name);
                            }
                            sw.Write("enum {0}TexName", TexturePackName);
                            sw.WriteLine();
                            sw.WriteLine("{");
                            sw.WriteLine("\t" + string.Join("," + Environment.NewLine + "\t", texnames));
                            sw.WriteLine("};");
                            sw.WriteLine();
                        }
                        model.ToStructVariables(sw, dx, labels, texnames);
                    }
                }
        }