Beispiel #1
1
		private void OnProcessFileDialog(Object sender, FileDialogEventArgs e)
		{
			switch (e.Mode)
			{
				case FileDialogMode.Save:
					using (var saveDialog = new SaveFileDialog())
					{
						saveDialog.Title = e.Title;
						saveDialog.Filter = e.Filter;
						saveDialog.FileName = e.DefaultFileName;
						if (saveDialog.ShowDialog() != DialogResult.Cancel)
						{
							FormProgress.ShowProgress();
							FormProgress.SetTitle("Downloading…", true);
							FormProgress.SetDetails(Path.GetFileName(saveDialog.FileName));
							TabControl.Enabled = false;
							Application.DoEvents();
							e.Continue(saveDialog.FileName);
						}
						else
							e.Cancel();
					}
					break;
			}
			e.Handled = true;
		}
Beispiel #2
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog o = new SaveFileDialog();
            o.AddExtension = true;
            o.CheckPathExists = true;
            o.DefaultExt = "wav";
            o.Filter = "WAVE audio (*.wav)|*.wav";
            o.OverwritePrompt = true;
            if (o.ShowDialog() == DialogResult.OK)
                soundBase.Save_WAV(o.FileName, false);

            if (soundBase.CanLoop)
            {
                XElement xml = XElement.Load(Application.StartupPath + Path.DirectorySeparatorChar + "Plugins" +
                    Path.DirectorySeparatorChar + "SoundLang.xml");
                xml = xml.Element(pluginHost.Get_Language()).Element("SoundControl");
                if (MessageBox.Show(xml.Element("S05").Value, "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    if (o.ShowDialog() == DialogResult.OK)
                    {
                        string path = Path.GetDirectoryName(o.FileName) + Path.DirectorySeparatorChar +
                            Path.GetFileNameWithoutExtension(o.FileName) + "_loop.wav";
                        soundBase.Save_WAV(path, true);
                    }
                }
            }
        }
Beispiel #3
0
        // TODO: organise Dialogs.cs

        #region FileSelectFile

        /// <summary>
        /// Displays a standard dialog that allows the user to open or save files.
        /// </summary>
        /// <param name="OutputVar">The user selected files.</param>
        /// <param name="Options">
        /// <list type="bullet">
        /// <item><term>M</term>: <description>allow muliple files to be selected.</description></item>
        /// <item><term>S</term>: <description>show a save as dialog rather than a file open dialog.</description></item>
        /// <item><term>1</term>: <description>only allow existing file or directory paths.</description></item>
        /// <item><term>8</term>: <description>prompt to create files.</description></item>
        /// <item><term>16:</term>: <description>prompt to overwrite files.</description></item>
        /// <item><term>32</term>: <description>follow the target of a shortcut rather than using the shortcut file itself.</description></item>
        /// </list>
        /// </param>
        /// <param name="RootDir">The file path to initially select.</param>
        /// <param name="Prompt">Text displayed in the window to instruct the user what to do.</param>
        /// <param name="Filter">Indicates which types of files are shown by the dialog, e.g. <c>Audio (*.wav; *.mp2; *.mp3)</c>.</param>
        public static void FileSelectFile(out string OutputVar, string Options, string RootDir, string Prompt, string Filter)
        {
            bool save = false, multi = false, check = false, create = false, overwite = false, shortcuts = false;

            Options = Options.ToUpperInvariant();

            if (Options.Contains("M"))
            {
                Options = Options.Replace("M", string.Empty);
                multi = true;
            }

            if (Options.Contains("S"))
            {
                Options = Options.Replace("S", string.Empty);
                save = true;
            }

            int result;

            if (int.TryParse(Options.Trim(), out result))
            {
                if ((result & 1) == 1 || (result & 2) == 2)
                    check = true;

                if ((result & 8) == 8)
                    create = true;

                if ((result & 16) == 16)
                    overwite = true;

                if ((result & 32) == 32)
                    shortcuts = true;
            }

            ErrorLevel = 0;
            OutputVar = null;

            if (save)
            {
                var saveas = new SaveFileDialog { CheckPathExists = check, CreatePrompt = create, OverwritePrompt = overwite, DereferenceLinks = shortcuts, Filter = Filter };
                var selected = dialogOwner == null ? saveas.ShowDialog() : saveas.ShowDialog(dialogOwner);

                if (selected == DialogResult.OK)
                    OutputVar = saveas.FileName;
                else
                    ErrorLevel = 1;
            }
            else
            {
                var open = new OpenFileDialog { Multiselect = multi, CheckFileExists = check, DereferenceLinks = shortcuts, Filter = Filter };
                var selected = dialogOwner == null ? open.ShowDialog() : open.ShowDialog(dialogOwner);

                if (selected == DialogResult.OK)
                    OutputVar = multi ? string.Join("\n", open.FileNames) : open.FileName;
                else
                    ErrorLevel = 1;
            }
        }
Beispiel #4
0
 private void сохранитьКакToolStripMenuItem_Click(object sender, EventArgs e)
 {
     SaveFileDialog saveFileDialog1 = new SaveFileDialog();
     saveFileDialog1.Title = "Сохранить";
     saveFileDialog1.Filter = "Файлы блокнота|*.txt";
     saveFileDialog1.ShowDialog();
     if (saveFileDialog1.FileName != "")
     {
         saveFileDialog1.ShowDialog();
         System.IO.File.WriteAllText(saveFileDialog1.FileName, textBox1.Text);
     }
 }
 private static string callSaveFileDialog(string startFileName, string fileTypes, IWin32Window parentForm, ScriptEngine engine)
 {
     try {
         SaveFileDialog dlg = new SaveFileDialog();
         dlg.FileName = startFileName;
         dlg.Filter = fileTypes;
         DialogResult result = parentForm == null ? dlg.ShowDialog() : dlg.ShowDialog(parentForm);
         return result == DialogResult.OK ? dlg.FileName : string.Empty;
     } catch (Exception ex) {
         throw ex.convertException(engine);
     }
 }
        private void Browse(object sender, EventArgs e)
        {
            Button b = sender as Button;
            TextBox t = b.Tag as TextBox;

            OpenFileDialog ofd = new OpenFileDialog();
            SaveFileDialog sfd = new SaveFileDialog();

            if (t.Name == "txtInput")
            {
                // ofd
                ofd.Filter = "Bitmap Files (*.bmp)|*.bmp";
                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return;
                t.Text = ofd.FileName;
            }
            else if (t.Name == "txtOutput")
            {
                if (rdbHide.Checked)
                {
                    // sfd
                    sfd.Filter = "Bitmap Files (*.bmp)|*.bmp";
                    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return;
                    t.Text = sfd.FileName;
                }
                else
                {
                    // ofd
                    ofd.Filter = "Bitmap Files (*.bmp)|*.bmp";
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return;
                    t.Text = ofd.FileName;
                }

            }
            else if (t.Name == "txtData")
            {
                if (rdbHide.Checked)
                {
                    // ofd
                    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return;
                    t.Text = ofd.FileName;
                }
                else
                {
                    // sfd
                    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return;
                    t.Text = sfd.FileName;
                }
            }
        }
Beispiel #7
0
		string ShowDialog()
		{
			DialogResult result = DialogResult.Ignore;
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.Filter = DialogFilter;
			dlg.InitialDirectory = Program.UserDataPath;
			dlg.CheckFileExists = false;
			if (CallerControl != null)
				CallerControl.Invoke(new Action(() => result = dlg.ShowDialog()));
			else
				result = dlg.ShowDialog();
			if (result == DialogResult.OK)
				return dlg.FileName;
			return string.Empty;
		}
Beispiel #8
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.textBox1.Text.Trim()))
            {
                MessageBox.Show("请输入需要转换的信息!");
            }

            string content = this.textBox1.Text;
            SaveFileDialog sFD = new SaveFileDialog();
            sFD.DefaultExt = "*.png|*.png";
            sFD.AddExtension = true;            
            
            try
            {
                if (sFD.ShowDialog() == DialogResult.OK)
                {
                    //string content = @"url:http://writeblog.csdn.net/PostEdit.aspx; name:nickwar";
                    COMMON.ByteMatrix byteMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 350, 350);
                    writeToFile(byteMatrix, System.Drawing.Imaging.ImageFormat.Png, sFD.FileName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 internal void SaveToFile()
 {
     SaveFileDialog sfd = new SaveFileDialog();
     sfd.AddExtension = true;
     //sfd.CheckFileExists = true;
     //sfd.CheckPathExists = true;
     sfd.CreatePrompt = true;
     sfd.DefaultExt = "rtf";
     sfd.Filter = "リッチテキストフォーマット|*.rtf";
     if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
     {
         Stream write = null;
         try
         {
             write = sfd.OpenFile();
             rtb_thread_main.SaveFile(write, RichTextBoxStreamType.RichText);
             MessageBox.Show("セーブ成功しました。");
         }
         catch (System.IO.IOException)
         {
             MessageBox.Show("セーブ失敗ました。");
         }
         finally
         {
             if (write != null)
             {
                 write.Close();
             }
         }
     }
 }
Beispiel #10
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "图象另存为";
            sfd.OverwritePrompt = true;
            sfd.CheckPathExists = true;
            sfd.Filter = cmbSaveFiletype.Text + "|" + cmbSaveFiletype.Text;
            sfd.ShowHelp = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string strFileName = sfd.FileName;
                switch (cmbSaveFiletype.Text)
                {
                    case "*.bmp":
                        m_bitmap.Save(strFileName, ImageFormat.Bmp);
                        break;

                    case "*.jpg":
                        m_bitmap.Save(strFileName, ImageFormat.Jpeg);
                        break;

                    case "*.gif":
                        m_bitmap.Save(strFileName, ImageFormat.Gif);
                        break;

                    case "*.tif":
                        m_bitmap.Save(strFileName, ImageFormat.Tiff);
                        break;
                }
                MessageBox.Show("图象文件格式转换成功!", "恭喜", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
 /// <summary>
 /// Function to take backup
 /// </summary>
 public void TakeBackUp()
 {
     try
     {
         if (MessageBox.Show("Do you want to take back up?", "OpenMiracle", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
         {
             if (sqlcon.State == ConnectionState.Closed)
             {
                 sqlcon.Open();
             }
             string strPath = Application.StartupPath + "\\Data\\" + PublicVariables._decCurrentCompanyId + "\\DBOpenMiracle.mdf";
             SaveFileDialog saveBackupDialog = new SaveFileDialog();
             string strDestinationPath = string.Empty;
             string strFname = "DBOpenMiracle" + DateTime.Now.ToString("ddMMyyyhhmmss");
             saveBackupDialog.FileName = strFname;
             if (saveBackupDialog.ShowDialog() == DialogResult.OK)
             {
                 strDestinationPath = saveBackupDialog.FileName;
                 strDestinationPath = "'" + strDestinationPath + ".bak'";
                 SqlCommand sccmd = new SqlCommand("CompanyBackUpDb", sqlcon);
                 sccmd.CommandType = CommandType.StoredProcedure;
                 sccmd.Parameters.Add("@path", SqlDbType.VarChar).Value = strPath;
                 sccmd.Parameters.Add("@name", SqlDbType.VarChar).Value = strDestinationPath;
                 decimal decEffect = Convert.ToDecimal(sccmd.ExecuteNonQuery().ToString());
                 MessageBox.Show("The backup of database  completed successfully", "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("BR 1 : " + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
 }
        public void CommandExport(object param)
        {
            if (!TilePoolExists(param))
                return;

            Guid uid = (Guid)param;
            TilePool tilePool = Editor.Project.TilePoolManager.Pools[uid];

            using (System.Drawing.Bitmap export = tilePool.TileSource.CreateBitmap()) {
                using (SaveFileDialog ofd = new SaveFileDialog()) {
                    ofd.Title = "Export Raw Tileset";
                    ofd.Filter = "Portable Network Graphics (*.png)|*.png|Windows Bitmap (*.bmp)|*.bmp|All Files|*";
                    ofd.OverwritePrompt = true;
                    ofd.RestoreDirectory = false;

                    if (ofd.ShowDialog() == DialogResult.OK) {
                        try {
                            export.Save(ofd.FileName);
                        }
                        catch {
                            MessageBox.Show("Could not save image file.", "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                    }
                }
            }
        }
Beispiel #13
0
        /// <summary>
        /// 
        /// </summary>
        public static void SaveScene(bool saveAs)
        {
            if (SceneManager.ActiveScene == null) return;

            if (!File.Exists(SceneManager.ActiveScenePath))
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.InitialDirectory = SceneManager.GameProject.ProjectPath;
                sfd.Filter = "(*.scene)|*.scene";
                DialogResult dr = sfd.ShowDialog();

                if (dr == DialogResult.Yes || dr == DialogResult.OK)
                {
                    SceneManager.ActiveScenePath = sfd.FileName;
                }
                else
                {
                    return;
                }
            }

            if (saveAs)
            {
                // TODO: implement "Save As" funcionality

            }
            else
            {
                SceneManager.ActiveScene.SaveComponentValues();
                SceneManager.SaveActiveScene();
            }
        }
Beispiel #14
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            var saveFileDlg = new SaveFileDialog {Filter = Resources.SaveFileFilter};

            if (DialogResult.OK.Equals(saveFileDlg.ShowDialog()))
            {
                var workbookParameterContainer = new WorkbookParameterContainer();
                workbookParameterContainer.Load(@"Template\Template.xml");
                SheetParameterContainer sheetParameterContainer = workbookParameterContainer["重复单元格式化器"];

                ExportHelper.ExportToLocal(@"Template\Template.xls", saveFileDlg.FileName,
                    new SheetFormatter("重复单元格式化器",
                        new RepeaterFormatter<StudentInfo>(sheetParameterContainer["rptStudentInfo_Start"],
                            sheetParameterContainer["rptStudentInfo_End"], StudentLogic.GetList(),
                            new CellFormatter<StudentInfo>(sheetParameterContainer["Name"], t => t.Name),
                            new CellFormatter<StudentInfo>(sheetParameterContainer["Gender"], t => t.Gender ? "男" : "女"),
                            new CellFormatter<StudentInfo>(sheetParameterContainer["Class"], t => t.Class),
                            new CellFormatter<StudentInfo>(sheetParameterContainer["RecordNo"], t => t.RecordNo),
                            new CellFormatter<StudentInfo>(sheetParameterContainer["Phone"], t => t.Phone),
                            new CellFormatter<StudentInfo>(sheetParameterContainer["Email"], t => t.Email)
                            )
                        )
                    );
            }
        }
Beispiel #15
0
        public static bool SaveDIBAs(string picname, IntPtr bminfo, IntPtr pixdat)
        {
            SaveFileDialog sd = new SaveFileDialog();

            sd.FileName = picname;
            sd.Title = "Save bitmap as...";
            sd.Filter = "Bitmap file (*.bmp)|*.bmp|TIFF file (*.tif)|*.tif|JPEG file (*.jpg)|*.jpg|PNG file (*.png)|*.png|GIF file (*.gif)|*.gif|All files (*.*)|*.*";
            sd.FilterIndex = 1;
            if (sd.ShowDialog() != DialogResult.OK)
                return false;

            Guid clsid;
            if (!GetCodecClsid(sd.FileName, out clsid))
            {
                MessageBox.Show("Unknown picture format for extension " + Path.GetExtension(sd.FileName),
                                "Image Codec", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }

            IntPtr img = IntPtr.Zero;
            int st = GdipCreateBitmapFromGdiDib(bminfo, pixdat, ref img);
            if ((st != 0) || (img == IntPtr.Zero))
                return false;

            st = GdipSaveImageToFile(img, sd.FileName, ref clsid, IntPtr.Zero);
            GdipDisposeImage(img);
            return st == 0;
        }
Beispiel #16
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            //string filename = "Azure_Pass_Account" +/* datePicker.ToString() + */inputApplicant.Text;
            Excel.Application excel = new Excel.Application();
            excel.Visible = true;
            Excel.Workbook wb = excel.Workbooks.Add(1);
            Excel.Worksheet sh = wb.Sheets.Add();
            datePicker.Format = DateTimePickerFormat.Custom;
            datePicker.CustomFormat = "yyMMdd";

            sh.Name = "Azure Account";

            sh.Cells[1, "A"].Value2 = "Index";
            sh.Cells[1, "B"].Value2 = "Account";
            sh.Cells[1, "C"].Value2 = "Password";
            sh.Cells[1, "D"].Value2 = "Applicant";

            for(int index = 1; index <= Int32.Parse( inputAmount.Text); index   ++)
            {
                sh.Cells[index + 1 ,"A"].Value2 = index;
                sh.Cells[index + 1, "B"].Value2 = "MS" + datePicker.Text + index.ToString("000") + "@outlook.com";
                sh.Cells[index + 1, "C"].Value2 = "MS" + datePicker.Text;
                sh.Cells[index + 1, "D"].Value2 = inputApplicant.Text;
            }

            string filename = "Azure_Pass_Account_" + datePicker.Text + "_" + inputApplicant.Text + "_Auto_Generate";
            SaveFileDialog mySaveFileDialog = new SaveFileDialog();
            mySaveFileDialog.FileName = filename;
            mySaveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx";
            mySaveFileDialog.ShowDialog();

            excel.Quit();
        }
Beispiel #17
0
        public bool export()
        {
            checkStuff();

            SaveFileDialog ofd = new SaveFileDialog();
            ofd.Filter = LanguageManager.Get("Filters", "png");
            if (ofd.ShowDialog(win) == DialogResult.Cancel) return false;
            calcSizes();

            Bitmap b = new Bitmap(tx, ty);
            Graphics bgfx = Graphics.FromImage(b);
            int x = 0;
            foreach (PixelPalettedImage img in imgs)
            {
                int y = 0;
                foreach (Palette pal in pals)
                {
                    Bitmap bb = img.render(pal);
                    bgfx.DrawImage(bb, x, y, bb.Width, bb.Height);
                    bb.Dispose();
                    y += tys;
                }
                x += img.getWidth();
            }

            b.Save(ofd.FileName);
            b.Dispose();
            return true;
        }
            public override void Invoke()
            {
                string value = HtmlSmartTag.Element.GetAttribute("ng-controller").Value;

                if (string.IsNullOrEmpty(value))
                    value = "myController";

                string folder = ProjectHelpers.GetProjectFolder(EditorExtensionsPackage.DTE.ActiveDocument.FullName);
                string file;

                using (var dialog = new SaveFileDialog())
                {
                    dialog.FileName = value + ".js";
                    dialog.DefaultExt = ".js";
                    dialog.Filter = "JS files | *.js";
                    dialog.InitialDirectory = folder;

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

                    file = dialog.FileName;
                }

                EditorExtensionsPackage.DTE.UndoContext.Open(this.DisplayText);

                string script = GetScript(value);
                File.WriteAllText(file, script);

                ProjectHelpers.AddFileToActiveProject(file);
                EditorExtensionsPackage.DTE.ItemOperations.OpenFile(file);

                EditorExtensionsPackage.DTE.UndoContext.Close();
            }
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
              SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            string fname = "";
            saveFileDialog1.Filter = "Microsoft Excel (*.xls)|*.xls";


            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                fname = saveFileDialog1.FileName;
                try
                {
                    dsoFramerControl1.FileSave(saveFileDialog1.FileName, true);
                    
                    if (MsgBox.ShowAskMessageBox("导出成功,是否打开该文档?") != DialogResult.OK)
                    {
                       
                        ExcelAccess ex = new ExcelAccess();
                        ex.Open(fname);
                        //此处写填充内容代码
                        ex.ShowExcel();
                        return;
                    }
                }
                catch
                {
                    MsgBox.ShowSuccessfulMessageBox("无法保存" + fname + "。请用其他文件名保存文件,或将文件存至其他位置。");
                    return;
                }
            }
        }
Beispiel #20
0
        /// <summary>
        /// Displays a save file dialog.
        /// </summary>
        /// <param name="title">Dialog title.</param>
        /// <param name="startPath">Initial path.</param>
        /// <param name="extension">File extension filter.</param>
        /// <param name="callback">Callback that is executed after the dialog completes.</param>
        /// <returns>True if succeeded.</returns>
        public static bool FileSave(String title, String startPath, String extension, Action<String> callback)
        {
            var dialog = new SaveFileDialog
            {
                Title = title,
                InitialDirectory = startPath,
                DefaultExt = @"*.*",
                Filter = extension,
                CheckPathExists = true,
                OverwritePrompt = true
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (callback != null)
                {
                    callback(dialog.FileName);
                }
            }
            else
            {
                if (callback != null)
                {
                    callback(String.Empty);
                }
                return false;
            }

            return true;
        }
Beispiel #21
0
 public static void ExportGridEx(Janus.Windows.GridEX.GridEX gridEx )
 {
     Stream sw = null;
     try
     {
         var sd = new SaveFileDialog { Filter = "Excel File (*.xml)|*.xml" };
         if (sd.ShowDialog() == DialogResult.OK)
         {
             //sw = new FileStream(sd.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
             sw = new FileStream(sd.FileName, FileMode.Create);
             GridEXExporter grdListExporter = new GridEXExporter();
             grdListExporter.IncludeExcelProcessingInstruction = true;
             grdListExporter.IncludeFormatStyle = true;
             grdListExporter.IncludeHeaders = true;
             grdListExporter.GridEX = gridEx;
             grdListExporter.Export(sw);
             Utility.ShowMsg("Xuất dữ liệu thành công");
         }
     }
     catch (Exception ex)
     {
         Utility.ShowMsg(ex.Message);
     }
     finally
     {
         if (sw != null)
         {
             sw.Flush();
             sw.Close();
             sw.Dispose();
         }
     }
 }
Beispiel #22
0
        private void btnSaveSetList_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dlgSave = new SaveFileDialog())
            {
                dlgSave.Title = "Select where to save the training set to...";
                dlgSave.Filter = "ENFORM Set File (*.eset)|*.eset|Text File (*.txt) |*.txt|Any file (*.*)|*.*";

                if (dlgSave.ShowDialog() == DialogResult.OK)
                {
                    using (StreamWriter w = new StreamWriter(dlgSave.FileName, false))
                    {
                        foreach (selectedSet.SelectedIndexRow row in selectedTable.Rows)
                        {

                            if (row.testingset || row.trainingset)
                            {
                                w.WriteLine(row.subjectid.ToString() + "," + Convert.ToInt32(row.trainingset).ToString() + "," + Convert.ToInt32(row.testingset).ToString() + "," + feretDataSet.faces.Select("subjectid=" +row.subjectid.ToString())[0]["filename"].ToString() );
                            }

                        }

                    }
                }

            }
        }
Beispiel #23
0
        public static int dialSaveFile(ref string dir,
                                      string filter,
                                      string title,
                                      int filterIndex,   
                                      out string path)
        {
            path = "";

            SaveFileDialog dlg = new SaveFileDialog();

            if (Directory.Exists(dir))
                dlg.InitialDirectory = dir;

            dlg.Title = title;
            dlg.Filter = filter;
            dlg.RestoreDirectory = true;
            dlg.FilterIndex = filterIndex;

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                path = dlg.FileName;
                dir = Path.GetDirectoryName(path);
                return dlg.FilterIndex;
            }

            return -1;
        }
Beispiel #24
0
        private void btn_save_Click(object sender, System.EventArgs e)
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = @"Bitmap files (*.bmp)|*.bmp|Image files (*.jpg)|*.jpg|PNG files (*.png)|*.png|" +
                         @"ICO files (*.ico)|*.ico|GIF files (*.gif)|*.gif|TIFF files (*.tiff)|*.tiff|" +
                         @"XPS files (*.xps)|*.xps|PDF files (*.pdf)|*.pdf|PSD files (*.psd)|*.psd"
            };
            if (saveFileDialog.ShowDialog() == DialogResult.Cancel) return;

            // Switch
            //FactorySwitch.ChooseFormat(saveFileDialog.FilterIndex).Save(saveFileDialog.FileName, pctbx_canvas.Image);

            // LinkedList
            //var factory = new FactoryLinked();
            //factory.GetFormat(saveFileDialog.FilterIndex).Save(saveFileDialog.FileName, pctbx_canvas.Image);

            // Loop
            var factory = new FactoryLoop();
            var formats = factory.GetValidFormats(saveFileDialog.FilterIndex);
            foreach (var item in formats)
            {
                item.Save(saveFileDialog.FileName, pctbx_canvas.Image);
            }
        }
        private void yesButton_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog save = new SaveFileDialog())
              {
            save.DefaultExt = "sql";
            save.OverwritePrompt = true;
            save.Filter = "SQL Script Files (*.sql)|*.sql|All Files (*.*)|*.*";
            save.FileName = String.Format("{0}.sql", _tableName);
            save.Title = "Save SQLite Change Script";

            DialogResult = save.ShowDialog(this);

            if (DialogResult == DialogResult.OK)
            {
              _defaultSave = _saveOrig.Checked;

              using (System.IO.StreamWriter writer = new System.IO.StreamWriter(save.FileName, false, Encoding.UTF8))
              {
            if ((_show.Visible == true && _saveOrig.Checked == true) || (_show.Visible == false && _splitter.Panel2Collapsed == true))
            {
              if (_show.Visible == true) writer.WriteLine("/*");
              writer.WriteLine(_original.Text.Replace("\r", "").TrimEnd('\n').Replace("\n", "\r\n"));
              if (_show.Visible == true) writer.WriteLine("*/");
            }
            if (_show.Visible == true || _splitter.Panel2Collapsed == false)
              writer.WriteLine(_script.Text.Replace("\r", "").TrimEnd('\n').Replace("\n", "\r\n"));
              }
            }
              }
              Close();
        }
        private void buttonExtract_Click(object sender, EventArgs e)
        {
            if (!File.Exists(txtCompiledFile.Text))
            {
                MessageBox.Show(this, "Please select a compiled ArchAngel template file.", "Missing File", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = ".stz";
            dialog.Filter = "ArchAngel templates (*.stz)|*.stz";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if (!Directory.Exists(Path.GetDirectoryName(dialog.FileName)))
                {
                    MessageBox.Show(this, "Please specify a valid save location.", "Invalid Folder", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                if (File.Exists(dialog.FileName))
                {
                    Slyce.Common.Utility.DeleteFileBrute(dialog.FileName);
                }
                Project.ExtractTemplateFromCompiledTemplate(txtCompiledFile.Text, dialog.FileName);
                this.FileName = dialog.FileName;
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }
Beispiel #27
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog { Title = "Program to crypt" })
            {
                ofd.Filter = "Programs(*.exe)|*.exe";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    textBox1.Text = ofd.FileName;
                    textBox2.AppendText("Executable loaded!" + Environment.NewLine);
                    using (SaveFileDialog sfd = new SaveFileDialog { Title = "Saves as" })
                    {
                        sfd.Filter = "Programs(*.exe)|*.exe";
                        if (sfd.ShowDialog() == DialogResult.OK)
                        {
                            File.WriteAllBytes(sfd.FileName, Properties.Resources.dependency);
                            Compress(ofd.FileName);
                            byte[] bytes = File.ReadAllBytes(ofd.FileName.Replace(".exe", ".bin"));
                            misc.WriteResource(sfd.FileName, bytes);
                            textBox2.AppendText("Protection done!" + Environment.NewLine);
                            File.Delete(CompressedFile);
                        }
                    }
                }
            }

        }
Beispiel #28
0
        protected override void mergeTiffToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

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

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

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

                    ImageIOHelper.MergeTiff(openFileDialog1.FileNames, saveFileDialog1.FileName);
                    MessageBox.Show(this, Properties.Resources.Mergecompleted + Path.GetFileName(saveFileDialog1.FileName) + Properties.Resources.created, strProgName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
 public static void SaveRadTree(RadTreeView view, IWin32Window frm = null, string filename = "")
 {
     var saveFileDialogCsv = new SaveFileDialog();
     saveFileDialogCsv.Title = "Save data to Comma Separated File";
     saveFileDialogCsv.Filter = "CSV or Excel|*.csv";
     saveFileDialogCsv.CheckPathExists = true;
     saveFileDialogCsv.DefaultExt = "csv";
     saveFileDialogCsv.AddExtension = true;
     saveFileDialogCsv.OverwritePrompt = true;
     saveFileDialogCsv.InitialDirectory = Repository.DataFolder;
     saveFileDialogCsv.FileName = filename;
     if (saveFileDialogCsv.ShowDialog(frm) == System.Windows.Forms.DialogResult.OK)
     {
         try
         {
             sb = new StringBuilder();
             foreach (var node in view.Nodes)
             {
                 sb.AppendLine(node.Text.Replace("<=", ","));
                 ListNodes(node);
             }
             System.IO.File.WriteAllText(saveFileDialogCsv.FileName, sb.ToString(),Encoding.UTF8);
         }
         catch (Exception exc)
         {
             MessageBox.Show(exc.Message, "Unexpected Error");
         }
     }
 }
 public void ExportPDF(DateTime dateFrom, DateTime dateTo)
 {
     Cursor current = this.Cursor;
     this.Cursor = Cursors.WaitCursor;
     if (organizationSumBindingSource.DataSource == null)
         GenerateReportGrid(dateFrom, dateTo);
     try
     {
         SaveFileDialog openFileDialog1 = new SaveFileDialog();
         openFileDialog1.Filter = "Pdf files (*.Pdf)|*.Pdf";
         if (openFileDialog1.ShowDialog() == DialogResult.OK)
         {
             chartControlAnalizeCount.Dock = DockStyle.None;
             chartControlAnalizeCount.Width = 600;
             chartControlAnalizeCount.ExportToPdf(openFileDialog1.FileName);
             chartControlAnalizeCount.Dock = DockStyle.Top;
             System.Diagnostics.Process.Start(openFileDialog1.FileName);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Возможно файл открыт.", "Ошибка сохранения.",
       MessageBoxButtons.OK, MessageBoxIcon.Error);
         this.Cursor = current;
     }
     this.Cursor = current;
 }
Beispiel #31
0
        private static bool saveLicenseFile(LicenseFeaturesParams p, Activation a)
        {
            //globalization
            CultureInfo en = new CultureInfo("en-US"), orig = Thread.CurrentThread.CurrentCulture;

            Thread.CurrentThread.CurrentCulture = en;

            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ActivationCode"]                     = "";
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["AddNewCollectionAvailable"]          = p.AddNewCollection.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["AddNewReportAvailable"]              = p.AddNewReport.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["AddUsersAvailable"]                  = p.AddUsers.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["AdministratorPassword"]              = p.AdministratorPassword;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["AdvancedMenuAvailable"]              = p.AdvancedMenuAvailable.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["AMWTAvailable"]                      = p.EnterLogSheetData.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["CloneReportAvailable"]               = p.Clone.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ConfiguratorAvailable"]              = p.UseConfigurator.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ConfigureDaypartEntryAvailable"]     = p.ConfigureDaypartEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ConfigureDispositionEntryAvailable"] = p.ConfigureDispositionEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ConfigurePrePostEntryAvailable"]     = p.ConfigurePrePostEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ConfigureStationEntryAvailable"]     = p.ConfigureStationEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["CPU_ID"] = "";
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["DaypartEntryAvailable"]        = p.DaypartEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["DefaultUserLevel"]             = p.DefaultUserLevel.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["DispositionEntryAvailable"]    = p.DispositionEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["EnterFinancialsAvailable"]     = p.EnterFinancialsAvailable.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["EnterSWATNotesAvailable"]      = p.EnterSWATNotesAvailable.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ExpirationDate"]               = p.ExpirationDate.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ExpirationWarningsBeginDate"]  = p.ExpirationWarningStartDate.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ExpirationWarningsMode"]       = p.ExpirationWarningsMode.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ExpirationWarningsFrequency"]  = p.ExpirationWarningsFrequency.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ExpirationWarningsUnit"]       = p.ExpirationWarningsUnit;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["FoodCostAdjustmentsAvailable"] = p.FoodCostAdjustments.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["FoodWasteClassAllowed"]        = p.AllowedWasteClassses.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ImportWasteDataAvailable"]     = p.ImportWasteData.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["LicenseType"] = p.LicenseType.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageBaselinesAvailable"]    = p.ManageBaselines.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageDETsAvailable"]         = p.ManageDataEntryTemplates.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageEventClientsAvailable"] = p.ManageEventClients.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageEventOrdersAvailable"]  = p.ManageEventOrders.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageLogFormsAvailable"]     = p.ManageLogForms.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManagePreferencesAvailable"]  = p.ManagePreferences.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageReportsAvailable"]      = p.ManageReportsSettingsShortcut.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageSitesAvailable"]        = p.ManageSites.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageTrackersAvailable"]     = p.ManageTrackers.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManagerPassword"]             = p.ManagerPassword;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ManageTypesAvailable"]        = p.ManageTypesAvailable.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["MaxNumberofFoodTypes"]        = p.FoodTypeLimit.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["MaxNumberofLossTypes"]        = p.LossTypeLimit.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["MaxNumberofSites"]            = p.NumberOfSites.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["MaxNumberofTrackers"]         = p.TrackerLimit.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["MaxNumberofUserTypes"]        = p.UserTypeLimit.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["MaxNumberofDETs"]             = p.DetLimits.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["MaxNumberofReports"]          = p.ReportLimits.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["PrePostEntryAvailable"]       = p.PrePostEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ProductType"] = p.Product.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["RecurringTransactionsAvailable"] = p.RecurringTransactionsAvailable.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["RemoveUsersAvailable"]           = p.RemoveUsers.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ShowSupportEmailAddress"]        = p.ShowSupportEmailAddress.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ShowSupportPhoneNumber"]         = p.ShowSupportPhoneNumber.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ShowSupportWebsite"]             = p.ShowSupportWebSiteURL.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["StationEntryAvailable"]          = p.StationEntry.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["SupportEmailAddress"]            = p.SupportEmailAddress;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["SupportPhoneNumber"]             = p.SupportPhoneNumber;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["UpdateTrackerAvailable"]         = p.UpdateTracker.ToString();
            ///**************
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ClientID"]           = p.ClientID.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ClientName"]         = p.ClientName;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["Generatedby"]        = p.GeneratedBy;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["GeneratedDate"]      = p.GeneratedDate.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["IsActivated"]        = "False";
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["LicenseID"]          = p.LicenseKey;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["LicenseRecordID"]    = p.LicenseID.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ProductVersionName"] = p.ProductVersionName;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["SiteID"]             = p.SiteID.ToString();
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["SiteName"]           = p.SiteName;
            VWA4Common.Security.LicenseUtility.GetLicenseUtility()["SupportWebsite"]     = p.SupportWebSiteURL;
            //VWA4Common.Security.LicenseUtility.GetLicenseUtility()["Create/Save New Reports"] = p.AddNewReport.ToString();

            if (a != null)
            {
                VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ActivationCode"] = a.ActivationCode;
                VWA4Common.Security.LicenseUtility.GetLicenseUtility()["IsActivated"]    = a.IsActivated.ToString();
                VWA4Common.Security.LicenseUtility.GetLicenseUtility()["CPU_ID"]         = a.CPUID.ToString();
                VWA4Common.Security.LicenseUtility.GetLicenseUtility()["ExpirationDate"] = p.ExtendedExpirationDate.ToString();
            }
            //globalization
            Thread.CurrentThread.CurrentCulture = orig;

            SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();

            dlg.InitialDirectory = Application.StartupPath;
            dlg.Filter           = "License files (*.txt)|*.TXT|All files (*.*)|*.*";
            dlg.FileName         = "vw4license.txt";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                VWA4Common.Security.LicenseUtility.GetLicenseUtility().GenerateLicense(dlg.FileName);
                return(true);
            }
            return(false);
        }
Beispiel #32
0
        /// <summary>
        /// 匯出合併欄位總表Word
        /// </summary>
        public static void ExportMappingFieldWord()
        {
            #region 儲存檔案
            string inputReportName = "高雄評量成績單合併欄位總表";
            string reportName      = inputReportName;

            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Reports");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, reportName + ".doc");

            if (File.Exists(path))
            {
                int i = 1;
                while (true)
                {
                    string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                    if (!File.Exists(newPath))
                    {
                        path = newPath;
                        break;
                    }
                }
            }

            Document tempDoc = new Document(new MemoryStream(Properties.Resources.高雄評量成績合併欄位總表_多樣版));
            try
            {
                #region 動態產生合併欄位
                // 讀取總表檔案並動態加入合併欄位

                DocumentBuilder builder = new DocumentBuilder(tempDoc);

                builder.StartTable();
                builder.Write("=== 高雄評量成績單合併欄位總表 ===");
                builder.CellFormat.Borders.LineStyle = LineStyle.None;

                builder.InsertCell();
                builder.Write("學校名稱");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 學校名稱" + " \\* MERGEFORMAT ", "«學校名稱" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("學年度");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 學年度" + " \\* MERGEFORMAT ", "«學年度" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("學期");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 學期" + " \\* MERGEFORMAT ", "«學期" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("試別名稱");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 試別名稱" + " \\* MERGEFORMAT ", "«試別名稱" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("班級");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 班級" + " \\* MERGEFORMAT ", "«班級" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("學號");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 學號" + " \\* MERGEFORMAT ", "«學號" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("座號");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 座號" + " \\* MERGEFORMAT ", "«座號" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("姓名");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 姓名" + " \\* MERGEFORMAT ", "«姓名" + "»");
                builder.EndRow();

                builder.InsertCell();
                builder.Write("領域成績加權平均");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 領域成績加權平均" + " \\* MERGEFORMAT ", "«DA" + "»");
                builder.EndRow();

                builder.InsertCell();
                builder.Write("領域成績加權平均(不含彈性課程)");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 領域成績加權平均(不含彈性課程)" + " \\* MERGEFORMAT ", "«DA" + "»");
                builder.EndRow();

                builder.InsertCell();
                builder.Write("科目評量分數加權平均");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 科目評量分數加權平均" + " \\* MERGEFORMAT ", "«SS" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("科目平時成績加權平均");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 科目平時成績加權平均" + " \\* MERGEFORMAT ", "«SA" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("缺曠紀錄");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 缺曠紀錄" + " \\* MERGEFORMAT ", "«缺曠紀錄" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("服務學習時數");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 服務學習時數" + " \\* MERGEFORMAT ", "«SL" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("校長");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 校長" + " \\* MERGEFORMAT ", "«校長" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("教務主任");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 教務主任" + " \\* MERGEFORMAT ", "«教務主任" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("班導師");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 班導師" + " \\* MERGEFORMAT ", "«班導師" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("成績校正日期");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 成績校正日期" + " \\* MERGEFORMAT ", "«成績校正日期" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("區間開始日期");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 區間開始日期" + " \\* MERGEFORMAT ", "«區間開始日期" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("區間結束日期");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 區間結束日期" + " \\* MERGEFORMAT ", "«區間結束日期" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("大功區間統計");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 大功區間統計" + " \\* MERGEFORMAT ", "«D1A" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("小功區間統計");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 小功區間統計" + " \\* MERGEFORMAT ", "«D1B" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("嘉獎區間統計");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 嘉獎區間統計" + " \\* MERGEFORMAT ", "«D1C" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("大過區間統計");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 大過區間統計" + " \\* MERGEFORMAT ", "«D2A" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("小過區間統計");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 小過區間統計" + " \\* MERGEFORMAT ", "«D2B" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("警告區間統計");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 警告區間統計" + " \\* MERGEFORMAT ", "«D2C" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("監護人姓名");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 監護人姓名" + " \\* MERGEFORMAT ", "«監護人姓名" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("父親姓名");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 父親姓名" + " \\* MERGEFORMAT ", "«父親姓名" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("母親姓名");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 母親姓名" + " \\* MERGEFORMAT ", "«母親姓名" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("戶籍地址");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 戶籍地址" + " \\* MERGEFORMAT ", "«戶籍地址" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("聯絡地址");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 聯絡地址" + " \\* MERGEFORMAT ", "«聯絡地址" + "»");
                builder.EndRow();
                builder.InsertCell();
                builder.Write("其他地址");
                builder.InsertCell();
                builder.InsertField("MERGEFIELD 其他地址" + " \\* MERGEFORMAT ", "«其他地址" + "»");
                builder.EndRow();
                builder.EndTable();

                builder.Writeln();
                builder.Writeln();
                builder.StartTable();
                builder.CellFormat.Borders.LineStyle = LineStyle.None;
                // 領域成績
                builder.Writeln("領域成績");
                builder.InsertCell();
                builder.Write("領域名稱");
                builder.InsertCell();
                builder.Write("加權平均");
                builder.InsertCell();
                builder.Write("平時加權平均");
                builder.InsertCell();
                builder.Write("權數");
                builder.InsertCell();
                builder.Write("努力程度");
                builder.EndRow();

                foreach (string domainName in DomainNameList)
                {
                    builder.InsertCell();
                    builder.Write(domainName);
                    string mName1 = domainName + "_領域加權平均";
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + mName1 + " \\* MERGEFORMAT ", "«DS" + "»");
                    mName1 = domainName + "_領域平時加權平均";
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + mName1 + " \\* MERGEFORMAT ", "«DA" + "»");
                    mName1 = domainName + "_領域權數";
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + mName1 + " \\* MERGEFORMAT ", "«DC" + "»");
                    mName1 = domainName + "_領域努力程度";
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + mName1 + " \\* MERGEFORMAT ", "«DE" + "»");
                    builder.EndRow();
                }
                builder.EndTable();
                builder.Writeln();
                builder.Writeln();


                // 領域科目成績
                foreach (string domainName in DomainNameList)
                {
                    builder.StartTable();
                    builder.CellFormat.Borders.LineStyle = LineStyle.None;

                    builder.Writeln(domainName + "領域");
                    builder.InsertCell();
                    builder.Write("科目名稱");
                    builder.InsertCell();
                    builder.Write("科目權數");
                    builder.InsertCell();
                    builder.Write("科目努力程度");
                    builder.InsertCell();
                    builder.Write("科目評量分數");
                    builder.InsertCell();
                    builder.Write("科目平時成績");
                    builder.InsertCell();
                    builder.Write("科目文字描述");
                    builder.EndRow();
                    // 科目數
                    for (int sj = 1; sj <= 10; sj++)
                    {
                        string sName1 = domainName + "_科目名稱" + sj;
                        builder.InsertCell();
                        builder.InsertField("MERGEFIELD " + sName1 + " \\* MERGEFORMAT ", "«SN" + "»");
                        sName1 = domainName + "_科目權數" + sj;
                        builder.InsertCell();
                        builder.InsertField("MERGEFIELD " + sName1 + " \\* MERGEFORMAT ", "«SC" + "»");
                        sName1 = domainName + "_科目努力程度" + sj;
                        builder.InsertCell();
                        builder.InsertField("MERGEFIELD " + sName1 + " \\* MERGEFORMAT ", "«SE" + "»");
                        sName1 = domainName + "_科目評量分數" + sj;
                        builder.InsertCell();
                        builder.InsertField("MERGEFIELD " + sName1 + " \\* MERGEFORMAT ", "«SS" + "»");
                        sName1 = domainName + "_科目平時成績" + sj;
                        builder.InsertCell();
                        builder.InsertField("MERGEFIELD " + sName1 + " \\* MERGEFORMAT ", "«SA" + "»");
                        sName1 = domainName + "_科目文字描述" + sj;
                        builder.InsertCell();
                        builder.InsertField("MERGEFIELD " + sName1 + " \\* MERGEFORMAT ", "«ST" + "»");
                        builder.EndRow();
                    }
                    builder.EndTable();
                    builder.Writeln();
                    builder.Writeln();
                }
                tempDoc.Save(path, SaveFormat.Doc);
                #endregion

                //System.IO.FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write);

                //stream.Write(Properties.Resources.高雄評量成績合併欄位總表, 0, Properties.Resources.高雄評量成績合併欄位總表.Length);
                //stream.Flush();
                //stream.Close();
                System.Diagnostics.Process.Start(path);
            }
            catch
            {
                System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
                sd.Title    = "另存新檔";
                sd.FileName = reportName + ".doc";
                sd.Filter   = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        tempDoc.Save(sd.FileName, SaveFormat.Doc);
                        //System.IO.FileStream stream = new FileStream(sd.FileName, FileMode.Create, FileAccess.Write);
                        //stream.Write(Properties.Resources.高雄評量成績合併欄位總表, 0, Properties.Resources.高雄評量成績合併欄位總表.Length);
                        //stream.Flush();
                        //stream.Close();
                    }
                    catch
                    {
                        FISCA.Presentation.Controls.MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            #endregion
        }
Beispiel #33
0
        public void dataGridViewExportToExcel(DataGridView dateGridView)
        {
            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.Filter           = "Execl files (*.xls)|*.xls";
            saveFileDialog.FilterIndex      = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt     = true;
            saveFileDialog.Title            = "保存为Excel文件";
            saveFileDialog.ShowDialog();

            if (saveFileDialog.FileName.IndexOf(":") < 0)
            {
                return;                                           //被点了"取消"
            }
            Stream myStream;

            myStream = saveFileDialog.OpenFile();
            StreamWriter sw          = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
            string       columnTitle = "";

            try
            {
                //写入列标题
                for (int i = 0; i < dateGridView.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        columnTitle += "\t";
                    }
                    columnTitle += dateGridView.Columns[i].HeaderText;
                }
                sw.WriteLine(columnTitle);

                //写入列内容

                for (int j = 0; j < dateGridView.Rows.Count - 1; j++)
                {
                    string columnValue = "";
                    for (int k = 0; k < dateGridView.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            columnValue += "\t";
                        }

                        if (dateGridView.Rows[j].Cells[k].Value == null)
                        {
                            columnValue += "";
                        }
                        else
                        {
                            columnValue += dateGridView.Rows[j].Cells[k].Value.ToString().Trim();
                        }
                    }
                    sw.WriteLine(columnValue);
                }
                sw.Close();
                myStream.Close();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }
    private void buttonPressedHandler(object sender, EventArgs e)
    {
        if (levelManager.loading)
        {
            return;
        }

        PressGesture gesture = (PressGesture)sender;
        GameObject   s       = gesture.gameObject;

        if (s.name.Equals(pathBtn.name))
        {
            // Get GameObject at touch location and add a PathFollowing component to it
            Pair <GameObject, GameObject> selectedObject = levelManager.getObjectAtPosition(Camera.main.ScreenToWorldPoint(touchManager.ActiveTouches[0].Position));
            if (selectedObject != null)
            {
                PathFollowing p = selectedObject.second.GetComponent <PathFollowing>();
                if (p != null)
                {
                    DestroyImmediate(p);
                    p = null;

                    p = selectedObject.first.GetComponent <PathFollowing>();
                    DestroyImmediate(p);
                }

                selectedObject.first.AddComponent <PathFollowing>().initDrawing(touchManager.ActiveTouches[touchManager.ActiveTouches.Count - 1].Id, true);
                selectedObject.second.AddComponent <PathFollowing>().initDrawing(touchManager.ActiveTouches[touchManager.ActiveTouches.Count - 1].Id, false);
            }
        }
        else if (s.name.Equals(replaceBtn.name))
        {
            ReplaceObject();
        }
        else if (s.name.Equals(removeBtn.name))
        {
            RemoveObject(false);
        }
        else if (s.name.Equals(pathSliderTab.name))
        {
            pathSliderTouchID = touchManager.ActiveTouches[touchManager.ActiveTouches.Count - 1].Id;
        }
        else if (s.name.Equals(jumpSliderTab.name))
        {
            jumpSliderTouchID = touchManager.ActiveTouches[touchManager.ActiveTouches.Count - 1].Id;
        }
        else if (s.name.Equals(moveSliderTab.name))
        {
            moveSliderTouchID = touchManager.ActiveTouches[touchManager.ActiveTouches.Count - 1].Id;
        }
        else if (s.name.Equals(aiHorizMoveSliderTab.name))
        {
            aiHorizMoveSliderTouchID = touchManager.ActiveTouches[touchManager.ActiveTouches.Count - 1].Id;
        }
        else if (s.name.Equals(resetBtn.name))
        {
            levelManager.revert();
            levelManager.paused = true;
            Time.timeScale      = 0;
        }
        else if (s.name.Equals(exitBtn.name))
        {
#if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
#else
            Application.Quit();
#endif
        }
        else if (s.name.Equals(cameraBtn.name))
        {
            cameraOutline.SetActive(!cameraOutline.activeSelf);
            cameraPanel.SetActive(!cameraPanel.activeSelf);
            snapToGridBtn.GetComponent <Animator>().SetBool("Checked", snapToGrid);
        }
        else if (s.name.Equals(saveBtn.name))
        {
            System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog();
            sfd.Filter      = "Level Design TIME Save File (*.lts)|*.lts";
            sfd.FilterIndex = 0;

            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                saveLoad.save(sfd.FileName);
            }
        }
        else if (s.name.Equals(loadBtn.name))
        {
            levelManager.paused = true;
            Time.timeScale      = 0;

            System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
            ofd.Filter      = "Level Design TIME Save File (*.lts)|*.lts";
            ofd.FilterIndex = 0;

            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                levelManager.loading = true;
                loadingSign.SetActive(true);
                StartCoroutine(saveLoad.loadGame(ofd.FileName));
            }
        }
        else if (s.name.Equals(snapToGridBtn.name))
        {
            snapToGrid = !snapToGrid;
            snapToGridBtn.GetComponent <Animator>().SetBool("Checked", snapToGrid);
        }
        else if (s.name.Equals(bottomCamCanvas.name))
        {
            Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touchManager.ActiveTouches[0].Position);

            PlacementUI.SetActive(true);

            if (activeKey != "" && (database[activeKey].first.tag == "PaintableBackground" || !levelManager.isObjectAtPosition(touchPosition)))
            {
                database[activeKey].first.SetActive(true);
                database[activeKey].second.SetActive(true);
            }

            if (activeKey != "" && database[activeKey].first.tag == "PaintableBackground")
            {
                if (database[activeKey].first.GetComponent <SpriteRenderer>() != null)
                {
                    PlaceObject(touchPosition, true);
                }
                else
                {
                    RemoveObject(true);
                }
                dragging          = true;
                dragStartPosition = touchPosition;
            }
            else if (levelManager.isObjectAtPosition(touchPosition))
            {
                dragging          = true;
                dragStartPosition = touchPosition;
            }
        }
    }
Beispiel #35
0
        public static string BrowseForFileSave(this IServiceProvider provider, IntPtr owner, string filter, string initialPath = null)
        {
            if (string.IsNullOrEmpty(initialPath))
            {
                initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
            }

            IVsUIShell uiShell = provider.GetService(typeof(SVsUIShell)) as IVsUIShell;

            if (null == uiShell)
            {
                using (var sfd = new System.Windows.Forms.SaveFileDialog()) {
                    sfd.AutoUpgradeEnabled = true;
                    sfd.Filter             = filter;
                    sfd.FileName           = Path.GetFileName(initialPath);
                    sfd.InitialDirectory   = Path.GetDirectoryName(initialPath);
                    DialogResult result;
                    if (owner == IntPtr.Zero)
                    {
                        result = sfd.ShowDialog();
                    }
                    else
                    {
                        result = sfd.ShowDialog(NativeWindow.FromHandle(owner));
                    }
                    if (result == DialogResult.OK)
                    {
                        return(sfd.FileName);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            if (owner == IntPtr.Zero)
            {
                ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
            }

            VSSAVEFILENAMEW[] saveInfo = new VSSAVEFILENAMEW[1];
            saveInfo[0].lStructSize  = (uint)Marshal.SizeOf(typeof(VSSAVEFILENAMEW));
            saveInfo[0].pwzFilter    = filter.Replace('|', '\0') + "\0";
            saveInfo[0].hwndOwner    = owner;
            saveInfo[0].nMaxFileName = 260;
            var pFileName = Marshal.AllocCoTaskMem(520);

            saveInfo[0].pwzFileName   = pFileName;
            saveInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
            var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();

            Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
            try {
                int hr = uiShell.GetSaveFileNameViaDlg(saveInfo);
                if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED)
                {
                    return(null);
                }
                ErrorHandler.ThrowOnFailure(hr);
                return(Marshal.PtrToStringAuto(saveInfo[0].pwzFileName));
            } finally {
                if (pFileName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pFileName);
                }
            }
        }
Beispiel #36
0
        protected override bool ProcessKeyPreview(ref Message m)
        {
            KeyEventArgs ke = new KeyEventArgs((Keys)m.WParam.ToInt32() | ModifierKeys);

            FNeedsKeyUp = !(m.Msg == 0x101);

            if (ke.Control && ke.KeyCode == Keys.S && !ke.Alt && m.Msg == 0x100)
            {
                if (!TextDocument.IsReadOnly)
                {
                    SyncControlWithDocument();
                    TextDocument.Save();
                    // Trigger a recompile
                    var project = TextDocument.Project;
                    if (project != null)
                    {
                        project.Save();
                        project.CompileAsync();
                    }
                    OnSavePressed();
                }
                return(true);
            }
            else if (ke.Control && ke.KeyCode == Keys.S && ke.Alt && m.Msg == 0x100)
            {
                string ext = Path.GetExtension(TextDocument.Project.LocalPath);

                var saveDialog = new System.Windows.Forms.SaveFileDialog();
                saveDialog.InitialDirectory = Path.GetDirectoryName(TextDocument.Project.LocalPath);
                saveDialog.Filter           = String.Format("{0} Document (*.{1})|*.{1}", ext.ToUpper(), ext.ToLower());
                saveDialog.AddExtension     = true;

                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(saveDialog.FileName, TextDocument.TextContent);
                }
                return(true);
            }
            else if (ke.Control && ke.KeyCode == Keys.F && m.Msg == 0x100)
            {
                // Show search bar
                FSearchBar.ShowSearchBar();
                return(true);
            }
            else if ((ke.Control && !ke.Alt) && (ke.KeyCode == Keys.Add || ke.KeyCode == Keys.Oemplus))
            {
                if (!FNeedsKeyUp)
                {
                    FNeedsKeyUp = true;
                    this.Font   = new Font(this.Font.Name, this.Font.Size + 1);
                }
                return(true);
            }
            else if ((ke.Control && !ke.Alt) && (ke.KeyCode == Keys.Subtract || ke.KeyCode == Keys.OemMinus))
            {
                if (!FNeedsKeyUp)
                {
                    FNeedsKeyUp = true;
                    this.Font   = new Font(this.Font.Name, this.Font.Size - 1);
                }
                return(true);
            }
            else if ((ke.Control && !ke.Alt) && (ke.KeyCode == Keys.NumPad0 || ke.KeyCode == Keys.D0))
            {
                this.Font = new Font(this.Font.Name, 10);
                return(true);
            }
            else if (ke.KeyCode == Keys.F1 && m.Msg == 0x100)
            {
                if (TextDocument is CSDocument)
                {
                    Process.Start("http://vvvv.org/documentation/plugins");
                }
                else
                {
                    Process.Start("http://vvvv.org/documentation/effects");
                }
                return(true);
            }
            else
            {
                return(base.ProcessKeyPreview(ref m));
            }
        }
Beispiel #37
0
        private void btnRepresentacionImpresa_Click(object sender, RoutedEventArgs e)
        {
            //Descargar representacion impresa.
            try
            {
                clsEntityDeclarant declarante       = new clsEntityDeclarant().cs_pxObtenerUnoPorId(localDB.Cs_pr_Declarant_Id);
                string             currentDirectory = Environment.CurrentDirectory;
                string             pathImage        = currentDirectory + "\\" + declarante.Cs_pr_Ruc + "\\logo.png";
                string             pathDatos        = currentDirectory + "\\" + declarante.Cs_pr_Ruc + "\\informacionImpreso.txt";
                if (File.Exists(pathImage) && File.Exists(pathDatos))
                {
                    StreamReader readDatos    = new StreamReader(pathDatos);
                    string       datosImpresa = readDatos.ReadToEnd();
                    readDatos.Close();

                    clsEntityRetention cabecera = new clsEntityRetention(localDB);
                    cabecera.cs_fxObtenerUnoPorId(IdComprobante);
                    if (cabecera != null)
                    {
                        string[] partes = cabecera.Cs_tag_Id.Split('-');

                        System.Windows.Forms.SaveFileDialog sfdDescargar = new System.Windows.Forms.SaveFileDialog();
                        sfdDescargar.FileName = cabecera.Cs_tag_PartyIdentification_Id + "_" + partes[0] + "_" + partes[1] + ".pdf";
                        DialogResult result = sfdDescargar.ShowDialog();
                        if (result == System.Windows.Forms.DialogResult.OK)
                        {
                            string fileName = sfdDescargar.FileName;
                            if (fileName.Substring(fileName.Length - 4) != ".pdf")
                            {
                                fileName = fileName + ".pdf";
                            }

                            bool procesado = false;
                            if (cabecera.Cs_pr_XML.Trim() != "")
                            {
                                procesado = RepresentacionImpresa.getRepresentacionImpresaRetencion(fileName, cabecera, cabecera.Cs_pr_XML, datosImpresa, pathImage, localDB);
                            }
                            else
                            {
                                //generar xml
                                string xml = string.Empty;

                                xml = new clsNegocioCERetention(localDB).cs_pxGenerarXMLAString(cabecera.Cs_pr_Retention_id);

                                procesado = RepresentacionImpresa.getRepresentacionImpresaRetencion(fileName, cabecera, xml, datosImpresa, pathImage, localDB);
                            }

                            if (procesado)
                            {
                                System.Diagnostics.Process.Start(fileName);
                            }
                            else
                            {
                                System.Windows.Forms.MessageBox.Show("Ha ocurrido un error al procesar la representacion impresa.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("No se encuentra la imagen del logo y/o la información para la representacion impresa. Verifique la existencia de la imagen 'logo.png' y el archivo 'informacionImpreso.txt'  en la ruta de instalación.", "Mensaje", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                clsBaseLog.cs_pxRegistarAdd("pdf repimpresa" + ex.ToString());
            }
        }
Beispiel #38
0
        private void SyncSaveButton_Click(object sender, System.EventArgs e)
        {
            SyncSaveFileDialog.InitialDirectory = MOG_ControllerProject.GetUser().GetUserToolsPath();

            // Save this custom sync file
            if (SyncSaveFileDialog.ShowDialog() == DialogResult.OK)
            {
                string  syncFilename = SyncSaveFileDialog.FileName;
                MOG_Ini syncFile     = new MOG_Ini(syncFilename);

                foreach (TreeNode sectionNode in XboxSincTreeView.Nodes)
                {
                    string section = sectionNode.Text;

                    foreach (TreeNode keyNode in sectionNode.Nodes)
                    {
                        string key = keyNode.Text;

                        if (keyNode.Nodes.Count > 0)
                        {
                            foreach (TreeNode valNode in keyNode.Nodes)
                            {
                                string val = valNode.Text;

                                syncFile.PutString(section, key, val);
                            }
                        }
                        else
                        {
                            syncFile.PutSectionString(section, key);
                        }
                    }
                }

                // Verify that the newly created sync file has the correct number amount of sections
                if (syncFile.SectionExist("Filemap"))
                {
                    if (syncFile.CountKeys("Filemap") > 0 && string.Compare(SyncProjectMapComboBox.Text, "None") == 0)
                    {
                        MOG_Prompt.PromptMessage("Missing syncfile data", "The required 'FILEMAP' section was not found in this custom sync file.  Aborting...");
                        syncFile.CloseNoSave();
                        return;
                    }
                }
                else
                {
                    MOG_Prompt.PromptMessage("Missing syncfile data", "The required 'FILEMAP' section was not found in this custom sync file.  Aborting...");
                    syncFile.CloseNoSave();
                    return;
                }

                // Make sure we have a valid root definition
                if (syncFile.SectionExist(MOG_ControllerProject.GetCurrentSyncDataController().GetPlatformName()))
                {
                    if (syncFile.CountKeys(MOG_ControllerProject.GetCurrentSyncDataController().GetPlatformName()) > 0 && string.Compare(SyncProjectMapComboBox.Text, "None") == 0)
                    {
                        MOG_Prompt.PromptMessage("Missing syncfile data", "The required '" + MOG_ControllerProject.GetCurrentSyncDataController().GetPlatformName() + "' section was not found in this custom sync file.  Aborting...");
                        syncFile.CloseNoSave();
                        return;
                    }
                }
                else
                {
                    MOG_Prompt.PromptMessage("Missing syncfile data", "The required '" + MOG_ControllerProject.GetCurrentSyncDataController().GetPlatformName() + "' section was not found in this custom sync file.  Aborting...");
                    syncFile.CloseNoSave();
                    return;
                }

                // Save out our new syncFile
                syncFile.Save();
                SyncSaveButton.Enabled = false;

                mUserMap = syncFile.GetFilename();
            }
        }
Beispiel #39
0
        private void CreateSkinOverride(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            if (!cbtxtr.Checked && !cbtxmt.Checked && !cbref.Checked)
            {
                MessageBox.Show("Please select at least one Checkbox!");
                return;
            }

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string skintone = "";
                string family   = "";
                if (cbskins.SelectedIndex < 4)
                {
                    skintone = "0000000" + (cbskins.SelectedIndex + 1).ToString() + "-0000-0000-0000-000000000000";
                }
                else if (cbskins.SelectedIndex == 4)
                {
                    skintone = "6baf064a-85ad-4e37-8d81-a987e9f8da46";                                                //Alien Skin
                }
                else if (cbskins.SelectedIndex == 5)
                {
                    skintone = "b6ee1dbc-5bb3-4146-8315-02bd64eda707";                                                //Zombie Skin
                }
                else if (cbskins.SelectedIndex == 6)
                {
                    skintone = "b9a94827-7544-450c-a8f4-6f643ae89a71";                                                //Mannequin Skin
                }
                else if (cbskins.SelectedIndex == 7)
                {
                    skintone = "6eea47c7-8a35-4be7-9242-dcd082f53b55";                                                //CAS Mannequin Skin
                }
                else if (cbskins.SelectedIndex == 8)
                {
                    skintone = "00000000-0000-0000-0000-000000000000";                                                //Vampire
                }
                if (cbskins.SelectedIndex < 4)
                {
                    family = "21afb87c-e872-4f4c-af3c-c3685ed4e220";
                }
                else if (cbskins.SelectedIndex == 4)
                {
                    family = "ad5da337-bdd1-4593-acdd-19001595cbbb";                                                //Alien Skin
                }
                else if (cbskins.SelectedIndex == 5)
                {
                    family = "b6ee1dbc-5bb3-4146-8315-02bd64eda707";                                                //Zombie Skin
                }
                else if (cbskins.SelectedIndex == 6)
                {
                    family = "59621330-1005-4b88-b4f2-77deb751fcf3";                                                //Mannequin Skin
                }
                else if (cbskins.SelectedIndex == 7)
                {
                    family = "59621330-1005-4b88-b4f2-77deb751fcf3";                                                //CAS Mannequin Skin
                }
                else if (cbskins.SelectedIndex == 8)
                {
                    family = "13ae91e7-b825-4559-82a3-0ead8e8dd7fd";                                                //Vampire
                }
                SkinScanner cs = (SkinScanner)pnskin.Tag;
                cs.CreateOverride(skintone, family, sfd.FileName, cbtxmt.Checked, cbtxtr.Checked, cbref.Checked);
            }
        }
        public void GenerateLicense()
        {
            int posID       = 200;
            int posCompany  = 400;
            int posContact  = 800;
            int posUsers    = 1200;
            int posMode     = 1600;
            int posStartDay = 2000;
            int posDays     = 3200;

            /*
             * posNumAccounts
             * */


            byte[] array = new byte[512 * 1024];             // 512K File.
            Random rand  = new Random();

            GeneratorProgressDialog gpd = new GeneratorProgressDialog();

            gpd.Show();

            //progressBar1.Visible = true;

            //progressBar1.PerformStep();
            gpd.Progress.PerformStep();

            for (int i = 0; i < array.Length; i++)
            {
                if (i == 0)
                {
                    statusBar.Text = "Creating Company Entry";
                    //progressBar1.PerformStep();
                    gpd.Progress.PerformStep();

                    CharEnumerator ceCompany = "DOMMONI - ROUNDTABLE COLLABORATION ENVIRONMENT".GetEnumerator();
                    while (ceCompany.MoveNext())
                    {
                        array[i++] = (byte)ceCompany.Current;
                    }
                }

                if (i == posCompany || i == posContact || i == posUsers || i == posMode || i == posDays)
                {
                    if (i == posCompany)
                    {
                        statusBar.Text = "Creating Company Entry";
                        //progressBar1.PerformStep();
                        gpd.Progress.PerformStep();

                        // write the length
                        array[i - 1] = (byte)tfCompanyName.Text.Length;

                        CharEnumerator ceCompany = tfCompanyName.Text.GetEnumerator();
                        while (ceCompany.MoveNext())
                        {
                            array[i++] = (byte)ceCompany.Current;
                        }
                    }
                    if (i == posContact)
                    {
                        statusBar.Text = "Creating Contact Entry";
                        //progressBar1.PerformStep();
                        gpd.Progress.PerformStep();

                        // write the length
                        array[i - 1] = (byte)tfContactName.Text.Length;

                        CharEnumerator ceContact = tfContactName.Text.GetEnumerator();
                        while (ceContact.MoveNext())
                        {
                            array[i++] = (byte)ceContact.Current;
                        }
                    }
                    if (i == posUsers)
                    {
                        statusBar.Text = "Creating number of Users";
                        gpd.Progress.PerformStep();

                        // what if greater than 255?
                        MessageBox.Show("Writing: " + nudNumberOfUsers.Value);
                        array[i] = (byte)nudNumberOfUsers.Value;
                    }
                    if (i == posMode)
                    {
                        //progressBar1.PerformStep();
                        gpd.Progress.PerformStep();
                        statusBar.Text = "Creating Mode Entry";
                        if (rbProduct.Checked)
                        {
                            array[i] = (byte)100;
                        }
                        else
                        {
                            array[i] = (byte)125;
                        }
                    }
                    if (i == posDays && rbTrial.Checked)                    // We only add this if trial mode is set.
                    {
                        statusBar.Text = "Creating Days Entry";

                        array[i] = (byte)nudDaysInTrial.Value;
                    }
                }
                else
                {
                    array[i] = (byte)rand.Next();
                }
            }

            // TODO: Generate/Append a CRC to the file to prevent tampering.

            //progressBar1.Value = 100;
            gpd.Progress.Value = 100;


            //progressBar1.Visible = false;
            statusBar.Text = "Successfully generated license file.";

            saveLicenseFileDlg.FileName = tfCompanyName.Text + ".lic";
            if (saveLicenseFileDlg.ShowDialog() == DialogResult.OK)
            {
                FileStream fs = new FileStream(saveLicenseFileDlg.FileName, FileMode.Create);
                fs.Write(array, 0, array.Length);
                fs.Flush();
                fs.Close();
            }
            gpd.Visible = false;
        }
Beispiel #41
0
        private void linkLabel5_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            #region 儲存檔案
            string inputReportName = "個人學期成績單合併欄位總表.doc";
            string reportName      = inputReportName;

            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Reports");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, reportName + ".doc");

            if (File.Exists(path))
            {
                int i = 1;
                while (true)
                {
                    string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                    if (!File.Exists(newPath))
                    {
                        path = newPath;
                        break;
                    }
                }
            }

            try
            {
                //document.Save(path, Aspose.Words.SaveFormat.Doc);
                System.IO.FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write);
                stream.Write(Properties.Resources.歡樂的合併欄位總表, 0, Properties.Resources.歡樂的合併欄位總表.Length);
                stream.Flush();
                stream.Close();
                System.Diagnostics.Process.Start(path);
            }
            catch
            {
                System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
                sd.Title    = "另存新檔";
                sd.FileName = reportName + ".doc";
                sd.Filter   = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        //document.Save(sd.FileName, Aspose.Words.SaveFormat.Doc);
                        System.IO.FileStream stream = new FileStream(sd.FileName, FileMode.Create, FileAccess.Write);
                        stream.Write(Properties.Resources.歡樂的合併欄位總表, 0, Properties.Resources.歡樂的合併欄位總表.Length);
                        stream.Flush();
                        stream.Close();
                    }
                    catch
                    {
                        FISCA.Presentation.Controls.MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            #endregion
        }
Beispiel #42
0
 private void mnuSaveAs_Click(object sender, System.EventArgs e)
 {
     fileSaver.ShowDialog();
 }
Beispiel #43
0
        public void Cosinus()
        {
            int szerokosc = picture.Width;
            int dlugosc   = picture.Height;

            int[,] tablica = null;
            int    szerokosc1 = szerokosc - (szerokosc % 8);
            int    dlugosc1 = dlugosc - (dlugosc % 8);
            int    pom1 = 0, pom2 = 0;
            int    temp1 = 0, temp2 = 0, fk1 = 0;
            double ulamek1 = 0, ulamek2 = 0;
            int    temp11, temp22, pom11, pom22;
            double Cm = 0, Cn = 0;
            int    x1 = 8, x2 = 8;
            int    krok = 8;
            double liczba = 0;
            int    i, j;

            pom1    = x1;
            pom2    = x2;
            tablica = new int[szerokosc1, dlugosc1];
            System.Windows.Forms.SaveFileDialog sF = new System.Windows.Forms.SaveFileDialog();
            StreamWriter sw = null;

            sF.Filter = "txt Files | *.txt; *.txt|All files| *.*";
            if (sF.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                sw = new StreamWriter(sF.FileName);
            }
            else
            {
                return;
            }
            while (temp2 != dlugosc1)
            {
                while (temp1 != szerokosc1)
                {
                    temp11 = temp1;
                    temp22 = temp2;
                    pom11  = pom1;
                    pom22  = pom2;
                    for (i = temp1; i < pom1; i++)
                    {
                        for (j = temp2; j < pom2; j++)
                        {
                            if (i == 0)
                            {
                                Cm = 1.41;
                            }
                            else
                            {
                                Cm = 1;
                            }
                            if (j == 0)
                            {
                                Cn = 1.41;
                            }
                            else
                            {
                                Cn = 1;
                            }
                            for (int a = temp11; a < pom11; a++)
                            {
                                for (int b = temp22; b < pom22; b++)
                                {
                                    fk1     = Convert.ToInt16(picture.GetPixel(a, b).B);
                                    ulamek1 = (double)Math.Cos(((Math.PI) * i * (2 * (a % 8) + 1)) / 16);
                                    ulamek2 = (double)Math.Cos(((Math.PI) * j * (2 * (a % 8) + 1)) / 16);
                                    liczba  = (liczba + fk1 * ulamek1 * ulamek2);
                                }
                            }
                            tablica[i, j] = (int)(((0.25) * Cm * Cn) * liczba * ulamek1 *
                                                  ulamek2);
                            liczba = 0;
                        }
                    }
                    temp1 = temp1 + krok;
                    pom1  = pom1 + krok;
                }
                temp1 = 0;
                pom1  = krok;
                temp2 = temp2 + krok;
                pom2  = pom2 + krok;
            }
            for (i = 0; i < szerokosc1; i++)
            {
                for (j = 0; j < dlugosc1; j++)
                {
                    sw.Write(tablica[i, j]);
                    sw.Write(' ');
                }
            }
            sw.Close();
            System.Windows.Forms.MessageBox.Show("File compressed.");
            WriteNewDescriptionInImage(picture, "Cosinus.jpg");
        }
Beispiel #44
0
 public DialogResult ShowDialog()
 {
     return(_saveFileDialog.ShowDialog());
 }
Beispiel #45
0
        private void DoReport(string query, string firstParam, string secondParam)
        {
            SqlDataReader sqlReader = null; // инициализируем reader

            using (WinForms.SaveFileDialog saveFileDialog = new WinForms.SaveFileDialog()
            {
                Filter = "PDF file|*.pdf", ValidateNames = true // выбираем фильтр для сохранения
            })
                if (saveFileDialog.ShowDialog() == WinForms.DialogResult.OK)
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4);
                    try
                    {
                        if (tbPercent.Text == "" || cmbGroup.Text == "") // проверяем выбраны ли все параметры
                        {
                            MessageBox.Show("Необходимо выбрать все параметры", "Внимание", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else if (Convert.ToDouble(tbPercent.Text) < 0 || Convert.ToDouble(tbPercent.Text) > 100) // проверяем правильный ли диапазон процента
                        {
                            MessageBox.Show("Введите коректный параметр процента посещения (от 0 до 100)", "Внимание", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            PdfWriter.GetInstance(doc, new FileStream(saveFileDialog.FileName, FileMode.Create));

                            doc.Open();
                            BaseFont             bf    = BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Verdana.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                            BaseFont             italf = BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Verdanai.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                            iTextSharp.text.Font itf   = new iTextSharp.text.Font(bf, 10f, iTextSharp.text.Font.ITALIC);
                            iTextSharp.text.Font htf   = new iTextSharp.text.Font(bf, 20f, iTextSharp.text.Font.NORMAL);
                            iTextSharp.text.Font ttf   = new iTextSharp.text.Font(bf, 10f, iTextSharp.text.Font.NORMAL);
                            iTextSharp.text.Font stf   = new iTextSharp.text.Font(bf, 8f, iTextSharp.text.Font.NORMAL);

                            doc.Add(new iTextSharp.text.Paragraph("ХНЭУ", htf));
                            doc.Add(new iTextSharp.text.Paragraph("им. Семена Кузнеца", ttf));
                            PdfPTable table = new PdfPTable(5);
                            PdfPCell  cell  = new PdfPCell(new Phrase("Список студентов", ttf));
                            cell.Colspan             = 5;
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            table.AddCell(cell);
                            table.AddCell(new Phrase("ФИО", ttf));
                            table.AddCell(new Phrase("Тел.", ttf));
                            table.AddCell(new Phrase("Всего часов", ttf));
                            table.AddCell(new Phrase("Пропущено", ttf));
                            table.AddCell(new Phrase("По ув. причине", ttf));
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            if (rbMore.IsChecked == true)
                            {
                                doc.Add(new iTextSharp.text.Paragraph("Список студентов, у которых % пропусков больше " + tbPercent.Text, ttf));
                            }
                            else if (rbLess.IsChecked == true)
                            {
                                doc.Add(new iTextSharp.text.Paragraph("Список студентов, у которых % пропусков меньше " + tbPercent.Text, ttf));
                            }
                            doc.Add(new iTextSharp.text.Paragraph("Группа: " + cmbGroup.Text, ttf));
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            SqlCommand command = new SqlCommand(query, sqlConnection); // создаем SQL запрос к БД
                            command.Parameters.AddWithValue("@group", firstParam);     // подставляем параметры в запрос
                            command.Parameters.AddWithValue("@percent", secondParam);
                            sqlReader = command.ExecuteReader();                       // исполняем SQL запрос

                            while (sqlReader.Read())                                   // пока sqlReader содержит строки добавляем их в отчет
                            {
                                table.AddCell(new Phrase(sqlReader["name"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["number"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["allhours"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["losthours"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["reason"].ToString(), stf));
                            }
                            doc.Add(table);
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            PdfPTable dateTable = new PdfPTable(1);
                            cell = new PdfPCell(new Phrase("Дата: " + DateTime.Now, ttf));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            cell.Border = 0;
                            dateTable.AddCell(cell);
                            doc.Add(dateTable);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, ex.Source, MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    finally
                    {
                        doc.Close();
                        sqlReader.Close();
                    }
                }
        }
Beispiel #46
0
        private async void btnGenerateSheet_Click(object sender, EventArgs e)
        {
            if (!isConnected)
            {
                MessageBox.Show("Please connect to crm oganization firts!", "Error"); return;
            }
            includeAllEntities = cbIncludeAllEntities.Checked;
            List <string> selectedEntities = new List <string>();

            includeAppend            = cbAppend.Checked;
            includeAssign            = cbAssign.Checked;
            btnGenerateSheet.Enabled = false;
            var tempRoles = new List <SecurityRole>(roles);

            foreach (TreeNode node in this.treeView1.Nodes)
            {
                if (!node.Checked)
                {
                    tempRoles.Remove(tempRoles.Where(x => x.Id.ToString() == node.Name).FirstOrDefault());
                }
            }
            await Task.Run(() =>
            {
                FileManager.WriteToFile(tempRoles.Select(x => x.Id.ToString()).ToList(), "PrevSelectedRoles");
            });

            Console.WriteLine($"Fetching Entity Meta Data!");
            await Task.Run(() =>
            {
                MetaDataHandler metaDataHandler = new MetaDataHandler(orgService);
                if (metaDataList.Count == 0)
                {
                    metaDataList = metaDataHandler.GetEntitiesMetDataList();
                }

                IAsyncResult result = this.BeginInvoke((Action)(() =>
                {
                    ChooseEntities chooseEntities = new ChooseEntities(selectedEntities, metaDataList, metaDataHandler);
                    chooseEntities.ShowDialog();
                }
                                                                ));
                result.AsyncWaitHandle.WaitOne();

                List <Permission> permissionList = new List <Permission>();

                if (includeAllEntities)
                {
                    if (tempRoles.Where(x => x.Name == SystemAdminRoleName).Count() == 0)
                    {
                        tempRoles.Add(roles.Where(x => x.Name == SystemAdminRoleName).FirstOrDefault());
                    }
                    else
                    {
                        isSystemAdminSelected = true;
                    }
                }
                foreach (var role in tempRoles)
                {
                    PrivilegeAccess privilegeAccess = new PrivilegeAccess(orgService);
                    privilegeAccess.GetRolePermission(role, permissionList);

                    result = this.BeginInvoke((Action)(() =>
                    {
                        Console.WriteLine($"Fetching {role.Name} Security Role Details");
                    }
                                                       ));
                    result.AsyncWaitHandle.WaitOne();
                }
                Console.WriteLine($"Creating File!");

                //foreach (var a in metaDataList) {
                //    Console.WriteLine(a.LogicalName +" "+ a.DisplayName +" " + a.SchemaName + " "+ a.GroupName);
                //}

                var fileName = string.Empty;
                result       = this.BeginInvoke((Action)(() =>
                {
                    var saveFileDialog = new System.Windows.Forms.SaveFileDialog();
                    saveFileDialog.DefaultExt = "xlsx";
                    saveFileDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
                    saveFileDialog.ShowDialog();
                    fileName = saveFileDialog.FileName;
                }
                                                         ));
                result.AsyncWaitHandle.WaitOne();
                if (fileName.Length > 0)
                {
                    RolesHandler rolesHandler = new RolesHandler();
                    rolesHandler.SetDisplayNameAndGroup(permissionList, metaDataList);
                    permissionList = permissionList.Where(x => selectedEntities.Contains(x.EntityName)).ToList();
                    permissionList = permissionList.OrderBy(x => x.EntityName).ThenBy(y => y.ActionName).ToList();

                    var dt = rolesHandler.CreateTableForSingleSheet(permissionList);
                    if (isSystemAdminSelected == false)
                    {
                        if (dt.Columns.Contains(SystemAdminRoleName))
                        {
                            dt.Columns.Remove(SystemAdminRoleName);
                        }
                    }
                    rolesHandler.CreateExcel(dt, fileName);
                }


                this.BeginInvoke((Action)(() =>
                {
                    btnGenerateSheet.Enabled = true;
                }
                                          ));
            });
        }
Beispiel #47
0
        private void menuItem4_Click(object sender, System.EventArgs e)
        {
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textDocument.New();
                Paragraph p1 = new Paragraph(textDocument);
                p1.TextContent.Add(new SimpleText(textDocument, "This is a test form generated by the ODF Forms demo generator using the AODL library."));

                Paragraph p2 = new Paragraph(textDocument);

                ODFForm fMain = textDocument.AddNewForm("mainform");

                ODFFrame frame = new ODFFrame(fMain, p2.Content, "frame", "5mm", "5mm", "9cm", "5cm");
                frame.Label      = "Demo Form";
                frame.AnchorType = AnchorType.Paragraph;


                ODFFixedText ft_name = new ODFFixedText(fMain, p2.Content, "ft_name", "8mm", "10mm", "3cm", "4mm");
                ft_name.Label = "Name";

                ODFTextArea name = new ODFTextArea(fMain, p2.Content, "name", "8mm", "14mm", "3cm", "5mm");
                name.CurrentValue = eName.Text;
                name.AnchorType   = AnchorType.Paragraph;

                ODFFixedText ft_surname = new ODFFixedText(fMain, p2.Content, "ft_surname", "8mm", "20mm", "3cm", "4mm");
                ft_surname.Label = "Surname";

                ODFTextArea surname = new ODFTextArea(fMain, p2.Content, "surname", "8mm", "24mm", "3cm", "5mm");
                surname.CurrentValue = eSurname.Text;
                surname.AnchorType   = AnchorType.Paragraph;

                ODFFixedText ft_gender = new ODFFixedText(fMain, p2.Content, "ft_gender", "8mm", "30mm", "3cm", "4mm");
                ft_gender.Label = "Gender";

                ODFListBox gender = new ODFListBox(fMain, p2.Content, "gender", "8mm", "35mm", "3cm", "5mm");

                ODFOption male = new ODFOption(textDocument, "Male");
                if (eGender.SelectedIndex == 0)
                {
                    male.CurrentSelected = true;
                }
                gender.Options.Add(male);
                ODFOption female = new ODFOption(textDocument, "Female");
                if (eGender.SelectedIndex == 1)
                {
                    female.CurrentSelected = true;
                }
                gender.Options.Add(female);
                gender.AnchorType = AnchorType.Paragraph;
                gender.DropDown   = true;

                ODFFixedText ft_age = new ODFFixedText(fMain, p2.Content, "ft_age", "8mm", "40mm", "3cm", "4mm");
                ft_age.Label = "Age";
                ODFFormattedText age = new ODFFormattedText(fMain, p2.Content, "age", "8mm", "44mm", "3cm", "5mm");
                age.CurrentValue = eAge.Value.ToString();
                age.MinValue     = 16;
                age.MaxValue     = 100;


                ODFFixedText ft_addinfo = new ODFFixedText(fMain, p2.Content, "ft_addinfo", "45mm", "10mm", "45mm", "4mm");
                ft_addinfo.Label = "Additional information";

                ODFTextArea addinfo = new ODFTextArea(fMain, p2.Content, "addinfo", "45mm", "14mm", "45mm", "25mm");
                addinfo.CurrentValue = eAdditional.Text;
                addinfo.AnchorType   = AnchorType.Paragraph;
                addinfo.Properties.Add(new SingleFormProperty(textDocument, PropertyValueType.Boolean, "MultiLine", "true"));

                ODFCheckBox usesaodl = new ODFCheckBox(fMain, p2.Content, "usesaodl", "45mm", "40mm", "45mm", "25mm");
                if (eUsesAODL.Checked)
                {
                    usesaodl.CurrentState = State.Checked;
                }
                usesaodl.Label      = "This person uses AODL:)";
                usesaodl.AnchorType = AnchorType.Paragraph;

                fMain.Controls.Add(frame);
                fMain.Controls.Add(ft_name);
                fMain.Controls.Add(name);
                fMain.Controls.Add(ft_surname);
                fMain.Controls.Add(surname);
                fMain.Controls.Add(ft_gender);
                fMain.Controls.Add(gender);
                fMain.Controls.Add(ft_age);
                fMain.Controls.Add(age);
                fMain.Controls.Add(ft_addinfo);
                fMain.Controls.Add(addinfo);
                fMain.Controls.Add(usesaodl);

                textDocument.Content.Add(p1);
                textDocument.Content.Add(p2);

                using (IPackageWriter writer = new OnDiskPackageWriter())
                {
                    textDocument.Save(saveFileDialog1.FileName, new OpenDocumentTextExporter(writer));
                }
                lastOpenedFile = saveFileDialog1.FileName;
            }
        }
        private void GenerateBasedOnData()
        {
            List <string[]> generating = new List <string[]>(); // do ewentualnego sprawdzania

            var attrType = RemoveAt(this.attrType, 0);

            //tutaj dorzucam tworzenie wykresu ciągłego prawdopodobieństwa
            Spline3Deg[,] probabilities = new Spline3Deg[classes, attribs];
            for (int i = 0; i < attribs; i++)
            {
                if (attrType[i].Equals("double") || attrType[i].Equals("integer"))
                {
                    for (int j = 0; j < classes; j++)
                    {
                        int      c    = values.ElementAt(j).Value.Item2.ElementAt(i).Value.Count;
                        double[] y, x = new double[c];
                        SortedList <double, int> temp = new SortedList <double, int>();
                        foreach (var v in values.ElementAt(j).Value.Item2.ElementAt(i).Value)
                        {
                            int tI = v.Value; double tD = Double.Parse(v.Key.Replace(" ", string.Empty),
                                                                       System.Globalization.NumberStyles.AllowDecimalPoint,
                                                                       System.Globalization.NumberFormatInfo.InvariantInfo);
                            temp.Add(tD, tI);
                        }
                        y    = temp.Keys.ToArray();
                        x[0] = 0;
                        for (int k = 1; k < temp.Count; k++)
                        {
                            x[k] = x[k - 1] + temp.ElementAt(k - 1).Value + temp.ElementAt(k).Value;
                        }
                        probabilities[j, i] = new Spline3Deg(x, y);
                    }
                }
            }


            //do sprawdzania punktacji później
            //podzielić dane wejściowe i wygenerowane na klasy i artybuty
            var readClass  = new int[reading.Count];
            var readAttr_d = new double[reading.Count, reading.ElementAt(0).Length - 1].ToJagged();

            var stringIntCheatSheet = new Dictionary <string, int> [reading.ElementAt(0).Length];

            for (int i = 0; i < stringIntCheatSheet.Length; i++)
            {
                stringIntCheatSheet[i] = new Dictionary <string, int>();
            }

            for (int x = 0; x < reading.Count; x++)
            {
                for (int y = 0; y < reading.ElementAt(0).Length; y++)
                {
                    double rr = 0;
                    string ss = reading.ElementAt(x)[y];
                    if (!double.TryParse(ss, System.Globalization.NumberStyles.AllowDecimalPoint,
                                         System.Globalization.NumberFormatInfo.InvariantInfo, out rr) ||
                        y == 0)
                    {
                        if (!stringIntCheatSheet[y].ContainsKey(ss))
                        {
                            stringIntCheatSheet[y].Add(ss, stringIntCheatSheet[y].Count);
                        }
                        rr = stringIntCheatSheet[y][ss];
                    }
                    if (y == 0)
                    {
                        readClass[x] = (int)rr;
                    }
                    else
                    {
                        readAttr_d[x][y - 1] = rr;
                    }
                }
            }
            int readClassesSqrt = (int)Math.Round(Math.Sqrt(reading.Count)),
                genClassesSqrt, mixClassesSqrt;
            var learnKnn = new KNearestNeighbors(readClassesSqrt);

            var knn = learnKnn.Learn(readAttr_d, readClass);

            double[] attrcr = new double[attribs];


            string[] bestattr = new string[attribs];
            double   bestscore;

            //czas generować ten szajs
            var newStuff = new string[newData, attribs + 1];

            for (int it = 0; it < newStuff.GetLength(0); it++)
            {
                bestscore = 0;

                int cl = rnd.Next(classes); //rnd to zadelkarowany wcześniej Random //losowanie klasy
                newStuff[it, 0] = values.ElementAt(cl).Key;
                int safety = 0;
                do
                {
                    for (int v = 1; v <= attribs; v++)
                    {     //losowanie wartości atrybutu
                        if (attrType[v - 1].Equals("string"))
                        { //funkcja dyskretna
                            int val = rnd.Next(values.ElementAt(cl).Value.Item1);
                            int b   = 0;
                            foreach (var a in values.ElementAt(cl).Value.Item2[v])
                            {
                                if (val < (b += a.Value))
                                {
                                    newStuff[it, v] = a.Key; //na Monte Carlo
                                    break;
                                }
                            }
                        }
                        else
                        {  //funkcja ciągła
                            Tuple <double, double> extr = probabilities[cl, v - 1].Limits();
                            double val = rnd.Next((int)extr.Item1, (int)extr.Item2) + rnd.NextDouble();
                            double r   = probabilities[cl, v - 1].y(val);
                            if (attrType[v - 1].Equals("double"))
                            {
                                newStuff[it, v] = r.ToString(fltPrec, System.Globalization.CultureInfo.InvariantCulture);
                            }
                            else //if (attrType[v - 1].Equals("integer"))
                            {
                                newStuff[it, v] = Math.Round(r).ToString();
                            }
                        }//koniec losowania wartości atrybutu
                        ///ekstra warunek bezpieczeństwa, bo czasami trafiają się NULLe
                        if (string.IsNullOrEmpty(newStuff[it, v]))
                        {
                            v--;
                            continue; //jeśli atrybut ma nulla, powtórz pętlę
                        }
                        ///koniec ekstra warunku bespieczeństwa
                    }//koniec generowania obiektu


                    //do tabliczki do sprawdzenia punktacji
                    for (int v = 1; v <= attribs; v++)
                    {
                        double rr = 0;
                        string ss = newStuff[it, v];
                        if (!double.TryParse(ss, System.Globalization.NumberStyles.AllowDecimalPoint,
                                             System.Globalization.NumberFormatInfo.InvariantInfo, out rr))
                        {
                            if (!stringIntCheatSheet[v].ContainsKey(ss))
                            {
                                stringIntCheatSheet[v].Add(ss, stringIntCheatSheet[v].Count);
                            }
                            rr = stringIntCheatSheet[v][ss];
                        }
                        attrcr[v - 1] = rr;
                    }
                    if (knn.Score(attrcr, cl) > bestscore)
                    {
                        for (int iter = 0; iter < attribs; iter++)
                        {
                            bestattr[iter] = newStuff[it, iter + 1];
                        }
                    }
                } while (knn.Score(attrcr, cl) < scoreH / 100 && ++safety < 1000);

                for (int iter = 0; iter < attribs; iter++)
                {
                    newStuff[it, iter + 1] = bestattr[iter];
                }
            }//koniec całego generowania

            //tu dać zapis do pliku
            string savefiledir = "";

            using (var dirB = new System.Windows.Forms.SaveFileDialog())
            {
                dirB.Filter     = "Text Files | *.txt";
                dirB.DefaultExt = "txt";
                var res = dirB.ShowDialog();
                if (res == System.Windows.Forms.DialogResult.OK)
                {
                    using (var write = new System.IO.StreamWriter(savefiledir = dirB.FileName))
                    {
                        for (int x = 0; x < newStuff.GetLength(0); x++)
                        {
                            string line = "";
                            for (int y = 0; y < newStuff.GetLength(1); y++)
                            {
                                line += newStuff[x, y] + ',';
                            }
                            line = line.Remove(line.Length - 1);
                            string[] temp = line.Split(',');
                            generating.Add(line.Split(','));
                            swap(ref temp[0], ref temp[clsCol]);
                            line = "";
                            for (int y = 0; y < temp.Length; y++)
                            {
                                line += temp[y] + ',';
                            }
                            line = line.Remove(line.Length - 1);
                            write.WriteLine(line);
                        }
                    }
                }
                else
                {
                    return;
                }
            }
            //tu dać walidację wygenerowanych danych

            var dialogResult = System.Windows.MessageBox.Show("Do you want to test the generated data?", "Data testing - extended data", System.Windows.MessageBoxButton.YesNo);

            if (dialogResult == MessageBoxResult.Yes)
            {
                var genClass = new int[generating.Count];
                //var genAttr = new int[generating.Count, generating.ElementAt(0).Length - 1].ToJagged();
                var genAttr_d = new double[generating.Count, generating.ElementAt(0).Length - 1].ToJagged();


                for (int x = 0; x < generating.Count; x++)
                {
                    for (int y = 0; y < generating.ElementAt(0).Length; y++)
                    {
                        double rr = 0;
                        string ss = generating.ElementAt(x)[y];
                        if (!double.TryParse(ss, System.Globalization.NumberStyles.AllowDecimalPoint,
                                             System.Globalization.NumberFormatInfo.InvariantInfo, out rr) || y == 0)
                        {
                            if (!stringIntCheatSheet[y].ContainsKey(ss))
                            {
                                stringIntCheatSheet[y].Add(ss, stringIntCheatSheet[y].Count);
                            }
                            rr = stringIntCheatSheet[y][ss];
                        }
                        if (y == 0)
                        {
                            genClass[x] = (int)rr;
                        }
                        else
                        {
                            genAttr_d[x][y - 1] = rr;
                        }
                    }
                }

                //przerobienie na tablicę intów, z przesunięciem dobli o precyzję
                var genAttr_i  = new int[generating.Count, generating.ElementAt(0).Length - 1].ToJagged();
                var readAttr_i = new int[reading.Count, reading.ElementAt(0).Length - 1].ToJagged();

                int shift = (int)Math.Pow(10, FltPrecBox.SelectedIndex + 1);
                for (int x = 0; x < generating.Count; x++)
                {
                    for (int y = 0; y < generating.ElementAt(0).Length - 1; y++)
                    {
                        if (attrType[y].Equals("double"))
                        {
                            genAttr_i[x][y] = (int)(genAttr_d[x][y] * shift);
                        }
                        else
                        {
                            genAttr_i[x][y] = (int)genAttr_d[x][y];
                        }
                    }
                }
                for (int x = 0; x < reading.Count; x++)
                {
                    for (int y = 0; y < reading.ElementAt(0).Length - 1; y++)
                    {
                        if (attrType[y].Equals("double"))
                        {
                            readAttr_i[x][y] = (int)(readAttr_d[x][y] * shift);
                        }
                        else
                        {
                            readAttr_i[x][y] = (int)readAttr_d[x][y];
                        }
                    }
                }


                int correctnb = 0, incorrectnb = 0, correctknn = 0, incorrectknn = 0, correctsvm = 0, incorrectsvm = 0;

                var        learn = new NaiveBayesLearning();
                NaiveBayes nb    = learn.Learn(readAttr_i, readClass);
                var        test  = nb.Decide(genAttr_i);
                foreach (var v in test)
                {
                    if (v.Equals(genClass[test.IndexOf(v)]))
                    {
                        correctnb++;
                    }
                    else
                    {
                        incorrectnb++;
                    }
                }

                /////////////////////////////////////////////////////////////////////////

                var testknn = knn.Decide(genAttr_d);
                for (int i = 0; i < testknn.Length; i++)
                //foreach (var v in testknn)
                {
                    if (testknn[i].Equals(genClass[i]))
                    {
                        correctknn++;
                    }
                    else
                    {
                        incorrectknn++;
                    }
                }
                /////////////////////////////////////////////////////////////////////////

                try
                {
                    var teach = new MulticlassSupportVectorLearning <Gaussian>()
                    {
                        // Configure the learning algorithm to use SMO to train the
                        //  underlying SVMs in each of the binary class subproblems.
                        Learner = (param) => new SequentialMinimalOptimization <Gaussian>()
                        {
                            // Estimate a suitable guess for the Gaussian kernel's parameters.
                            // This estimate can serve as a starting point for a grid search.
                            UseKernelEstimation = true
                        }
                    };
                    var svm = teach.Learn(readAttr_d, readClass);

                    var testsvm = svm.Decide(genAttr_d);
                    for (int i = 0; i < testsvm.Length; i++)
                    //foreach (var v in testknn)
                    {
                        if (testsvm[i].Equals(genClass[i]))
                        {
                            correctsvm++;
                        }
                        else
                        {
                            incorrectsvm++;
                        }
                    }
                }
                catch (AggregateException) { }
                ////////////////////////////////////////////////////////////

                double[][] mixAttr_d = new double[genAttr_d.GetLength(0) + readAttr_d.GetLength(0),
                                                  genAttr_d[0].Length].ToJagged();
                int[] mixClass = new int[genClass.Length + readClass.Length];

                Array.Copy(readClass, mixClass, readClass.Length);
                Array.Copy(genClass, 0, mixClass, readClass.Length, genClass.Length);

                Array.Copy(readAttr_d, mixAttr_d, readAttr_d.Length);
                Array.Copy(genAttr_d, 0, mixAttr_d, readAttr_d.Length, genAttr_d.Length);

                int[][] mixAttr_i = new int[genAttr_i.GetLength(0) + readAttr_i.GetLength(0),
                                            genAttr_i[0].Length].ToJagged();

                Array.Copy(readAttr_i, mixAttr_i, readAttr_i.Length);
                Array.Copy(genAttr_i, 0, mixAttr_i, readAttr_i.Length, genAttr_i.Length);

                //KROSWALIDACJAAAAAAAAAAAAAAAAAA
                genClassesSqrt = (int)Math.Round(Math.Sqrt(genClass.Length));
                mixClassesSqrt = (int)Math.Round(Math.Sqrt(mixClass.Length));

                //KNN

                var crossvalidationRead = CrossValidation.Create(
                    k: 4,
                    learner: (p) => new KNearestNeighbors(k: readClassesSqrt),
                    loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                    fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                    x: readAttr_d, y: readClass
                    );
                var resultRead = crossvalidationRead.Learn(readAttr_d, readClass);
                // We can grab some information about the problem:
                var numberOfSamplesRead = resultRead.NumberOfSamples;
                var numberOfInputsRead  = resultRead.NumberOfInputs;
                var numberOfOutputsRead = resultRead.NumberOfOutputs;

                var trainingErrorRead   = resultRead.Training.Mean;
                var validationErrorRead = resultRead.Validation.Mean;

                var    readCM       = resultRead.ToConfusionMatrix(readAttr_d, readClass);
                double readAccuracy = readCM.Accuracy;
                //////////////////////////////////////////////////////////
                var crossvalidationGen = CrossValidation.Create(
                    k: 4,
                    learner: (p) => new KNearestNeighbors(k: genClassesSqrt),
                    loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                    fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                    x: genAttr_d, y: genClass
                    );
                var resultGen = crossvalidationGen.Learn(genAttr_d, genClass);
                // We can grab some information about the problem:
                var numberOfSamplesGen = resultGen.NumberOfSamples;
                var numberOfInputsGen  = resultGen.NumberOfInputs;
                var numberOfOutputsGen = resultGen.NumberOfOutputs;

                var    trainingErrorGen   = resultGen.Training.Mean;
                var    validationErrorGen = resultGen.Validation.Mean;
                var    genCM       = resultGen.ToConfusionMatrix(genAttr_d, genClass);
                double genAccuracy = genCM.Accuracy;
                //////////////////////////////////////////////////////////

                var crossvalidationMix = CrossValidation.Create(
                    k: 4,
                    learner: (p) => new KNearestNeighbors(k: mixClassesSqrt),
                    loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                    fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                    x: mixAttr_d, y: mixClass
                    );
                var resultMix = crossvalidationMix.Learn(readAttr_d, readClass);
                // We can grab some information about the problem:
                var numberOfSamplesMix = resultMix.NumberOfSamples;
                var numberOfInputsMix  = resultMix.NumberOfInputs;
                var numberOfOutputsMix = resultMix.NumberOfOutputs;

                var trainingErrorMix   = resultMix.Training.Mean;
                var validationErrorMix = resultMix.Validation.Mean;

                var    mixCM       = resultMix.ToConfusionMatrix(mixAttr_d, mixClass);
                double mixAccuracy = mixCM.Accuracy;

                //NB
                var crossvalidationReadnb = CrossValidation.Create(
                    k: 4,
                    learner: (p) => new NaiveBayesLearning(),
                    loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                    fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                    x: readAttr_i, y: readClass
                    );
                var resultReadnb = crossvalidationReadnb.Learn(readAttr_i, readClass);
                // We can grab some information about the problem:
                var numberOfSamplesReadnb = resultReadnb.NumberOfSamples;
                var numberOfInputsReadnb  = resultReadnb.NumberOfInputs;
                var numberOfOutputsReadnb = resultReadnb.NumberOfOutputs;

                var trainingErrorReadnb   = resultReadnb.Training.Mean;
                var validationErrorReadnb = resultReadnb.Validation.Mean;

                var    readCMnb       = resultReadnb.ToConfusionMatrix(readAttr_i, readClass);
                double readAccuracynb = readCMnb.Accuracy;
                //////////////////////////////////////////////////////////
                var crossvalidationGennb = CrossValidation.Create(
                    k: 4,
                    learner: (p) => new NaiveBayesLearning(),
                    loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                    fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                    x: genAttr_i, y: genClass
                    );
                var resultGennb = crossvalidationGennb.Learn(genAttr_i, genClass);
                // We can grab some information about the problem:
                var numberOfSamplesGennb = resultGennb.NumberOfSamples;
                var numberOfInputsGennb  = resultGennb.NumberOfInputs;
                var numberOfOutputsGennb = resultGennb.NumberOfOutputs;

                var    trainingErrorGennb   = resultGennb.Training.Mean;
                var    validationErrorGennb = resultGennb.Validation.Mean;
                var    genCMnb       = resultGennb.ToConfusionMatrix(genAttr_i, genClass);
                double genAccuracynb = genCMnb.Accuracy;
                //////////////////////////////////////////////////////////

                var crossvalidationMixnb = CrossValidation.Create(
                    k: 4,
                    learner: (p) => new NaiveBayesLearning(),
                    loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                    fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                    x: mixAttr_i, y: mixClass
                    );
                var resultMixnb = crossvalidationMixnb.Learn(mixAttr_i, mixClass);
                // We can grab some information about the problem:
                var numberOfSamplesMixnb = resultMixnb.NumberOfSamples;
                var numberOfInputsMixnb  = resultMixnb.NumberOfInputs;
                var numberOfOutputsMixnb = resultMixnb.NumberOfOutputs;

                var trainingErrorMixnb   = resultMixnb.Training.Mean;
                var validationErrorMixnb = resultMixnb.Validation.Mean;

                var    mixCMnb       = resultMixnb.ToConfusionMatrix(mixAttr_i, mixClass);
                double mixAccuracynb = mixCMnb.Accuracy;

                //SVM
                double readAccuracysvm = 0, genAccuracysvm = 0, mixAccuracysvm = 0;
                try
                {
                    var crossvalidationReadsvm = CrossValidation.Create(
                        k: 4,
                        learner: (p) => new MulticlassSupportVectorLearning <Gaussian>()
                    {
                        Learner = (param) => new SequentialMinimalOptimization <Gaussian>()
                        {
                            UseKernelEstimation = true
                        }
                    },
                        loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                        fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                        x: readAttr_d, y: readClass
                        );
                    //crossvalidationReadsvm.ParallelOptions.MaxDegreeOfParallelism = 1;
                    var resultReadsvm = crossvalidationReadsvm.Learn(readAttr_d, readClass);
                    // We can grab some information about the problem:
                    var numberOfSamplesReadsvm = resultReadsvm.NumberOfSamples;
                    var numberOfInputsReadsvm  = resultReadsvm.NumberOfInputs;
                    var numberOfOutputsReadsvm = resultReadsvm.NumberOfOutputs;

                    var trainingErrorReadsvm   = resultReadsvm.Training.Mean;
                    var validationErrorReadsvm = resultReadsvm.Validation.Mean;

                    var readCMsvm = resultReadsvm.ToConfusionMatrix(readAttr_d, readClass);
                    readAccuracysvm = readCMsvm.Accuracy;
                }
                catch (AggregateException) { }
                //////////////////////////////////////////////////////////
                try
                {
                    var crossvalidationGensvm = CrossValidation.Create(
                        k: 4,
                        learner: (p) => new MulticlassSupportVectorLearning <Gaussian>()
                    {
                        Learner = (param) => new SequentialMinimalOptimization <Gaussian>()
                        {
                            UseKernelEstimation = true
                        }
                    },
                        loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                        fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                        x: genAttr_d, y: genClass
                        );
                    var resultGensvm = crossvalidationGensvm.Learn(genAttr_d, genClass);
                    // We can grab some information about the problem:
                    var numberOfSamplesGensvm = resultGensvm.NumberOfSamples;
                    var numberOfInputsGensvm  = resultGensvm.NumberOfInputs;
                    var numberOfOutputsGensvm = resultGensvm.NumberOfOutputs;

                    var trainingErrorGensvm   = resultGensvm.Training.Mean;
                    var validationErrorGensvm = resultGensvm.Validation.Mean;
                    var genCMsvm = resultGensvm.ToConfusionMatrix(genAttr_d, genClass);
                    genAccuracysvm = genCMsvm.Accuracy;
                }
                catch (AggregateException) { }
                //////////////////////////////////////////////////////////
                try
                {
                    var crossvalidationMixsvm = CrossValidation.Create(
                        k: 4,
                        learner: (p) => new MulticlassSupportVectorLearning <Gaussian>()
                    {
                        Learner = (param) => new SequentialMinimalOptimization <Gaussian>()
                        {
                            UseKernelEstimation = true
                        }
                    },
                        loss: (actual, expected, p) => new ZeroOneLoss(expected).Loss(actual),
                        fit: (teacher, x, y, w) => teacher.Learn(x, y, w),
                        x: mixAttr_d, y: mixClass
                        );
                    var resultMixsvm = crossvalidationMixsvm.Learn(mixAttr_d, mixClass);
                    // We can grab some information about the problem:
                    var numberOfSamplesMixsvm = resultMixsvm.NumberOfSamples;
                    var numberOfInputsMixsvm  = resultMixsvm.NumberOfInputs;
                    var numberOfOutputsMixsvm = resultMixsvm.NumberOfOutputs;

                    var trainingErrorMixsvm   = resultMixsvm.Training.Mean;
                    var validationErrorMixsvm = resultMixsvm.Validation.Mean;

                    var mixCMsvm = resultMixsvm.ToConfusionMatrix(mixAttr_d, mixClass);
                    mixAccuracysvm = mixCMsvm.Accuracy;
                }
                catch (AggregateException) { }
                /////////////////////////////////////////////////
                if (correctsvm == 0 && incorrectsvm == 0)
                {
                    incorrectsvm = 1;
                }
                double knnRatio = 100.0 * correctknn / (correctknn + incorrectknn),
                       nbRatio  = 100.0 * correctnb / (correctnb + incorrectnb),
                       svmRatio = 100.0 * correctsvm / (correctsvm + incorrectsvm);
                System.Windows.MessageBox.Show(
                    "K Nearest Neighbours Classification:\nGenerated Data Correct Ratio: " +
                    knnRatio.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "%\n" +
                    "Original Data X-Validation Accuracy: "
                    + (100.0 * readAccuracy).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n" + "Generated Data X-Validation Accuracy: "
                    + (100.0 * genAccuracy).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n" + "Mixed Data X-Validation Accuracy: "
                    + (100.0 * mixAccuracy).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n"
                    + "\n\n" + "Naive Bayes Classification:\nGenerated Data Correct Ratio: " +
                    nbRatio.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "%\n" +
                    "Original Data X-Validation Accuracy: "
                    + (100.0 * readAccuracynb).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n" + "Generated Data X-Validation Accuracy: "
                    + (100.0 * genAccuracynb).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n" + "Mixed Data X-Validation Accuracy: "
                    + (100.0 * mixAccuracynb).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n" +
                    "\n\n" + "Support Vector Machine Classification:\nGenerated Data Correct Ratio: " +
                    svmRatio.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "%\n" +
                    "Original Data X-Validation Accuracy: "
                    + (100.0 * readAccuracysvm).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n" + "Generated Data X-Validation Accuracy: "
                    + (100.0 * genAccuracysvm).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n" + "Mixed Data X-Validation Accuracy: "
                    + (100.0 * mixAccuracysvm).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)
                    + "%\n",
                    "Data Testing - extending dataset",
                    System.Windows.MessageBoxButton.OK);

                /*
                 * ///TEMP - do eksportowania danych do arkusza
                 *
                 *  using (var write = new System.IO.StreamWriter("TestDataDump.txt")){
                 *      write.WriteLine("ScoreTreshold," + scoreH.ToString());
                 *      write.WriteLine("NewDataAmt," + newData.ToString());
                 *      write.WriteLine("Generated Data Correct Ratio," +
                 *          knnRatio.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
                 *          nbRatio.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) +"," +
                 *          svmRatio.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
                 *      write.WriteLine("Original Data X-Validation Accuracy," +
                 *          (100.0 * readAccuracy).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
                 *          (100.0 * readAccuracynb).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
                 *          (100.0 * readAccuracysvm).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
                 *      write.WriteLine("Generated Data X-Validation Accuracy," +
                 *          (100.0 * genAccuracy).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
                 *          (100.0 * genAccuracynb).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
                 *          (100.0 * genAccuracysvm).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
                 *  write.WriteLine("Mixed Data X-Validation Accuracy," +
                 *          (100.0 * mixAccuracy).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
                 *          (100.0 * mixAccuracynb).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," +
                 *          (100.0 * mixAccuracysvm).ToString("0.00", System.Globalization.CultureInfo.InvariantCulture));
                 *
                 * }
                 *  System.Diagnostics.Process.Start("TestDataDump.txt");
                 */
            }
            dialogResult = System.Windows.MessageBox.Show("Do you want to open the file with generated data?", "Data testing - extended data", System.Windows.MessageBoxButton.YesNo);
            if (dialogResult == MessageBoxResult.Yes)
            {
                System.Diagnostics.Process.Start(savefiledir);
            }
        }
Beispiel #49
0
        private bool SaveProject(bool SaveAs)
        {
            string saveFilename = DocumentInfo.FullPath;

            if ((String.IsNullOrEmpty(DocumentInfo.DocumentFilename)) ||
                (SaveAs))
            {
                System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();

                saveDlg.Title  = "Save Charset Project as";
                saveDlg.Filter = "Charset Projects|*.charsetproject|All Files|*.*";
                if (DocumentInfo.Project != null)
                {
                    saveDlg.InitialDirectory = DocumentInfo.Project.Settings.BasePath;
                }
                if (saveDlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return(false);
                }
                if (SaveAs)
                {
                    saveFilename = saveDlg.FileName;
                }
                else
                {
                    DocumentInfo.DocumentFilename = saveDlg.FileName;
                    if (DocumentInfo.Element != null)
                    {
                        if (string.IsNullOrEmpty(DocumentInfo.Project.Settings.BasePath))
                        {
                            DocumentInfo.DocumentFilename = saveDlg.FileName;
                        }
                        else
                        {
                            DocumentInfo.DocumentFilename = GR.Path.RelativePathTo(saveDlg.FileName, false, System.IO.Path.GetFullPath(DocumentInfo.Project.Settings.BasePath), true);
                        }
                        DocumentInfo.Element.Name      = System.IO.Path.GetFileNameWithoutExtension(DocumentInfo.DocumentFilename);
                        DocumentInfo.Element.Node.Text = System.IO.Path.GetFileName(DocumentInfo.DocumentFilename);
                        DocumentInfo.Element.Filename  = DocumentInfo.DocumentFilename;
                    }
                    saveFilename = DocumentInfo.FullPath;
                }
            }

            if (!SaveAs)
            {
                m_Charset.Name      = DocumentInfo.DocumentFilename;
                m_Charset.UsedTiles = GR.Convert.ToU32(editCharactersFrom.Text);
            }

            if (IsBinaryFile())
            {
                // save binary only!
                GR.Memory.ByteBuffer charSet = new GR.Memory.ByteBuffer();
                charSet.Reserve(256 * 8);

                for (int i = 0; i < 256; ++i)
                {
                    charSet.Append(m_Charset.Characters[i].Data);
                }
                DisableFileWatcher();
                if (!GR.IO.File.WriteAllBytes(saveFilename, charSet))
                {
                    EnableFileWatcher();
                    return(false);
                }
                SetUnmodified();
                EnableFileWatcher();
                return(true);
            }
            GR.Memory.ByteBuffer projectFile = SaveToBuffer();

            return(SaveDocumentData(saveFilename, projectFile, SaveAs));
        }
        private void lnkDownload_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            lnkDownload.Enabled = false;

            #region   範本
            // 當沒有設定檔
            if (_Configure == null)
            {
                return;
            }

            string reportName = "高雄領域補考通知單範本";

            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Reports");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, reportName + ".doc");

            if (File.Exists(path))
            {
                int i = 1;
                while (true)
                {
                    string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                    if (!File.Exists(newPath))
                    {
                        path = newPath;
                        break;
                    }
                }
            }

            try
            {
                // 檢查目前範本是否 Null,當Null使用預設
                if (_Configure.Template == null)
                {
                    _Configure.Template = new Document(new MemoryStream(Properties.Resources.領域補考通知單範本));
                }

                _Configure.Template.Save(path, Aspose.Words.SaveFormat.Doc);
                System.Diagnostics.Process.Start(path);
            }
            catch
            {
                System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
                sd.Title    = "另存新檔";
                sd.FileName = reportName + ".doc";
                sd.Filter   = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        _Configure.Template.Save(sd.FileName, Aspose.Words.SaveFormat.Doc);
                    }
                    catch
                    {
                        FISCA.Presentation.Controls.MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                }
            }

            #endregion
            lnkDownload.Enabled = true;
        }
Beispiel #51
0
        /// <summary>
        /// Displays the character exportation window and then exports it.
        /// </summary>
        /// <param name="character"></param>
        public static void ExportCharacter(Character character)
        {
            // Open the dialog box
            using (var characterSaveDialog = new System.Windows.Forms.SaveFileDialog())
            {
                characterSaveDialog.Title       = "Save Character Info";
                characterSaveDialog.Filter      = "Text Format|*.txt|HTML Format|*.html|XML Format (CCP API)|*.xml|XML Format (EVEMon)|*.xml|PNG Image|*.png";
                characterSaveDialog.FileName    = character.Name;
                characterSaveDialog.FilterIndex = (int)CharacterSaveFormat.CCPXML;

                var result = characterSaveDialog.ShowDialog();
                if (result == DialogResult.Cancel)
                {
                    return;
                }

                // Serialize
                try
                {
                    // Save file to the chosen format and to a temp file
                    string tempFileName        = Path.GetTempFileName();
                    CharacterSaveFormat format = (CharacterSaveFormat)characterSaveDialog.FilterIndex;
                    switch (format)
                    {
                    case CharacterSaveFormat.HTML:
                        File.WriteAllText(tempFileName, CharacterExporter.ExportAsHTML(character), Encoding.UTF8);
                        break;

                    case CharacterSaveFormat.CCPXML:
                        var content = CharacterExporter.ExportAsCCPXML(character);
                        if (content == null)
                        {
                            MessageBox.Show("This character has never been downloaded from CCP, cannot find it in the XML cache.", "Cannot export the character", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        File.WriteAllText(tempFileName, content, Encoding.UTF8);
                        break;

                    case CharacterSaveFormat.EVEMonXML:
                        File.WriteAllText(tempFileName, CharacterExporter.ExportAsEVEMonXML(character), Encoding.UTF8);
                        break;

                    case CharacterSaveFormat.Text:
                        File.WriteAllText(tempFileName, CharacterExporter.ExportAsText(character), Encoding.UTF8);
                        break;

                    case CharacterSaveFormat.PNG:
                        var monitor = Program.MainWindow.GetCurrentMonitor();
                        var bmp     = monitor.GetCharacterScreenshot();
                        bmp.Save(tempFileName, System.Drawing.Imaging.ImageFormat.Png);
                        break;

                    default:
                        throw new NotImplementedException();
                    }

                    // Writes to our file
                    FileHelper.OverwriteOrWarnTheUser(tempFileName, characterSaveDialog.FileName, OverwriteOperation.Move);
                }
                // Handle exception
                catch (IOException exc)
                {
                    ExceptionHandler.LogException(exc, true);
                    MessageBox.Show("A problem occured during exportation. The operation has not been completed.");
                }
            }
        }
Beispiel #52
0
        public void ExportDataToExcel(List <StudInfoEntity> StudInfoEntityList)
        {
            Workbook  wb  = new Workbook();
            Worksheet wst = wb.Worksheets[0];

            wst.Name = "學生基本學力資料";
            Dictionary <string, int> ColumnIdx = new Dictionary <string, int>();

            ColumnIdx.Add("考區/考場代碼", 0);
            ColumnIdx.Add("學校代碼", 1);
            ColumnIdx.Add("報名序號", 2);
            ColumnIdx.Add("學號", 3);
            ColumnIdx.Add("班級", 4);
            ColumnIdx.Add("座號", 5);
            ColumnIdx.Add("學生姓名", 6);
            ColumnIdx.Add("身分證號", 7);
            ColumnIdx.Add("性別", 8);
            ColumnIdx.Add("出生年", 9);
            ColumnIdx.Add("出生月", 10);
            ColumnIdx.Add("出生日", 11);
            ColumnIdx.Add("畢業學校代碼", 12);
            ColumnIdx.Add("畢業年度", 13);
            ColumnIdx.Add("畢肄業", 14);
            ColumnIdx.Add("學生身分", 15);
            ColumnIdx.Add("身心障礙", 16);
            ColumnIdx.Add("分發區", 17);
            ColumnIdx.Add("低收入戶", 18);
            ColumnIdx.Add("失業勞工子女", 19);
            //ColumnIdx.Add("中低收入戶", 20);
            ColumnIdx.Add("資料授權", 20);
            ColumnIdx.Add("家長姓名", 21);
            ColumnIdx.Add("緊急連絡電話", 22);
            ColumnIdx.Add("郵遞區號", 23);
            ColumnIdx.Add("地址", 24);
            ColumnIdx.Add("手機", 25);

            // 標頭
            foreach (KeyValuePair <string, int> val in ColumnIdx)
            {
                wst.Cells[0, val.Value].PutValue(val.Key);
            }
            int RowIdx = 1;

            // 設欄寬
            if (StudInfoEntityList.Count > 0)
            {
                // default
                wst.Cells.SetColumnWidth(0, 2);
                wst.Cells.SetColumnWidth(2, 5);
                wst.Cells.SetColumnWidth(17, 2);
                wst.Cells.SetColumnWidth(20, 1);

                foreach (KeyValuePair <string, int> val in ColumnIdx)
                {
                    if (StudInfoEntityList[0].GetDataCellEntity(val.Key).FieldLenght > 0)
                    {
                        wst.Cells.SetColumnWidth(val.Value, StudInfoEntityList[0].GetDataCellEntity(val.Key).FieldLenght);
                    }
                }
            }

            foreach (StudInfoEntity sie in StudInfoEntityList)
            {
                foreach (KeyValuePair <string, int> ColIdx in ColumnIdx)
                {
                    if ((ColIdx.Value >= 2 && ColIdx.Value <= 5) || ColIdx.Value >= 9 && ColIdx.Value <= 11)
                    {
                        wst.Cells[RowIdx, ColIdx.Value].Style.HorizontalAlignment = TextAlignmentType.Right;
                    }
                    else
                    {
                        wst.Cells[RowIdx, ColIdx.Value].Style.HorizontalAlignment = TextAlignmentType.Left;
                    }

                    wst.Cells[RowIdx, ColIdx.Value].PutValue(sie.GetDataCellEntity(ColIdx.Key).Value);
                }
                RowIdx++;
            }



            try
            {
                wb.Save(Application.StartupPath + "\\Reports\\學生基本學力資料.xls", FileFormatType.Excel2003);
                System.Diagnostics.Process.Start(Application.StartupPath + "\\Reports\\學生基本學力資料.xls");
            }
            catch
            {
                System.Windows.Forms.SaveFileDialog sd1 = new System.Windows.Forms.SaveFileDialog();
                sd1.Title    = "另存新檔";
                sd1.FileName = "學生基本學力資料.xls";
                sd1.Filter   = "Excel檔案 (*.xls)|*.xls|所有檔案 (*.*)|*.*";
                if (sd1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        wb.Save(sd1.FileName, FileFormatType.Excel2003);
                        System.Diagnostics.Process.Start(sd1.FileName);
                    }
                    catch
                    {
                        System.Windows.Forms.MessageBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                }
            }
        }
Beispiel #53
0
        private string GetSaveFilePath()
        {
            var workSaveFileDialog = new oForms.SaveFileDialog();

            return(workSaveFileDialog.ShowDialog() != oForms.DialogResult.OK ? workSaveFileDialog.FileName : null);
        }
Beispiel #54
0
        /// <summary>
        /// 匯出合併欄位總表Word
        /// </summary>
        public static void ExportMappingFieldWord()
        {
            #region 儲存檔案
            string inputReportName = "學期成績單合併欄位總表";
            string reportName      = inputReportName;

            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Reports");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, reportName + ".doc");

            if (File.Exists(path))
            {
                int i = 1;
                while (true)
                {
                    string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                    if (!File.Exists(newPath))
                    {
                        path = newPath;
                        break;
                    }
                }
            }

            Document tempDoc = new Document(new MemoryStream(Properties.Resources.學期成績單合併欄位總表));

            try
            {
                #region 動態產生合併欄位
                // 讀取總表檔案並動態加入合併欄位
                Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(tempDoc);
                builder.MoveToDocumentEnd();

                List <string> plist = K12.Data.PeriodMapping.SelectAll().Select(x => x.Type).Distinct().ToList();
                List <string> alist = K12.Data.AbsenceMapping.SelectAll().Select(x => x.Name).ToList();
                builder.Writeln();
                builder.Writeln();
                builder.Writeln("缺曠動態產生合併欄位");
                builder.StartTable();

                builder.InsertCell();
                builder.Write("缺曠名稱與合併欄位");
                builder.EndRow();

                foreach (string pp in plist)
                {
                    foreach (string aa in alist)
                    {
                        string key = pp.Replace(" ", "_") + "_" + aa.Replace(" ", "_");

                        builder.InsertCell();
                        builder.Write(key);
                        builder.InsertCell();
                        builder.InsertField("MERGEFIELD " + key + " \\* MERGEFORMAT ", "«" + key + "»");
                        builder.EndRow();
                    }
                }

                builder.EndTable();

                builder.Writeln();
                builder.Writeln("缺曠總計(不分節次類型)合併欄位");
                builder.StartTable();

                foreach (string aa in alist)
                {
                    string key = aa.Replace(" ", "_") + "總計";
                    builder.InsertCell();
                    builder.Write(key);
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + key + " \\* MERGEFORMAT ", "«" + key + "»");
                    builder.EndRow();
                }
                builder.EndTable();


                // 日常生活表現
                builder.Writeln();
                builder.Writeln();
                builder.Writeln("日常生活表現評量");
                builder.StartTable();
                builder.InsertCell();
                builder.Write("分類");
                builder.InsertCell();
                builder.Write("名稱");
                builder.InsertCell();
                builder.Write("建議內容");
                builder.EndRow();

                foreach (string key in DLBehaviorRef.Keys)
                {
                    builder.InsertCell();
                    builder.Write(key);
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + key + "_Name" + " \\* MERGEFORMAT ", "«" + key + "名稱»");
                    builder.InsertCell();
                    // 新竹版沒有
                    if (key != "日常生活表現程度")
                    {
                        builder.InsertField("MERGEFIELD " + key + "_Description" + " \\* MERGEFORMAT ", "«" + key + "建議內容»");
                    }

                    builder.EndRow();
                }
                builder.EndTable();

                // 日常生活表現
                builder.Writeln();
                builder.Writeln();
                builder.Writeln("日常生活表現評量子項目");
                builder.StartTable();
                builder.InsertCell();
                builder.Write("項目");
                builder.InsertCell();
                builder.Write("指標");
                builder.InsertCell();
                builder.Write("表現程度");
                builder.EndRow();

                for (int i = 1; i <= 7; i++)
                {
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + "日常生活表現程度_Item_Name" + i + " \\* MERGEFORMAT ", "«項目" + i + "»");
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + "日常生活表現程度_Item_Index" + i + " \\* MERGEFORMAT ", "«指標" + i + "»");
                    builder.InsertCell();
                    builder.InsertField("MERGEFIELD " + "日常生活表現程度_Item_Degree" + i + " \\* MERGEFORMAT ", "«表現" + i + "»");
                    builder.EndRow();
                }

                builder.EndTable();



                // 動態計算領域
                List <JHSemesterScoreRecord> SemesterScoreRecordList = JHSemesterScore.SelectBySchoolYearAndSemester(_SelStudentIDList, _SelSchoolYear, _SelSemester);

                // 領域名稱
                List <string> DomainNameList = new List <string>();

                foreach (JHSemesterScoreRecord SemsScore in SemesterScoreRecordList)
                {
                    foreach (string dn in SemsScore.Domains.Keys)
                    {
                        if (!DomainNameList.Contains(dn))
                        {
                            DomainNameList.Add(dn);
                        }
                    }
                }
                DomainNameList.Sort(new StringComparer("語文", "數學", "社會", "自然與生活科技", "健康與體育", "藝術與人文", "綜合活動"));
                DomainNameList.Add("彈性課程");

                List <string> m1  = new List <string>();
                List <string> m2a = new List <string>();
                List <string> m2b = new List <string>();

                m1.Add("班排名");
                m1.Add("年排名");
                m1.Add("類別1排名");
                m1.Add("類別2排名");

                m2a.Add("rank");
                m2a.Add("matrix_count");
                m2a.Add("pr");
                m2a.Add("percentile");
                m2a.Add("avg_top_25");
                m2a.Add("avg_top_50");
                m2a.Add("avg");
                m2a.Add("avg_bottom_50");
                m2a.Add("avg_bottom_25");
                m2a.Add("pr_88");
                m2a.Add("pr_75");
                m2a.Add("pr_50");
                m2a.Add("pr_25");
                m2a.Add("pr_12");
                m2a.Add("std_dev_pop");
                m2b.Add("level_gte100");
                m2b.Add("level_90");
                m2b.Add("level_80");
                m2b.Add("level_70");
                m2b.Add("level_60");
                m2b.Add("level_50");
                m2b.Add("level_40");
                m2b.Add("level_30");
                m2b.Add("level_20");
                m2b.Add("level_10");
                m2b.Add("level_lt10");


                // 領域排名 排名、母數、五標
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域成績排名 排名、母數、五標";
                    builder.Writeln(dn);
                    builder.StartTable();
                    builder.InsertCell();
                    builder.Write("名稱");
                    builder.InsertCell();
                    builder.Write("排名");
                    builder.InsertCell();
                    builder.Write("排名母數");
                    builder.InsertCell();
                    builder.Write("PR");
                    builder.InsertCell();
                    builder.Write("百分比");
                    builder.InsertCell();
                    builder.Write("頂標");
                    builder.InsertCell();
                    builder.Write("高標");
                    builder.InsertCell();
                    builder.Write("均標");
                    builder.InsertCell();
                    builder.Write("低標");
                    builder.InsertCell();
                    builder.Write("底標");
                    builder.InsertCell();
                    builder.Write("新頂標");
                    builder.InsertCell();
                    builder.Write("新前標");
                    builder.InsertCell();
                    builder.Write("新均標");
                    builder.InsertCell();
                    builder.Write("新後標");
                    builder.InsertCell();
                    builder.Write("新底標");
                    builder.InsertCell();
                    builder.Write("標準差");
                    builder.EndRow();
                    foreach (string m in m1)
                    {
                        builder.InsertCell();
                        builder.Write(m);
                        foreach (string nn in m2a)
                        {
                            string dd = dName + "領域成績_" + m + "_" + nn;
                            builder.InsertCell();
                            builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R»");
                        }
                        builder.EndRow();
                    }

                    builder.EndTable();
                }


                // 領域(原始)排名 排名、母數、五標
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域成績(原始)排名 排名、母數、五標";
                    builder.Writeln(dn);
                    builder.StartTable();
                    builder.InsertCell();
                    builder.Write("名稱");
                    builder.InsertCell();
                    builder.Write("排名");
                    builder.InsertCell();
                    builder.Write("排名母數");
                    builder.InsertCell();
                    builder.Write("PR");
                    builder.InsertCell();
                    builder.Write("百分比");
                    builder.InsertCell();
                    builder.Write("頂標");
                    builder.InsertCell();
                    builder.Write("高標");
                    builder.InsertCell();
                    builder.Write("均標");
                    builder.InsertCell();
                    builder.Write("低標");
                    builder.InsertCell();
                    builder.Write("底標");
                    builder.InsertCell();
                    builder.Write("新頂標");
                    builder.InsertCell();
                    builder.Write("新前標");
                    builder.InsertCell();
                    builder.Write("新均標");
                    builder.InsertCell();
                    builder.Write("新後標");
                    builder.InsertCell();
                    builder.Write("新底標");
                    builder.InsertCell();
                    builder.Write("標準差");
                    builder.EndRow();
                    foreach (string m in m1)
                    {
                        builder.InsertCell();
                        builder.Write(m);
                        foreach (string nn in m2a)
                        {
                            string dd = dName + "領域成績(原始)_" + m + "_" + nn;
                            builder.InsertCell();
                            builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R»");
                        }
                        builder.EndRow();
                    }

                    builder.EndTable();
                }


                // 領域排名 組距
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域成績排名 組距";
                    builder.Writeln(dn);
                    builder.StartTable();
                    builder.InsertCell();
                    builder.Write("名稱");
                    builder.InsertCell();
                    builder.Write("100以上");
                    builder.InsertCell();
                    builder.Write("90以上小於100");
                    builder.InsertCell();
                    builder.Write("80以上小於90");
                    builder.InsertCell();
                    builder.Write("70以上小於80");
                    builder.InsertCell();
                    builder.Write("60以上小於70");
                    builder.InsertCell();
                    builder.Write("50以上小於60");
                    builder.InsertCell();
                    builder.Write("40以上小於50");
                    builder.InsertCell();
                    builder.Write("30以上小於40");
                    builder.InsertCell();
                    builder.Write("20以上小於30");
                    builder.InsertCell();
                    builder.Write("10以上小於20");
                    builder.InsertCell();
                    builder.Write("10以下");
                    builder.EndRow();
                    foreach (string m in m1)
                    {
                        builder.InsertCell();
                        builder.Write(m);
                        foreach (string nn in m2b)
                        {
                            string dd = dName + "領域成績_" + m + "_" + nn;
                            builder.InsertCell();
                            builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R»");
                        }
                        builder.EndRow();
                    }

                    builder.EndTable();
                }

                // 領域排名(原始) 組距
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域成績(原始)排名 組距";
                    builder.Writeln(dn);
                    builder.StartTable();
                    builder.InsertCell();
                    builder.Write("名稱");
                    builder.InsertCell();
                    builder.Write("100以上");
                    builder.InsertCell();
                    builder.Write("90以上小於100");
                    builder.InsertCell();
                    builder.Write("80以上小於90");
                    builder.InsertCell();
                    builder.Write("70以上小於80");
                    builder.InsertCell();
                    builder.Write("60以上小於70");
                    builder.InsertCell();
                    builder.Write("50以上小於60");
                    builder.InsertCell();
                    builder.Write("40以上小於50");
                    builder.InsertCell();
                    builder.Write("30以上小於40");
                    builder.InsertCell();
                    builder.Write("20以上小於30");
                    builder.InsertCell();
                    builder.Write("10以上小於20");
                    builder.InsertCell();
                    builder.Write("10以下");
                    builder.EndRow();
                    foreach (string m in m1)
                    {
                        builder.InsertCell();
                        builder.Write(m);
                        foreach (string nn in m2b)
                        {
                            string dd = dName + "領域成績(原始)_" + m + "_" + nn;
                            builder.InsertCell();
                            builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R»");
                        }
                        builder.EndRow();
                    }

                    builder.EndTable();
                }

                // 領域-科目排名 排名、母數、五標
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域-科目成績排名 排名、母數、五標";
                    builder.Writeln(dn);
                    builder.StartTable();
                    foreach (string m in m1)
                    {
                        builder.Writeln(m);
                        builder.InsertCell();
                        builder.Write("名稱");
                        builder.InsertCell();
                        builder.Write("排名");
                        builder.InsertCell();
                        builder.Write("排名母數");
                        builder.InsertCell();
                        builder.Write("PR");
                        builder.InsertCell();
                        builder.Write("百分比");
                        builder.InsertCell();
                        builder.Write("頂標");
                        builder.InsertCell();
                        builder.Write("高標");
                        builder.InsertCell();
                        builder.Write("均標");
                        builder.InsertCell();
                        builder.Write("低標");
                        builder.InsertCell();
                        builder.Write("底標");
                        builder.InsertCell();
                        builder.Write("新頂標");
                        builder.InsertCell();
                        builder.Write("新前標");
                        builder.InsertCell();
                        builder.Write("新均標");
                        builder.InsertCell();
                        builder.Write("新後標");
                        builder.InsertCell();
                        builder.Write("新底標");
                        builder.InsertCell();
                        builder.Write("標準差");
                        builder.EndRow();

                        for (int i = 1; i <= 12; i++)
                        {
                            builder.InsertCell();
                            string dsn = dName + "_科目排名名稱" + i;
                            builder.InsertField("MERGEFIELD " + dsn + " \\* MERGEFORMAT ", "«N" + i + "»");
                            foreach (string nn in m2a)
                            {
                                string dd = dName + "_科目成績" + i + "_" + m + "_" + nn;
                                builder.InsertCell();
                                builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R" + i + "»");
                            }
                            builder.EndRow();
                        }
                    }

                    builder.EndTable();
                }

                // 領域-科目排名 排名、母數、五標
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域-科目成績(原始)排名 排名、母數、五標";
                    builder.Writeln(dn);
                    builder.StartTable();
                    foreach (string m in m1)
                    {
                        builder.Writeln(m);
                        builder.InsertCell();
                        builder.Write("名稱");
                        builder.InsertCell();
                        builder.Write("排名");
                        builder.InsertCell();
                        builder.Write("排名母數");
                        builder.InsertCell();
                        builder.Write("PR");
                        builder.InsertCell();
                        builder.Write("百分比");
                        builder.InsertCell();
                        builder.Write("頂標");
                        builder.InsertCell();
                        builder.Write("高標");
                        builder.InsertCell();
                        builder.Write("均標");
                        builder.InsertCell();
                        builder.Write("低標");
                        builder.InsertCell();
                        builder.Write("底標");
                        builder.InsertCell();
                        builder.Write("新頂標");
                        builder.InsertCell();
                        builder.Write("新前標");
                        builder.InsertCell();
                        builder.Write("新均標");
                        builder.InsertCell();
                        builder.Write("新後標");
                        builder.InsertCell();
                        builder.Write("新底標");
                        builder.InsertCell();
                        builder.Write("標準差");
                        builder.EndRow();

                        for (int i = 1; i <= 12; i++)
                        {
                            builder.InsertCell();
                            string dsn = dName + "_科目排名名稱" + i;
                            builder.InsertField("MERGEFIELD " + dsn + " \\* MERGEFORMAT ", "«N" + i + "»");
                            foreach (string nn in m2a)
                            {
                                string dd = dName + "_科目成績(原始)" + i + "_" + m + "_" + nn;
                                builder.InsertCell();
                                builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R" + i + "»");
                            }
                            builder.EndRow();
                        }
                    }

                    builder.EndTable();
                }

                // 領域-科目排名 組距
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域-科目成績排名 組距";
                    builder.Writeln(dn);
                    builder.StartTable();
                    foreach (string m in m1)
                    {
                        builder.Writeln(m);
                        builder.InsertCell();
                        builder.Write("名稱");
                        builder.InsertCell();
                        builder.Write("100以上");
                        builder.InsertCell();
                        builder.Write("90以上小於100");
                        builder.InsertCell();
                        builder.Write("80以上小於90");
                        builder.InsertCell();
                        builder.Write("70以上小於80");
                        builder.InsertCell();
                        builder.Write("60以上小於70");
                        builder.InsertCell();
                        builder.Write("50以上小於60");
                        builder.InsertCell();
                        builder.Write("40以上小於50");
                        builder.InsertCell();
                        builder.Write("30以上小於40");
                        builder.InsertCell();
                        builder.Write("20以上小於30");
                        builder.InsertCell();
                        builder.Write("10以上小於20");
                        builder.InsertCell();
                        builder.Write("10以下");
                        builder.EndRow();

                        for (int i = 1; i <= 12; i++)
                        {
                            builder.InsertCell();
                            string dsn = dName + "_科目排名名稱" + i;
                            builder.InsertField("MERGEFIELD " + dsn + " \\* MERGEFORMAT ", "«N" + i + "»");
                            foreach (string nn in m2b)
                            {
                                string dd = dName + "_科目成績" + i + "_" + m + "_" + nn;
                                builder.InsertCell();
                                builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R" + i + "»");
                            }
                            builder.EndRow();
                        }
                    }

                    builder.EndTable();
                }

                // 領域-科目(原始)排名 組距
                foreach (string dName in DomainNameList)
                {
                    builder.Writeln();
                    builder.Writeln();
                    string dn = dName + "領域-科目成績(原始)排名 組距";
                    builder.Writeln(dn);
                    builder.StartTable();
                    foreach (string m in m1)
                    {
                        builder.Writeln(m);
                        builder.InsertCell();
                        builder.Write("名稱");
                        builder.InsertCell();
                        builder.Write("100以上");
                        builder.InsertCell();
                        builder.Write("90以上小於100");
                        builder.InsertCell();
                        builder.Write("80以上小於90");
                        builder.InsertCell();
                        builder.Write("70以上小於80");
                        builder.InsertCell();
                        builder.Write("60以上小於70");
                        builder.InsertCell();
                        builder.Write("50以上小於60");
                        builder.InsertCell();
                        builder.Write("40以上小於50");
                        builder.InsertCell();
                        builder.Write("30以上小於40");
                        builder.InsertCell();
                        builder.Write("20以上小於30");
                        builder.InsertCell();
                        builder.Write("10以上小於20");
                        builder.InsertCell();
                        builder.Write("10以下");
                        builder.EndRow();

                        for (int i = 1; i <= 12; i++)
                        {
                            builder.InsertCell();
                            string dsn = dName + "_科目排名名稱" + i;
                            builder.InsertField("MERGEFIELD " + dsn + " \\* MERGEFORMAT ", "«N" + i + "»");
                            foreach (string nn in m2b)
                            {
                                string dd = dName + "_科目成績(原始)" + i + "_" + m + "_" + nn;
                                builder.InsertCell();
                                builder.InsertField("MERGEFIELD " + dd + " \\* MERGEFORMAT ", "«R" + i + "»");
                            }
                            builder.EndRow();
                        }
                    }

                    builder.EndTable();
                }

                #endregion
                tempDoc.Save(path, SaveFormat.Doc);

                System.Diagnostics.Process.Start(path);
            }
            catch
            {
                System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
                sd.Title    = "另存新檔";
                sd.FileName = reportName + ".doc";
                sd.Filter   = "Word檔案 (*.doc)|*.doc|所有檔案 (*.*)|*.*";
                if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        tempDoc.Save(sd.FileName, SaveFormat.Doc);
                    }
                    catch
                    {
                        FISCA.Presentation.Controls.MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        return;
                    }
                }
            }
            #endregion
        }
        public static void CompletedXlsCsv(string inputReportName, DataTable dt)
        {
            #region 儲存檔案
            string reportName = inputReportName;

            string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Reports");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, reportName + ".csv");

            if (File.Exists(path))
            {
                int i = 1;
                while (true)
                {
                    string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                    if (!File.Exists(newPath))
                    {
                        path = newPath;
                        break;
                    }
                }
            }

            // StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.Unicode);
            StreamWriter sw        = new StreamWriter(path, false, System.Text.Encoding.Default);
            DataTable    dataTable = dt;

            List <string> strList = new List <string>();
            foreach (DataColumn dc in dt.Columns)
            {
                strList.Add(dc.ColumnName);
            }

            sw.WriteLine(string.Join(",", strList.ToArray()));

            foreach (DataRow dr in dt.Rows)
            {
                List <string> subList = new List <string>();
                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    subList.Add(dr[col].ToString());
                }
                sw.WriteLine(string.Join(",", subList.ToArray()));
            }

            sw.Close();
            try
            {
                System.Diagnostics.Process.Start("notepad.exe", path);
                //System.Diagnostics.Process.Start(path);
            }
            catch
            {
                try
                {
                    System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
                    sd.Title    = "另存新檔";
                    sd.FileName = reportName + ".csv";
                    sd.Filter   = "csv檔案 (*.csv)|*.txt|所有檔案 (*.*)|*.*";
                    if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        System.Diagnostics.Process.Start(sd.FileName);
                    }
                }
                catch
                {
                    FISCA.Presentation.Controls.MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    return;
                }
            }
            #endregion
        }
Beispiel #56
0
        private void exportStringsToFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // Find all lstring that are internalized and rewrite to
            var plugin = GetPluginFromNode(this.PluginTree.SelectedRecord);

            if (plugin == null)
            {
                MessageBox.Show(Resources.NoPluginSelected, Resources.ErrorText);
                return;
            }

            var lstrings = new LocalizedStrings
            {
                Strings = plugin.Strings.Select(x => new LocalizedString {
                    ID = x.Key, Type = LocalizedStringFormat.Base, Value = x.Value
                })
                          .Union(plugin.DLStrings.Select(x => new LocalizedString {
                    ID = x.Key, Type = LocalizedStringFormat.DL, Value = x.Value
                }))
                          .Union(plugin.ILStrings.Select(x => new LocalizedString {
                    ID = x.Key, Type = LocalizedStringFormat.IL, Value = x.Value
                }))
                          .ToArray()
            };

            if (lstrings.Strings.Length == 0)
            {
                MessageBox.Show("No strings available to export.", Resources.ErrorText);
                return;
            }

            using (var dlg = new System.Windows.Forms.SaveFileDialog())
            {
                if (string.IsNullOrEmpty(Properties.Settings.Default.DefaultSaveFolder) ||
                    !Directory.Exists(Properties.Settings.Default.DefaultSaveFolder))
                {
                    dlg.InitialDirectory = Path.Combine(Program.gameDataDir, "Strings");
                }
                else
                {
                    dlg.InitialDirectory = Path.Combine(Properties.Settings.Default.DefaultSaveFolder, "Strings");
                }
                dlg.DefaultExt      = ".xml";
                dlg.Filter          = "String Table|*.xml";
                dlg.CheckPathExists = true;
                dlg.AddExtension    = true;
                dlg.OverwritePrompt = true;
                dlg.FileName        = string.Format("{0}_{1}.xml"
                                                    , Path.GetFileNameWithoutExtension(plugin.Name)
                                                    , Properties.Settings.Default.LocalizationName);
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    var xs = new XmlSerializer(typeof(LocalizedStrings));
                    using (var tw = new XmlTextWriter(dlg.FileName, System.Text.Encoding.Unicode))
                    {
                        tw.Formatting = Formatting.Indented;
                        xs.Serialize(tw, lstrings);
                    }
                }
            }
        }
Beispiel #57
0
        private void linkLabel_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
        {
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                LinkLabel lb = sender as LinkLabel;
                Activity  ac = listBox1.Items[i] as Activity;

                if (LinkLabel.ReferenceEquals(lb, ac.linkLabel))
                {
                    if (ac.TransferState == TransferStatus.CONFIRM_RECIVE)
                    {
                        FileInfo fi = null;
                        try
                        {
                            bool gotFile = true;
                            do
                            {
                                saveFileDialog.FileName = ac.fileTransfer.FileName;
                                DialogResult fileDialogResult = saveFileDialog.ShowDialog(this);

                                if (fileDialogResult == DialogResult.OK)
                                {
                                    fi = new FileInfo(saveFileDialog.FileName);
                                    if (fi.Exists)
                                    {
                                        bool canContinue;
                                        if (fi.Length < ac.fileTransfer.FileSize)
                                        {
                                            canContinue = true;
                                        }
                                        else
                                        {
                                            canContinue = false;
                                        }

                                        ResumeDownloadDialog rs     = new ResumeDownloadDialog(fi.Name, canContinue);
                                        DialogResult         result = rs.ShowDialog();

                                        /*MessageBox.Show("Filen " + fi.Name + " finns redan. Men har inte blivit helt nerladdad!\n"+
                                         *      "Vill du försöka fortsätta nerladdningen där den slutade sist? \n" +
                                         *      "Om inte så kommer nerladdningen börja om från början och filen kommer skrivas över!",
                                         *      "File Prompt", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);*/

                                        if (result == DialogResult.OK)
                                        {
                                            ReciveFile rc = (ReciveFile)ac.fileTransfer;
                                            rc.ResumeTransfer(fi.FullName, fi.Length);
                                        }
                                        else if (result == DialogResult.Abort)
                                        {
                                            fi.Delete();
                                            MessageBox.Show("File Deleted");

                                            ReciveFile rc = (ReciveFile)ac.fileTransfer;
                                            rc.StartTransfer(fi.FullName);
                                        }
                                        else if (result == DialogResult.Cancel)
                                        {
                                            //MessageBox.Show("Leta ny fil");
                                            gotFile = false;
                                        }
                                    }
                                    else
                                    {
                                        ReciveFile rc = (ReciveFile)ac.fileTransfer;
                                        rc.StartTransfer(saveFileDialog.FileName);
                                    }
                                }
                                else if (fileDialogResult == DialogResult.Cancel)
                                {
                                    /// Didnt get the file, but do nothing
                                    gotFile = true;
                                }
                            }while(gotFile != true);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "Transfer Error");
                            if (ac != null)
                            {
                                ac.fileTransfer.close();
                            }
                        }

                        /*finally
                         * {
                         *
                         * }*/
                    }
                    else if (ac.TransferState != TransferStatus.FILE_RECIVING)
                    {
                        listBox1.Items.Remove(ac);
                        listBox1.Controls.Remove(lb);
                    }
                    else
                    {
                        ac.fileTransfer.close();
                        lb.Text = "Ta Bort";
                    }
                    listBox1.Refresh();
                }
            }
        }
        private void BgExportData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                MsgBox.Show("產生資料發生錯誤..," + e.Error.Message);
            }
            else
            {
                Workbook wb = (Workbook)e.Result;

                if (wb != null)
                {
                    #region 儲存檔案
                    string reportName = K12.Data.School.DefaultSchoolYear + "學年度第" + K12.Data.School.DefaultSemester + "學期 技職繁星報名檔";

                    string path = Path.Combine(System.Windows.Forms.Application.StartupPath, "Reports");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    path = Path.Combine(path, reportName + ".xls");

                    try
                    {
                        if (File.Exists(path))
                        {
                            int i = 1;
                            while (true)
                            {
                                string newPath = Path.GetDirectoryName(path) + "\\" + Path.GetFileNameWithoutExtension(path) + (i++) + Path.GetExtension(path);
                                if (!File.Exists(newPath))
                                {
                                    path = newPath;
                                    break;
                                }
                            }
                        }
                        wb.Save(path, SaveFormat.Excel97To2003);
                        System.Diagnostics.Process.Start(path);
                    }
                    catch
                    {
                        System.Windows.Forms.SaveFileDialog sd = new System.Windows.Forms.SaveFileDialog();
                        sd.Title    = "另存新檔";
                        sd.FileName = reportName + ".xls";
                        sd.Filter   = "Excel檔案 (*.xls)|*.xls|所有檔案 (*.*)|*.*";
                        if (sd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            try
                            {
                                wb.Save(sd.FileName, SaveFormat.Excel97To2003);
                            }
                            catch
                            {
                                FISCA.Presentation.Controls.MsgBox.Show("指定路徑無法存取。", "建立檔案失敗", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                                return;
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    MsgBox.Show("Excel 檔案無法產生。");
                }
            }

            btnExport.Enabled = true;
            FISCA.Presentation.MotherForm.SetStatusBarMessage("");
        }